Skip to content

DevOps Operations / Docker Compose · Step 3 of 6

Lesson: Service DiscoverySwitch
← DevOps Operations

Delivery and containers

Service Discovery

Let containers find each other by service name on a Compose network.

A web application usually needs to reach a database or cache in another container. Container IP addresses can change when containers are recreated, so you should not write them into your configuration. Compose gives you names instead.

The default network

When you run docker compose up, Compose creates a network for the project, named after it with _default added. Each service joins that network, and Docker's built-in DNS resolves a service name to the address of its container.

yaml
services:
  web:
    image: nginx:alpine
    ports:
      - "8080:80"
  cache:
    image: redis:alpine

From inside web, the name cache resolves:

bash
docker compose exec web getent hosts cache
172.18.0.2        cache  cache

Your address and the exact name columns may differ. If DNS ideas are new to you, read the networking basics guide.

Container ports, not published ports

Services on the same network talk directly to each other's container ports. web reaches Redis at cache:6379 even though cache has no ports entry. Publishing a port is only needed when something outside that network, such as your browser, must connect.

Suppose a database service is published as "15432:5432". Other containers use db:5432. Programs on the host use localhost:15432.

Inside a container, localhost means that container itself. An application that tries localhost:6379 from web will not find Redis.

Separate networks

You can define your own networks to limit who can talk to whom:

yaml
services:
  proxy:
    image: nginx:alpine
    networks: [front]
  app:
    image: nginx:alpine
    networks: [front, back]
  db:
    image: redis:alpine
    networks: [back]
networks:
  front:
  back:

proxy can reach app, and app can reach db. proxy and db share no network, so proxy cannot resolve or reach db by name.

Try it

Start the two-service example, then run the getent command from web. Next, run docker compose exec cache redis-cli -h cache ping and expect PONG. Finally, put the two services on different networks, run docker compose up -d, and repeat the lookup. It should now print nothing.

Check your understanding

Service Discovery

All 3 sections · no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.