Opscraft
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, localhost means that container itself. "Connection refused to localhost:5432" from the API means it should use db.
  • 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 name worker resolves to all three IPs (DNS round robin).
Enlarge diagramNETWORK: SHOP_DEFAULTapiconnects todb:5432dblistens on 5432your browserlocalhost:8080db:5432localhost:5432 from api = api itself: connection refusedpublished port
Figure 1. Inside a container, localhost means that container. Services talk to each other by service name on the project network, using container ports.
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 diagramFRONTENDBACKEND (INTERNAL)webnginxapion bothdbpostgresinternal: true also blocks the backend network from reaching the internet.
Figure 2. Two networks give three tiers: web reaches api, api reaches db, and web can never reach db directly.
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.