Why localhost in a container is not your machine

Network namespaces in one page

127.0.0.1 belongs to a network namespace. A process in a different one is looking at a different loopback.

Linux can separate network resources with network namespaces. Each namespace has its own routing tables, network devices and port space. So 127.0.0.1 means the loopback of the namespace the process lives in.

Example

An API and a database run in different network namespaces. The API connects to 127.0.0.1:5432. It is looking for a database inside its own namespace. It needs a target reachable over the network to get to the other one.

What to ask

The container boundary alone is not the answer. Ask which network namespace the process runs in, and whether it shares that namespace with other processes.

Check yourself

Two processes listen on 127.0.0.1:3000 in different namespaces. Do they collide? Not on that port: port spaces are isolated. That does not mean nothing else is shared between them.

This is also why a dotless hostname that only resolves inside a container network fails from a process on the host. Same family of mistake: right name, wrong place to look it up.

Tagged: linux, networking, containers, docker

Area: Systems and Networking

Related notes

עברית