Interview Q&A / Docker & Kubernetes

IntermediateQuick answer1 min readUpdated 3 Oct 2026

Why does localhost inside a container not reach a database running on your laptop?

SHORT ANSWER

Inside a container, localhost means the container itself, not the host. To reach a host service use host.docker.internal (Docker Desktop, or with --add-host on Linux), or put both on a Docker network and use the service name.

Explain it simply

Every container has its own private network, like each flat having its own 'home'. When a program in flat A says 'go to home', it means flat A, not the building's security cabin.

So if your app container connects to localhost:5432, it looks for Postgres inside that same container and gets 'connection refused'. Options: (1) run the database as another container on the same user-defined network and connect to db:5432; (2) for a service on the host machine, use host.docker.internal, which Docker Desktop provides; on Linux add --add-host=host.docker.internal:host-gateway; (3) as a last resort use --network host on Linux.

Also check that the host service listens on an address reachable from Docker, not only on 127.0.0.1.

Example

bash
# inside container, this fails:
#   postgres://localhost:5432/app
# better:
docker run --add-host=host.docker.internal:host-gateway myapp
#   postgres://host.docker.internal:5432/app
# or use another container:  postgres://db:5432/app

What to say in the interview

"localhost inside a container is the container itself. I point to a database container by service name on a shared network, or use host.docker.internal for a service on the host machine."

Common mistakes

  • Changing the database config to 0.0.0.0 on the app side; the app should call the db's address, and the db should listen on 0.0.0.0.

#docker#networking#localhost

Related questions

Practise more Docker & Kubernetes questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Docker & Kubernetes quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.