psycopg.OperationalError:连接失败:Docker中的连接被拒绝

omvjsjqw  于 2023-02-07  发布在  Docker
关注(0)|答案(1)|浏览(151)

所以我试着把我的Docker应用程序(python-1)连接到另一个Docker应用程序(postgres),但是它给了我这个错误:

psycopg.OperationalError: connection failed: Connection refused
python-1            |   Is the server running on host "localhost" (127.0.0.1) and accepting
python-1            |   TCP/IP connections on port 25432?

我试过使用condition: service_healthy,但它不起作用。事实上,我已经确保我的数据库在python-1尝试连接之前运行。但问题似乎不是数据库还没有打开。我已经使用0.0.0.0或postgres容器的IP在主机上使用postgres,它也不起作用。
这是我的docker-compose.yml

version: "3.8"
services:
  postgres:
    image: postgres:14.6
    ports:
        - 25432:5432
    healthcheck:
      test: ["CMD-SHELL", "PGPASSWORD=${DB_PASSWORD}", "pg_isready", "-U", "${DB_USERNAME}", "-d", "${DB_NAME}"]
      interval: 30s
      timeout: 60s
      retries: 5
      start_period: 80s  
    environment:
      POSTGRES_USER: ${DB_USERNAME}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: ${DB_NAME}
  python:
    build:
        context: .
        dockerfile: Dockerfile
    depends_on:
        postgres:
          condition: service_healthy
    command: flask --app app init-db && flask --app app run -h 0.0.0.0 -p ${PORT}
    ports:
        - ${PORT}:${PORT}
    environment:
      DB_HOST: localhost
      DB_PORT: 25432
      DB_NAME: ${DB_NAME}
      DB_USERNAME: ${DB_USERNAME}
      DB_PASSWORD: ${DB_PASSWORD}

这是我的Dockerfile:

# syntax=docker/dockerfile:1

FROM python:3.10

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .
jexiocij

jexiocij1#

在容器中,localhost表示容器本身。
Docker网络上的不同container可以使用服务名作为主机名进行通信。同样,在Docker网络上,您可以使用未Map的端口号。
因此,将环境变量更改为

environment:
  DB_HOST: postgres
  DB_PORT: 5432

你应该能和他交流。

相关问题