✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.2.1.2 Service Build Field

A focused guide to Service Build Field, connecting core concepts with practical Docker and container operations.

The build field within a Compose service tells Compose to construct that service's image from a local Dockerfile, rather than pulling an existing, pre-built image, used for any service representing the project's own custom application code.

The Simplest Form: Building From the Current Directory

Specifying build as a simple path tells Compose to use the Dockerfile in that directory to construct the service's image.

services:
  api:
    build: .

This builds using the Dockerfile found in the current directory, with that directory also serving as the build context.

Specifying a Different Dockerfile or Build Context

For more specific control, build can be expanded into a mapping specifying a distinct context directory and Dockerfile name.

services:
  api:
    build:
      context: ./backend
      dockerfile: Dockerfile.prod
Passing Build Arguments

Build-time arguments needed by the Dockerfile can be supplied directly through the build field.

services:
  api:
    build:
      context: .
      args:
        - NODE_VERSION=20
ARG NODE_VERSION
FROM node:${NODE_VERSION}-alpine
Forcing a Rebuild When the Dockerfile or Source Changes

Compose doesn't automatically rebuild an image just because the underlying Dockerfile or source code changed — an explicit rebuild is needed to pick up those changes.

docker compose build api
docker compose up -d --build

The second form conveniently combines rebuilding with starting the service in a single command, useful during active development when source changes happen frequently.

Why the Build Field Matters

The build field is what makes Compose useful not just for orchestrating existing images, but for actually constructing and running a project's own custom application code as part of the same unified, declarative application definition.