TExcelTAD
Home › Docker Compose › Services: image & build

Services: image & build

A service is one component of your application: "the API", "the database", "the worker". In the file it is a key under services:; at run time it becomes one or more containers that all share the same configuration. Every service needs to know where its image comes from, and Compose offers two answers: image (use an existing image from a registry) and build (build one from a Dockerfile). This lesson covers both, how they combine, and the keys that control pulling and naming.

image: run something that already exists

image takes a normal image reference, the same string you would give docker run:

Form Example Meaning
name redis Docker Hub library/redis:latest (avoid: latest moves)
name:tag postgres:18 a version tag
registry/path:tag ghcr.io/acme/api:1.4.2 another registry
name@digest nginx@sha256:… one exact, immutable image
tag + digest nginx:1.29@sha256:… readable and pinned; the digest wins

Compose does not rewrite or check the reference in config; a typo only shows up when the image is pulled. Image names must be lowercase, and pinning a tag (or a digest) is what makes "it works on my machine" reproducible.

build: make the image from source

build points at a build context, a folder sent to BuildKit, with a Dockerfile in it. The short form is just the path; the long form is covered in Building Images. If a service has build but no image, Compose names the result <project>-<service>.

Both at once: build and tag

When a service has both keys, image becomes the name of the built image. This is the usual pattern for your own code: developers build locally, CI builds and pushes, servers pull. Another service can reuse the same image with a different command:

compose · try it yourself
# $ docker compose config --no-path-resolution
# $ docker compose config --images
services:
  api:
    image: shop/api:${TAG:-dev}
    build: ./api
  worker:
    image: shop/api:${TAG:-dev}
    command: python -m worker
$ docker compose config --no-path-resolution
name: demo
services:
  api:
    image: shop/api:dev
    networks:
      default: null
    build:
      context: ./api
      dockerfile: Dockerfile
  worker:
    command:
      - python
      - -m
      - worker
    image: shop/api:dev
    networks:
      default: null
networks:
  default:
    name: demo_default
$ docker compose config --images
shop/api:dev
shop/api:dev

Only api builds; worker just uses the result. Notice --images lists the same image once per service. With TAG=1.5 docker compose build && docker compose push, the image shop/api:1.5 goes to the registry, and a server with the same file and TAG=1.5 pulls it instead of building.

Neither: an error

A service must have at least one of the two:

compose · try it yourself
services:
  api:
    environment:
      LOG_LEVEL: debug
service "api" has neither an image nor a build context specified: invalid compose project

pull_policy: when to pull

pull_policy decides what up does about the image:

Value Behaviour
missing (default; alias if_not_present) pull only if the image isn't on the host
always pull every time; fails if the registry is unreachable
never never pull; fail if the image is missing
build always build, even if an image with that name exists
daily, weekly, every_12h pull if the last pull is older than that
refresh check the registry and pull if the tag points somewhere new

Values are validated against a pattern, so a made-up policy fails config:

compose · try it yourself
services:
  api:
    image: shop/api:1.4
    pull_policy: sometimes
validating /home/ada/demo/compose.yaml: services.api.pull_policy 'sometimes' does not match pattern '^(always|never|build|if_not_present|missing|refresh|daily|weekly|every_([0-9]+[wdhms])+)
  

The default pairs badly with moving tags: with missing, a host that pulled redis:8 last year keeps running that old patch release forever. Either pin exact tags, or pull deliberately (docker compose pull before up).

The model below decides "pull or not" for each policy, given the local image's age:

python · try it yourself
def should_pull(policy, have_local, hours_since_pull, has_build=False):
    if policy in ("missing", "if_not_present"):
        return "pull" if not have_local else "use local"
    if policy == "always":
        return "pull"
    if policy == "never":
        return "use local" if have_local else "error: image not found locally"
    if policy == "build":
        return "build" if has_build else "error: no build section"
    if policy.startswith("every_") or policy in ("daily", "weekly"):
        limit = {"daily": 24, "weekly": 168}.get(policy) or int(policy[6:-1])
        return "pull" if not have_local or hours_since_pull >= limit else "use local"
    raise ValueError(policy)

cases = [("missing", True, 9000), ("missing", False, 0), ("always", True, 1), ("never", False, 0),
         ("daily", True, 30), ("daily", True, 3), ("every_12h", True, 13)]
for policy, have, age in cases:
    print(f"{policy:10} local={str(have):5} age={age:>4}h -> {should_pull(policy, have, age)}")
missing    local=True  age=9000h -> use local
missing    local=False age=   0h -> pull
always     local=True  age=   1h -> pull
never      local=False age=   0h -> error: image not found locally
daily      local=True  age=  30h -> pull
daily      local=True  age=   3h -> use local
every_12h  local=True  age=  13h -> pull

(The model only handles hours in every_…; the real key accepts combinations such as every_1d12h.)

Naming containers and hosts

By default a service's containers are named <project>-<service>-<n>. Some keys change names and identity:

compose · try it yourself
services:
  api:
    image: shop/api:1.4
    container_name: shop-api
    hostname: api.internal
    platform: linux/arm64
    labels:
      - "com.example.team=payments"
  cache:
    image: ghcr.io/acme/cache@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
name: demo
services:
  api:
    container_name: shop-api
    hostname: api.internal
    image: shop/api:1.4
    labels:
      com.example.team: payments
    networks:
      default: null
    platform: linux/arm64
  cache:
    image: ghcr.io/acme/cache@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
    networks:
      default: null
networks:
  default:
    name: demo_default
  • container_name fixes the container's name. It must be unique on the whole host, so two copies of the project can't run side by side, and the service can't scale beyond one container (example below).
  • hostname sets the name the container sees for itself (hostname inside it); other services still use the service name.
  • platform selects the image variant (linux/amd64, linux/arm64), useful on Apple Silicon for images without an ARM build; it then runs under emulation.
  • labels in list form (key=value) became a map, as many list-or-map keys do.

What happens when a fixed name meets scaling:

compose · try it yourself
services:
  api:
    image: shop/api:1.4
    container_name: shop-api
    deploy:
      replicas: 2
services.deploy.replicas: can't set container_name and api as container name must be unique: invalid compose project

Prefer the default names, and reach services by their service name.

One service, many containers

Everything under a service is a template. With deploy.replicas: 3 or docker compose up --scale worker=3, Compose creates demo-worker-1 to -3 from it, all identical apart from their number. That is why per-container settings (a fixed container_name, a fixed host port) clash with scaling; see Scaling & Resources.

Choosing between image and build

Situation Use
Third-party software (databases, caches, proxies) image with a pinned tag
Your own code in development build (plus image to give it a stable name)
Your own code on a server image pointing at the registry; build in CI, not on the server
A tiny helper image build with dockerfile_inline (next lesson)

Learn more: Building Images · Images in the Docker course · Swarm services

Test yourself

A service has both image: shop/api:1.5 and build: ./api. What does docker compose build do?

  1. Fails: the keys conflict
  2. Builds ./api and tags the result shop/api:1.5
  3. Pulls shop/api:1.5 and ignores build
  4. Builds an image called demo-api

Why does container_name prevent deploy.replicas: 2?

  1. Replicas need a registry
  2. Container names must be unique, so two containers can't share it
  3. container_name only works in Swarm
  4. It doesn't; Compose adds a suffix

With the default pull_policy, when does up pull redis:8?

  1. Every time
  2. Only if no redis:8 image exists locally
  3. Once a day
  4. Never