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

时间:2019-11-27 13:55:01

标签: python docker flask docker-compose psycopg2

做docker-compose时出现错误。

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?

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:

在App config.ini中:

[DEFAULT]
DB_NAME = user
DB_PASSWORD = admin
DB_USER = postgres
DB_HOST = localhost
DB_PORT = 5433
DEBUG = True

我已经遍历了'/ var / lib / postgresql / data'位置'listen adress = *'在那儿。不知道该如何处理。

1 个答案:

答案 0 :(得分:0)

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

在您的localhost中将db替换为config.ini,它应该可以工作。