✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.3.1.4 Compose Target Stage

A focused guide to Compose Target Stage, connecting core concepts with practical Docker and container operations.

The Compose target stage, specified through the target field within a service's build configuration, selects a specific named stage from a multi-stage Dockerfile to build, allowing different services (or different builds of the same service) to stop at different points in the same overall Dockerfile.

Selecting a Build Stage

The target field names which stage, defined with AS in the Dockerfile, the build process should stop at and use as the final result.

FROM node:20-alpine AS development
RUN npm install

FROM node:20-alpine AS production
RUN npm ci --production
COPY --from=development /app/dist ./dist
services:
  api-dev:
    build:
      context: .
      target: development
  api-prod:
    build:
      context: .
      target: production

Both services build from the exact same Dockerfile, but each selects a different stage, producing two distinctly purposed images from this single, shared multi-stage build definition.

Why Multi-Stage Builds With Target Selection Are Valuable

This approach avoids duplicating largely similar build logic across separate Dockerfiles for development and production variants, instead expressing both within a single file and selecting between them at build time.

docker compose build api-dev
docker compose build api-prod
Building Without Specifying a Target

Without an explicit target, a multi-stage build uses the final stage defined in the Dockerfile by default, which is generally the appropriate default for a service that doesn't need to select an earlier, intermediate stage.

services:
  api:
    build: .
Verifying Which Stage Was Actually Used

Reviewing the build's output, or inspecting the resulting image, can help confirm the intended stage was actually selected and built.

docker compose build --progress=plain api-dev
Why the Compose Target Stage Field Matters

Selecting a specific build stage through this field is what makes multi-stage Dockerfiles genuinely useful within a Compose context, allowing several differently purposed images to be produced from one well-organized, non-duplicated Dockerfile definition.