.NET应用通过Docker Compose连接PostgreSQL失败求助
.NET Docker Compose连接PostgreSQL失败的解决办法
问题详情
运行基于.NET的应用和PostgreSQL的Docker Compose栈时,出现数据库连接错误,报错信息:
appdemo-service | System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. appdemo-service | ---> Npgsql.NpgsqlException (0x80004005): Failed to connect to [::1]:5433 appdemo-service | ---> System.Net.Sockets.SocketException (99): Cannot assign requested address appdemo-service | at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.CreateException(SocketError error, Boolean forAsyncThrow)
使用的Docker Compose配置:
version: '3.4' networks: dev: driver: bridge services: app-demo: image: docker.io/library/appdemo depends_on: - "app_db" container_name: appdemo-service ports: - "5009:80" build: context: . dockerfile: Dockerfile environment: - ConnectionStrings__DefaultConnection=User ID =postgres;Password=postgres;Server=localhost;Port=5433;Database=SampleDriverDb; Integrated Security=true;Pooling=true; - ASPNETCORE_URLS=http://+:80 networks: - dev app_db: image: postgres:latest container_name: app_db environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=SampleDriverDb ports: - "5433:5432" restart: always volumes: - app_data:/var/lib/postgresql/data networks: - dev volumes: app_data:
错误原因及修复步骤
1. 容器间访问不能用localhost
Docker Compose自定义网络中,容器需通过服务名互相访问。app-demo容器内的localhost指向容器自身,而非数据库容器。
- 修复:将连接字符串中的
Server=localhost改为Server=app_db(对应PostgreSQL服务的名称)
2. 端口使用错误
数据库容器内部PostgreSQL默认端口为5432,ports: "5433:5432"是宿主机端口到容器端口的映射,容器间访问直接用容器内部端口即可。
- 修复:将连接字符串中的
Port=5433改为Port=5432
3. 移除无效参数
PostgreSQL不支持Integrated Security=true(该参数属于SQL Server),会干扰连接逻辑。
- 修复:删除连接字符串中的
Integrated Security=true;
4. 可选:处理数据库启动延迟
depends_on仅保证容器启动顺序,不确保数据库服务就绪。可添加健康检查或启动脚本,让应用等待数据库就绪:
app_db: # ... 其他配置 healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 app-demo: # ... 其他配置 depends_on: app_db: condition: service_healthy
修改后的连接字符串
最终app-demo服务的环境变量应改为:
environment: - ConnectionStrings__DefaultConnection=User ID=postgres;Password=postgres;Server=app_db;Port=5432;Database=SampleDriverDb;Pooling=true; - ASPNETCORE_URLS=http://+:80
内容的提问来源于stack exchange,提问作者wandos
相关产品推荐
相关产品推荐

