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

3

在执行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?

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:

在应用程序的 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 = *'。但是我不知道如何处理这个问题。

VVK Kumar表示他的问题从未得到解决。"已回答"框指向的解决方案并没有使用docker-compose。因此,我在这里添加这个评论来澄清在这种情况下使用docker-compose的步骤。@bug的答案部分正确:主机必须是服务名称db。然而,这还不够,因为Kumar试图通过端口5433进行连接,而postgres正在监听端口5432。YAML文件的ports部分只将本地端口连接到容器端口。要使pg监听端口5433,请在service db中添加command: postgres -p 5433 - ChrisFal
1个回答

8
每个Docker容器都是独立的主机,这意味着您无法使用localhostdcs_web访问Postgres,而必须使用默认的Postgres容器主机名。该主机名默认为在Docker Compose文件中定义服务的名称,在您的情况下即为db
config.ini中将localhost替换为db,然后应该就可以工作了。

我按照你说的方法尝试了,但是出现了错误。sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) 无法连接到服务器:连接被拒绝 服务器是否在主机 "db" (1XX.XX.XX.X) 上运行,并且接受来自端口 5433 的 TCP/IP 连接? - VVK kumar
这可能是因为当应用程序尝试连接到Postgres时,它仍在启动中。最佳实践是使用类似wait-for-it的工具等待服务启动。您可以在这里找到更多详细信息。 - bug
但是我得到的日志是'2019-11-28 06:00:45.801 UTC [1] LOG: 数据库系统已准备好接受连接',但在此之后才出现了上述错误。 - VVK kumar
| /entrypoint.sh:/app/wait-for-it.sh: /bin/sh^M:bad interpreter: No such file or directory |/entrypoint.sh: line 39:/app/wait-for-it.sh: Success | 2019-11-28 06:22:35.878UTC[1]LOG:listening on IPv4 address"0.0.0.0",port 5432 | 2019-11-28 06:22:35.878UTC[1]LOG:listening on IPv6 address "::",port 5432 | 2019-11-28 06:22:38.217UTC[1]LOG:listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" | 2019-11-28 06:22:38.859UTC[24]LOG:database system was shut down at 2019-11-28 06:13:19 UTC | 2019-11-28 06:22:38.911UTC[1]LOG:database system is ready to accept connections |exited with code 127 - VVK kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接