Data and networking
Connect containers by name
Place services on a user-defined network and use Docker DNS instead of hard-coded container IP addresses.
8 minute lesson
Container IP addresses are implementation details and can change when containers are replaced. Stable service names are a better connection contract.
A user-defined Docker network includes DNS-based name resolution. Containers on that network can use another container’s name as a hostname. They connect to the other container’s internal port, not its published host port.
docker network create notes-net
docker run --name database --network notes-net -d postgres:17-alpine
docker run --rm --network notes-net alpine ping -c 1 database
Inside the API container, localhost means the API container itself. To reach PostgreSQL, use database:5432: the service name and the port on which PostgreSQL listens inside its container. Publishing 5432 on the host is unnecessary for this connection and expands the exposed surface.
Docker DNS follows container and network membership, so replacement containers can receive new IP addresses without changing application configuration. Name resolution is discovery, not authentication or encryption. Still use database credentials, restrict which services join each network, and add transport security when the threat model requires it.
Create the network and confirm the temporary client resolves database. Remove the practice containers after the check.
Lesson completed