Benjamin Lu

everyday is cool

Debugging DNS Inside a Docker Container

When a container says it cannot reach a database, test from the app container. A successful lookup on the Docker host may use a different resolver and tells you little about the app’s network.

This example assumes a Compose project with an app service and a PostgreSQL service named db on port 5432. Run the commands from the directory containing your Compose file and substitute your service names and port.

1. Check the services and resolve the name

docker compose ps
docker compose exec app getent hosts db
docker compose exec app cat /etc/resolv.conf

The lookup should return an address for db. If getent is absent, use nslookup db if the image provides it. A missing command tells you only that the image lacks that tool. If both services are running and the name still fails, check whether the containers share a network.

docker inspect --format '{{json .NetworkSettings.Networks}}' \
  "$(docker compose ps -q app)"
docker inspect --format '{{json .NetworkSettings.Networks}}' \
  "$(docker compose ps -q db)"

Look for a network name in both outputs. A service on a shared Compose network can use the other service’s name. Use the port the database listens on inside its container. For example, a mapping of 15432:5432 still means the app connects to db:5432.

2. Test the connection

If the app image provides netcat, try:

docker compose exec app nc -vz -w 3 db 5432

A successful TCP connection confirms that the name resolved and the port accepted a connection. Test next with the app’s database client to check credentials, database name, and TLS settings. A refusal usually points to the listener or port. A timeout calls for checking the network path and filtering rules.

3. Confirm the app is using the same endpoint

Check the hostname and port in the app configuration without printing credentials. In a normal Compose setup, localhost inside app refers to app itself. If the app points to localhost:5432 while the database runs in db, change the hostname in the app configuration, apply it, and repeat the app’s original request.

Docker Compose networking