psycopg2 cannot resolve the host name db in Docker Compose
psycopg2.OperationalError: could not translate host name "db" to addressShort answer
Compose registers each service in its own DNS under the service name, but only containers on the same Compose network can look it up. The error means the process doing the lookup is not one of them: it runs on your host, sits on another network, or uses a name that is not the service key. Run it in the project, or use localhost and the published port.
Fix it fast
1Find out which cause you have
Find out where the failing Python process runs. If it runs in a container started by this Compose project, go to causes 2 and 3. If you start it from your own terminal, it is cause 1.
docker compose ps docker compose config2Match what you see, then jump to its fix
- 1
The error appears when you run python from your own terminal or IDE, while the same code works inside the app containerThe script runs on your machine, not inside a Compose containerFix - 2
The app container is in the project, but the compose file lists custom networks under each serviceThe app and the database are on different networksFix - 3
The compose file names the service something else, for example postgres or databaseThe host name is not the service keyFix - 4
The first start fails and a restart worksThe app starts before the database is readyFix
- 1
What does the error look like?
psycopg2.OperationalError: could not translate host name "db" to addresscould not translate host name "db" to addresscould not translate host name "db" to address: Temporary failure in name resolution
Cause 1 of 4
The script runs on your machine, not inside a Compose container
1Check
The name db exists only in the DNS server that Compose gives to its containers. Your host does not use it. From outside, you reach the database through the host port in the ports mapping.
docker compose ps2Fix
Publish the database port in the compose file and connect to localhost on the host side of the mapping. Keep db as the host name in the settings that the containers use.
# compose.yaml
services:
db:
image: postgres:17
ports:
- "5433:5432"
# script run from your terminal
psycopg2.connect(host="localhost", port=5433, dbname="app", user="app", password="secret")3Verify
Connect once from your terminal with the host and port you chose.
python -c "import psycopg2; psycopg2.connect(host='localhost', port=5433, dbname='app', user='app', password='secret').close(); print('ok')"Confirmed by docs.docker.com
Cause 2 of 4
The app and the database are on different networks
1Check
Containers can talk only when they share a network. If the app lists one network and db lists another, the name never resolves. Print the merged file and compare the networks key of both services.
docker compose config2Fix
Put both services on a common network, or remove the networks keys so both use the default one.
services:
app:
networks: [backend]
db:
networks: [backend]
networks:
backend: {}3Verify
Recreate the stack and start the app again.
docker compose up -dConfirmed by docs.docker.com
Cause 3 of 4
The host name is not the service key
1Check
Each service is registered under the name of its key in the services section. Read the key in the file and compare it with the host in the connection string.
docker compose config2Fix
Use the service key as the host. To keep an old name working, add it as a link on the service that needs it; the linked service then answers to both names.
services:
app:
links:
- "db:database"3Verify
Restart the app and connect using the service key.
docker compose up -dConfirmed by docs.docker.com
Cause 4 of 4
The app starts before the database is ready
1Check
depends_on alone only waits for the container to start. Compose documents a healthcheck with condition service_healthy to wait until the database accepts connections.
docker compose logs db --tail 202Fix
Add a healthcheck to the database and make the app wait for it.
services:
db:
image: postgres:16
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
retries: 5
web:
depends_on:
db:
condition: service_healthy3Verify
docker compose up starts web only after db is healthy.
docker compose up -d && docker compose psConfirmed by docs.docker.com
How do I stop it coming back?
- Read the host from an environment variable, so the container and your terminal can use different values.
- Inside containers always use the container port (5432), not the published host port.
- Add a healthcheck with pg_isready and depends_on with condition service_healthy, so the app starts when the database accepts connections.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- Dispatch ProA real-time logistics platform: Flutter apps, Spring Boot services and a Kafka event pipeline on AWS.
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
Related fixes
Databases
python manage.py migrate finishes but the tables for my app are missing
relation "myapp_book" does not exist
migrate only applies migration files that exist.
3 causes, each with a fixDatabases
Django save fails on PostgreSQL: null value in a column violates a not-null constraint
django.db.utils.IntegrityError: null value in column "price" of relation "shop_product" violates not-null constraint
A model field is NOT NULL in the database unless it has null=True.
3 causes, each with a fixDatabases
Django migration on PostgreSQL stops with 'pending trigger events'
django.db.utils.OperationalError: cannot ALTER TABLE "mytable" because it has pending trigger events
PostgreSQL runs a Django migration in one transaction.
2 causes, each with a fixDatabases
Django cannot connect to PostgreSQL: connection refused on port 5432, locally or in Docker
Is the server running on that host and accepting TCP/IP connections?
Connection refused means nothing accepted the connection at the host and port Django used.
4 causes, each with a fixDatabases
EF Core says 'transient failure' when it cannot reach PostgreSQL in Docker
The query fails only after a delay, because the connection is retried several times
The transient failure message comes from EF Core's retry layer, which hides the underlying connection error.
3 causes, each with a fixDatabases
A Postgres query in Docker fails with: could not resize shared memory segment
ERROR: could not resize shared memory segment: No space left on device
Postgres in a container hands query memory to parallel workers through the container's /dev/shm.
2 causes, each with a fix