🌐 Networks
Networks: A Docker network is an office phone directory: containers on the same network call each other by NAME (extension 'db'), instead of memorizing desk coordinates (IP addre
A Docker network is an office phone directory: containers on the same network call each other by NAME (extension 'db'), instead of memorizing desk coordinates (IP addresses that change on every restart). Why does Docker insist on name-based discovery instead of letting you hardcode container IPs? For the same reason Java code depends on interfaces instead of concrete classes: the implementation (IP) can be swapped on every restart while the contract (service name) stays stable. This is the single most common beginner failure in QA automation: your test container calls localhost:5432 and gets 'connection refused' — but localhost inside a container is the container ITSELF, not your machine. Put the test and the database on one network and dial 'db:5432' — call the directory, not the desk.
Container networking
🎬 Why Doesn't "localhost:5432" Work? — The View From Inside a Container
Connected via db:5432
The test container tries to reach the database at `localhost:5432` — this always worked on the laptop, so it is the habit.
IT BLOWS UP: `Connection refused`. Because inside a container, "localhost" points to the container ITSELF, not the host machine — and nothing in that container listens on port 5432.
Contrast — the office phone-directory metaphor: instead of memorizing a desk number (IP), you call by name (extension). `docker network create qa-network` sets up this directory.
The db and test containers join the SAME network: `--network qa-network`. Now both are listed in the same directory — they can find each other by name.
The test now dials `db:5432` instead of `localhost:5432` — typing the container NAME is like dialing the extension. Docker resolves this name to an IP automatically via DNS.
Final — the Java bridge: code depending on a fixed IP is like code depending on a concrete class — the implementation can change on every restart. Depending on a service NAME is depending on an interface: the contract stays stable.
Practice: Build a safe docker run command
Study the complete command in the reference above, then fill the blanks in the editor: write -d, --name, -p, and -v flags in the right order.
Container Command Lifecycle
If the image is missing locally, docker pull downloads it, or docker run does this automatically.