0

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 . . 

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It still gives me the same error ``` psycopg.OperationalError: connection failed: Connection refused python-1 | Is the server running on host "postgres" (192.168.16.2) and accepting python-1 | TCP/IP connections on port 25432? ```
Solved. I port forward my port like this 15432:5432 the left one is for outside the container and the right one is for the container. So when I use postgres host I should use 5432 port. I missed that part. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.