Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 111 ยท Docker Compose

Services in Compose

Learn how to describe containers as Compose services: image vs. build, ports, command, entrypoint, environment, restart policies, depends_on, and how scaling works.

Everything in a Compose file hangs off one top-level key: services. A service is a recipe for one kind of container: which image to run, how to start it, which ports to open, which settings to pass in. You describe each service once, and Compose creates one container (or several, if you ask for more) from that recipe.

This lesson walks through the service keys you will write every day. It builds on Introduction to Docker Compose and the options you already know from docker run in Running Containers. Every file and every piece of output below was run on Docker 29 with Compose v5.

A service is a docker run in YAML

The quickest way to understand a service is to translate a command you already know. This docker run:

Terminal
docker run -d --name web -p 127.0.0.1:18090:80 -e GREETING=hello --restart unless-stopped nginx:alpine

becomes this service:

YAML
services:
  web:
    image: nginx:alpine
    ports:
      - "127.0.0.1:18090:80"
    environment:
      GREETING: hello
    restart: unless-stopped

The service name (web) is a key you choose. It becomes the container's DNS name on the project network, and it is what you type in later commands such as docker compose logs web. Pick short, lowercase names that describe the role: web, api, db, cache, worker.

Compose names the real container <project>-<service>-<number>. With a project called tcd-b9-svc you get tcd-b9-svc-web-1. The project name defaults to the folder name; set it with a top-level name: key or -p on the command line. Nothing in this lesson needs version: at the top of the file: modern Compose ignores it (and warns if present).

image and build

Every service needs a source for its image. You choose one of two keys, or use both together.

image

image pulls a ready-made image from a registry (see Tags and Registries):

YAML
services:
  cache:
    image: redis:7-alpine

Always pin a tag. Writing image: redis means redis:latest, which changes under you; read Tagging and Versioning Strategies for why that hurts.

build

build tells Compose to build the image from a Dockerfile in your project. The short form is just a path to the build context:

YAML
services:
  app:
    build: ./app

The long form gives you the options of docker build (see Writing a Dockerfile and Multi-Stage Builds):

YAML
services:
  tool:
    build:
      context: .
      dockerfile: Dockerfile
      target: prod
      args:
        GREETING: from-compose
    image: tcd-b9-bld-tool:dev

Here the Dockerfile has three stages (base, dev, prod) and an ARG GREETING. target picks the stage to build, args fills in the build argument, and image gives the result a name instead of the generated default. Running it:

CONSOLE
$ docker compose up --build
 Network tcd-b9-bld_default Created
 Container tcd-b9-bld-tool-1 Created
Attaching to tool-1
tool-1  | from-compose
tool-1 exited with code 0

The container printed the value we passed through args, proving the build used it. When a service has both build and image, Compose builds the image and tags it with the image name. That is the usual pairing when you later want to push the image to a registry.

Key under build Same as Notes
context the path argument of docker build Relative to the Compose file. May also be a Git URL.
dockerfile -f Relative to the context.
target --target Stops at a named stage.
args --build-arg Values are visible in image history. Never put secrets here.
cache_from, platforms --cache-from, --platform Used in CI and multi-platform builds.

docker compose up builds an image only if it does not exist yet. After you edit the Dockerfile or the code it copies, run docker compose up --build (or docker compose build) so Compose rebuilds. The build cache from The Build Cache still applies, so unchanged layers are reused.

command and entrypoint

An image already contains a default CMD and maybe an ENTRYPOINT (see CMD and ENTRYPOINT). command replaces the CMD; entrypoint replaces the ENTRYPOINT. Write them in exec form (a YAML list) whenever you can, so no extra shell sits between Docker and your process:

YAML
services:
  app:
    build: ./app
    command: ["sh", "-c", "echo started with $$GREETING; sleep 300"]
    environment:
      - GREETING=hi from app

