Docker Compose Networking: How Services Talk to Each Other
Docker Compose puts your services on a private network, letting them communicate using service names as hostnames. This is how a 'web' container finds your 'db' container. The footgun is using `localhost`; always use the service name for inter-container calls.
WHY IT EXISTS Manually managing container networking is tedious, requiring you to create networks, attach containers, and handle IP addresses. Docker Compose networking automates this entire process, allowing multi-service applications to communicate with each other out-of-the-box.
THE MENTAL MODEL Think of docker-compose up as creating a private, isolated LAN for your application. Every service defined in your docker-compose.yml file is plugged into this LAN. Docker provides a built-in DNS service on this private network, so containers can find each other by their service name, just like you'd use google.com on the public internet.
HOW IT WORKS When you run docker-compose up, Compose first creates a default network for your project, typically named yourproject_default. Then, as it starts a container for each service (e.g., 'api', 'db'), it attaches each one to this network. Because they share a network, Docker's internal DNS resolver lets them find each other by name. A request from your 'api' container to the hostname 'db' will automatically resolve to the internal IP address of the 'db' container.
WHEN TO USE IT This is the default and desired behavior for nearly all multi-service applications using Docker Compose. It's the foundation for running microservices or any application with separate components (like a web server and a database) in a local development environment.
WHEN NOT TO USE IT You might override the default networking only in specific cases. For example, if you need to connect a container to a pre-existing network that wasn't created by Compose, or if you need to connect services across multiple, separate docker-compose.yml files. For most use cases, the default is correct.
ONE CANONICAL EXAMPLE Consider a docker-compose.yml with two services: 'api' and 'db'. The 'api' service needs to connect to the 'db' service. Inside the 'api' container's code, the database connection string should use 'db' as the hostname, like postgres://user:pass@db:5432. You should NOT use localhost or an IP address. Because both services are on the same Compose-managed network, the 'api' container can resolve the hostname 'db' to the database container's IP address automatically.
Read the original → docs.docker.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.