是否可以有一个具有相同连接字符串的 API 在本地和 Docker 中运行?这将使我能够在访问 Docker 中的数据库时调试代码,并在 Docker 中运行所有内容,而无需任何额外的配置
"ConnectionStrings": {
"Database": "Host=postgres-db;Port=5432;Database=database;Username=postgres;Password=postgres;Include Error Detail=true"
},
docker-compose.yaml
version: '3.4'
services:
example-api:
image: ${DOCKER_REGISTRY-}api
container_name: example-api
restart: always
build:
context: .
dockerfile: src/Api/Dockerfile
depends_on:
- postgres-db
postgres-db:
image: postgres:14.1
container_name: postgres-db
restart: always
environment:
- POSTGRES_DB=database
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
volumes:
- postgres:/data/postgres
ports:
- 5100:5432
您的
docker-compose.yaml
已将 postgres-db
容器的端口 5432
映射到主机上的 5100
。这样,您就可以使用 localhost:5100
作为主机和端口从本地计算机访问数据库。将您的连接字符串修改为:
"ConnectionStrings": {
"Database": "Host=localhost;Port=5100;Database=database;Username=postgres;Password=postgres;Include Error Detail=true"
}
只需确保
example-api
可以正确解析 localhost
,或将主机设置为 postgres-db
,因为 Docker Compose 网络中的任何服务都可以使用名称 postgres-db
作为主机名来访问 postgres-db
服务。