BuildBot

Containers from Scratch

Networks & service discovery

Lesson 4 of 5

What you'll learn

  • Understand the bridge network that connects containers
  • Reach another container by service name instead of an IP
  • Read a host:container port mapping correctly

When containers join the same Docker network (Compose creates one automatically), they get a private virtual network and a built-in DNS server. That means a container can reach another by its service name as a hostname — no IP addresses, no hardcoding.

# docker-compose.yml
services:
  api:
    build: .
    environment:
      REDIS_URL: redis://cache:6379   # "cache" resolves via DNS
    ports:
      - "8080:3000"                   # host:container

  cache:
    image: redis:7

The api service connects to cache:6379. Docker's DNS resolves cache to whatever IP that container currently has — even if it restarts with a new IP.

Published ports are host:container

"8080:3000" means "traffic to port 8080 on the host forwards to port 3000 inside the container." The left side is what you type in your browser; the right side is what the app listens on. Services talk to each other over the internal port (3000) directly — publishing is only needed to reach a container from your machine.

Service name, not localhost

Inside the network, localhost means this container, not its neighbor. To reach another service, use its service name (cache, db) — that's the single most common networking mistake.

Resolve a service name and map a port

Run it. DNS turns a service name into the container's current IP, and the port map translates host:container.

Loading editor…

Next: tying services together into one file with Compose.

Sign in to save your progress across devices.