我在 .netcore 和 postgres 的 docker-compose 中做错了什么?

mrG*_*own 6 postgresql docker docker-compose

我在这个问题上摸索了一段时间,找不到问题所在。在 Windows 10 上运行 Docker Desktop。我有一个连接到 postgres 的 dotnetcore 3.1 api。这两个都在容器中运行。

除了与数据库的连接之外,一切似乎都正常。由于我查看了 docker-compose.yml 一百万次,我想不出任何其他想法。

这是我的连接字符串:

"Server=postgres;Port=5432;Database=IdentityManager;User Id=postgres;Password=12345678;"
Run Code Online (Sandbox Code Playgroud)

这是 docker-compose.yml 文件:

version: '3'

services:
  identityserver:
    depends_on: 
      - "postgres"
    container_name: identityserver
    build:
      context: ./my_project/
      dockerfile: Dockerfile
    environment: 
      - ASPNETCORE_ENVIRONMENT='Development'
    ports: 
      - "5000:80"

  postgres:
    image: "postgres"
    container_name: "postgres"
    restart: always
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=12345678
      - POSTGRES_DB=IdentityManager
    expose: 
      - "5432"
Run Code Online (Sandbox Code Playgroud)

一切都建立起来,但与数据库的连接失败:

Unhandled exception. Npgsql.NpgsqlException (0x80004005): Exception while connecting identityserver 
---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (99): Cannot assign requested address [::1]:5432
Run Code Online (Sandbox Code Playgroud)

最奇怪的是,当我在 docker-compose.yml 上使用相同的配置单独运行 postgres 时,并使用稍微不同的连接字符串在容器外部运行应用程序:

"Server=127.0.0.1;Port=5432;Database=IdentityManager;User Id=postgres;Password=12345678;"
Run Code Online (Sandbox Code Playgroud)

我能够连接到数据库。

我尝试清理所有内容docker system prune -a,尝试重新启动 Docker,重新启动 PC,但没有成功。有人可以尝试帮忙吗?

mrG*_*own 9

最后,我能够解决我自己的问题,而且它docker-compose.yml根本不在文件中。在应用程序代码中的某个位置,连接字符串已更改为查找 localhost 而不是 postgres 作为主机。

改回postgres后,一切正常。

  • 感谢基督。非常感谢你做的这些。我真是个大白痴。花了2个小时寻找这个问题的解决方案。 (2认同)