Notice the doubled dollar sign. Compose itself interpolates $VARIABLE while reading the file (you will meet this in Environment, Variables and Secrets). To hand a literal $GREETING to the shell inside the container, write $$GREETING. You can confirm what Compose will pass with docker compose config:

CONSOLE
$ docker compose config
...
    command:
      - sh
      - -c
      - echo started with $$GREETING; sleep 300
...

And the container really did expand the variable at run time:

CONSOLE
$ docker compose logs app
app-1  | started with hi from app

Compose accepts the string form too (command: sleep 300), which it splits like a shell would. The list form is safer, because there is no guessing about quoting.

A service whose command exits is not an error. A one-shot task such as a migration is simply a service that runs, finishes and shows Exited (0) in docker compose ps -a.

ports and expose

ports publishes container ports on the host, exactly like -p. Each entry is "HOST_IP:HOST_PORT:CONTAINER_PORT":

YAML
services:
  api:
    image: nginx:alpine
    ports:
      - "127.0.0.1::80"   # random free host port, localhost only
    expose: ["8080"]      # documentation only: not published

Leaving out the host port asks Docker to choose a free one. Find it with docker compose port:

CONSOLE
$ docker compose ps api --format 'table {{.Service}}\t{{.Status}}\t{{.Ports}}'
SERVICE   STATUS         PORTS
api       Up 2 seconds   127.0.0.1:63256->80/tcp
$ docker compose port api 80
127.0.0.1:63256

Always quote port mappings. YAML can read an unquoted 22:22 as a base-60 number, and some values silently turn into the wrong thing. Quoting costs nothing: "8080:80".

Two more details worth knowing:

  • Without a host IP, "8080:80" binds to all interfaces, so anyone on your network can reach it. Prefer "127.0.0.1:8080:80" for services that only you need. Publishing Ports explains the security side.
  • expose does not publish anything. Containers on the same Compose network can already reach each other on any port; expose only documents which ones the service listens on.

Containers talk to each other by service name and container port, never through the published host port. The app service reaches web at http://web:80 even if the host port is 18090. More on that in Networks and Volumes in Compose.

environment

environment sets variables inside the container. It accepts a map or a list; the two are equivalent:

YAML
    environment:
      GREETING: hello      # map form
YAML
    environment:
      - GREETING=hello     # list form

A key with no value (- GREETING) copies the variable from the shell that runs Compose. Big sets of variables belong in an env_file, covered in Environment, Variables and Secrets.

restart

restart is the Compose spelling of --restart, with the same values as in The Container Lifecycle: no (the default), always, on-failure[:max] and unless-stopped. Here is a service that always fails, with a limit of two retries:

YAML
services:
  worker:
    image: alpine:3
    entrypoint: ["sh", "-c"]
    command: ["echo run; exit 3"]
    restart: on-failure:2
CONSOLE
$ docker compose ps -a --format 'table {{.Service}}\t{{.Status}}'
SERVICE   STATUS
worker    Exited (3) 8 seconds ago
$ docker inspect tcd-b9-svc-worker-1 --format '{{.RestartCount}} {{.State.ExitCode}} {{.HostConfig.RestartPolicy.Name}}'
2 3 on-failure

Docker restarted the container twice (RestartCount is 2), then gave up and left it exited with code 3. For servers that should survive reboots and crashes, unless-stopped is the usual choice.

Other keys you will meet

Key What it does Equivalent flag
container_name Fixes the container name --name
working_dir Sets the working directory -w
user Runs as a user or uid:gid -u
init Runs a tiny init as PID 1 (Signals, PID 1 and --init) --init
read_only Read-only root filesystem --read-only
stop_grace_period Wait before SIGKILL on stop --stop-timeout
healthcheck Health probe (Startup Order and Health) --health-*
mem_limit, cpus Resource limits (Resource Limits) --memory, --cpus

