Two services can't talk: they're on different Docker networks
Medium

Problem

The api service is up but can't reach the database. Its log repeats could not translate host name "db" to address: Name or service not known. The db container is healthy and accepting connections. Both are running — they just can't find each other by name. Get api able to resolve and reach db.

Initial setup

  • apimyapp:latest, Up, retrying its DB connection.
  • dbpostgres:15-alpine, Up, healthy.
  • Two user-defined networks exist; the two containers are not on the same one.

Example interaction

$ docker exec api getent hosts db
(no output, exit 2 — the name doesn't resolve)

$ docker network inspect frontend     # which containers are here?
$ docker network inspect backend

The name db won't resolve because Docker's embedded DNS only answers for names on the same user-defined network.

Acceptance

You've solved it when:

  • You've established the failure is DNS scoping across networksapi
and db are on different user-defined networks, so db returns Name or service not known / NXDOMAIN — and NOT a DB-down, credentials, or depends_on race issue.
  • You've put them on a shared network (`docker network connect frontend
db, or attach api to backend) so docker exec api getent hosts db` resolves and api can reach db.

Constraints

  • Tools: docker CLI only.
  • Hardcoding db's IP "fixes" it until the next restart re-assigns the IP —
put them on a shared network instead.

Follow-up

  1. Why does the legacy default bridge network NOT give name resolution,
while a user-defined bridge does?
  1. In a compose file, what's the idiomatic way to let two services on
different networks talk (a shared/external network)?
  1. Why is attaching db to frontend safer than hardcoding its container IP?
Live session
Code
SavedNo commands yet