alramdein
alramdein

Reputation: 901

psycopg.OperationalError: connection failed: Connection refused in Docker

so I tried to connect my docker app (python-1) into another docker app (postgres). But it giving me this error:

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?

I've tried using condition: service_healthy but it doesn't work. In fact, I already make sure my database is running before python-1 is trying to connect. But the problem seems not about the database hasn't turned on yet. I already use 0.0.0.0 or postgres container's IP using postgres on the host and it also doesn't work.

Here is my 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}
  

And this is my Dockerfile:

# syntax=docker/dockerfile:1

FROM python:3.10

WORKDIR /app

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

COPY . .

Upvotes: 0

Views: 389

Answers (1)

Hans Kilian
Hans Kilian

Reputation: 25120

In a container, localhost means the container itself.

Different containers on a docker network can communicate using the service names as host names. Also, on the docker network, you use the unmapped port numbers.

So change your environment variables to

environment:
  DB_HOST: postgres
  DB_PORT: 5432

and you should be able to connect.

Upvotes: 2

Related Questions