Be careful with container_name. It looks tidy, but a fixed name means Compose cannot start a second copy of the service, so scaling breaks. Leave it out unless something external needs the exact name.

Also mind user. Setting user: "101" on the nginx image made it crash at startup in our test, because that user cannot write to the places nginx writes at boot. Change users only when the image is designed for it, as discussed in Users and Permissions.

depends_on in one minute

depends_on lists services that must be started first:

YAML
services:
  web:
    image: nginx:alpine
  app:
    build: ./app
    depends_on:
      - web

In docker compose config Compose expands the short form into its full meaning:

CONSOLE
    depends_on:
      web:
        condition: service_started
        required: true

service_started only means "the container was created and started". It does not mean the program inside is ready to accept connections. Waiting for real readiness uses health checks and a different condition; that is the subject of Startup Order and Health.

Scaling a service

A service can have more than one container. Ask for three copies with --scale:

CONSOLE
$ docker compose up -d --scale web=3
$ docker compose ps --format 'table {{.Name}}\t{{.Service}}\t{{.Status}}'
NAME               SERVICE   STATUS
tcd-b9-svc-web-1   web       Up 2 seconds
tcd-b9-svc-web-2   web       Up 1 second
tcd-b9-svc-web-3   web       Up 1 second

All three share the DNS name web, and a lookup from the network returns every address, which gives you basic round-robin balancing between containers. There is one big catch: a fixed host port can only be bound once. With ports: ["127.0.0.1:18090:80"] the second copy fails:

CONSOLE
$ docker compose up -d --scale web=2
Error response from daemon: failed to set up container networking: ... Bind for 127.0.0.1:18090 failed: port is already allocated

To scale, publish only the container port ("127.0.0.1::80"), or put a reverse proxy in front and publish the proxy alone. Compose Commands covers --scale and friends in more detail.

Orphans: services that left the file

If you rename or delete a service from the file, its old container keeps running because Compose no longer knows about it. A plain docker compose down then stops the services it knows, but the network stays "in use" by the orphan:

CONSOLE
$ docker compose down
 Network tcd-b9-svc_default Removing
 Network tcd-b9-svc_default Resource is still in use
$ docker compose down --remove-orphans
 Container tcd-b9-svc-api-1 Removed
 Network tcd-b9-svc_default Removed

Use --remove-orphans after renaming services, so the project does not accumulate stale containers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A service has both build: ./app and image: shop-app:1.0. What does Compose do?

    When both keys are present, build produces the image and image supplies its name and tag. This is the usual setup when you plan to push the image later.
  2. 2. You want the shell inside the container to expand $GREETING at run time. How do you write it in a Compose command?

    Compose interpolates $VARIABLE while reading the file. A doubled $$ is passed on as a literal $, so the container's shell sees $GREETING and expands it.
  3. 3. What does expose: ["8080"] do?

    expose is documentation. Containers on the same network can reach each other's ports anyway, and only ports publishes to the host.
  4. 4. Why does docker compose up --scale web=2 fail when web has ports: ["127.0.0.1:18090:80"]?

    The second container cannot bind host port 18090 because the first one already holds it. Publish only the container port or place a proxy in front.
  5. 5. What does the default depends_on: [web] guarantee?

    The short form means condition: service_started: the container was started, nothing more. Readiness needs a health check and condition: service_healthy.

Summary

  • A service is a reusable recipe for containers; its key is also its DNS name on the project network.
  • Use image to pull, build to build from a Dockerfile, or both to build and name the result.
  • command and entrypoint override the image's defaults; prefer the list (exec) form and write $$ for literal dollar signs.
  • ports publishes (quote them and bind 127.0.0.1 when possible); expose only documents.
  • restart takes no, always, on-failure[:max] or unless-stopped.
  • depends_on orders startup but does not wait for readiness unless you add a health condition.
  • Scaling needs services without a fixed host port, and down --remove-orphans cleans up after renamed services.

Next: Networks and Volumes in Compose