【问题标题】:psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" [duplicate]psycopg2.OperationalError:无法连接到服务器:连接被拒绝服务器是否在主机“localhost”上运行[重复]
【发布时间】:2019-11-27 13:55:01
【问题描述】:

执行 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:

在 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' location 'listen adress = *' is there 。不知道如何处理。

【问题讨论】:

  • VVK kumar 在下面声明他的问题从未得到解决。 “已回答”框指向不使用 docker-compose 的解决方案。因此,我添加此评论以阐明在这种情况下使用 docker-compose 的步骤。 @bug 的答案部分正确:主机必须是服务名称db。但是,这还不够,因为 Kumar 尝试通过端口 5433 进行连接,而 postgres 正在侦听端口 5432。YAML 的端口部分仅将本地端口连接到容器端口。要使 pg 侦听端口 5433,请将 command: postgres -p 5433 添加到服务数据库。

标签: python docker flask docker-compose psycopg2


【解决方案1】:

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

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

【讨论】:

  • 我按照你说的做了,但出错了。 sqlalchemy.exc.OperationalError:(psycopg2.OperationalError)无法连接到服务器:连接被拒绝服务器是否在主机“db”(1XX.XX.XX.X)上运行并接受端口 5433 上的 TCP/IP 连接?
  • 这可能是因为当应用程序尝试连接到 Postgres 时,它仍在启动。最好使用wait-for-it 等工具来等待服务启动。 Here您可以找到更多详细信息。
  • 但是我得到了类似'2019-11-28 06:00:45.801 UTC [1] LOG: database system is ready to accept connections'之类的日志,但在此之后只得到了上述错误。
  • | /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 : 成功 | 2019-11-28 06:22:35.878UTC[1]LOG:监听 IPv4 地址“0.0.0.0”,端口 5432 | 2019-11-28 06:22:35.878UTC[1]LOG:监听 IPv6 地址“::”,端口 5432 | 2019-11-28 06:22:38.217UTC[1]LOG:监听 Unix 套接字“/var/run/postgresql/.s.PGSQL.5432”| 2019-11-28 06:22:38.859UTC[24]LOG:数据库系统于 2019-11-28 06:13:19 UTC 关闭 | 2019-11-28 06:22:38.911UTC[1]LOG:数据库系统已准备好接受连接|以代码 127 退出
猜你喜欢
  • 1970-01-01
  • 2018-10-12
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
相关资源
最近更新 更多