psycopg2.OperationalError:无法连接到服务器:连接被拒绝服务器是否在主机“localhost”上运行

VVK*_*mar 4 python psycopg2 flask docker docker-compose

执行 docker-compose up 时出错。

conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5433?
could not connect to server: Cannot assign requested address
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5433?
Run Code Online (Sandbox Code Playgroud)

docker-compose.yml:-

version: '3'

services:
  dcs_web:
    build: .
    depends_on:
      - db
    ports:
      - "5000:5000"
  db:
    image: postgres:latest
    volumes:
      - db-data:/var/lib/postgresql/data
    ports:
      - "5433:5433"
    environment:
      - 'POSTGRES_DB:dcmDB'
      - 'POSTGRES_USER:postgres'
      - 'POSTGRES_PASSWORD:admin'

volumes:
  db-data:
Run Code Online (Sandbox Code Playgroud)

在应用程序config.ini中:

[DEFAULT]
DB_NAME = user
DB_PASSWORD = admin
DB_USER = postgres
DB_HOST = localhost
DB_PORT = 5433
DEBUG = True
Run Code Online (Sandbox Code Playgroud)

我已经浏览过 '/var/lib/postgresql/data' 位置 'listen adress = *' 就在那里。不知道如何处理这个问题。

bug*_*bug 9

Docker 中的每个容器都是一个单独的主机,这意味着您无法通过dcs_web使用来访问 Postgres localhost,您必须使用 Postgres 容器的主机名,默认情况下是 Docker Compose 文件中定义的服务名称,在您的案件:db

替换localhostdb你的config.ini,它应该可以工作。