Docker Compose · Lesson 4 of 10 · 3 min read
Networking between services
The default network and service discovery
Compose creates <project>_default and attaches every service to it. Docker's embedded DNS (127.0.0.11) resolves each service name to the IPs of that service's containers. So the API connects to db:5432, the worker to redis:6379.
- Inside a container,
localhostmeans that container itself. "Connection refused to localhost:5432" from the API means it should usedb. - Use the container port for service-to-service traffic, not the published host port.
- From your laptop's browser or tools, you reach services through published ports:
localhost:8080. - With
--scale worker=3, the nameworkerresolves to all three IPs (DNS round robin).
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.
Custom networks and isolation
services:
web: { image: nginx, networks: [frontend] }
api: { build: ./api, networks: [frontend, backend] }
db: { image: postgres:16, networks: [backend] }
networks:
frontend: {}
backend:
internal: true # no outbound internet access
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.
web can reach api but not db; db can't reach the internet. Aliases give a service extra names on a network:
networks:
backend:
aliases: [database, postgres.local]
External networks let separate Compose projects talk: create a network once (docker network create shared) and declare it with external: true in each project.
Reaching the host from a container
On Docker Desktop, host.docker.internal resolves to the host. On Linux add extra_hosts: ["host.docker.internal:host-gateway"]. Useful when a service runs on your machine outside Compose.