Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 128 of 8022. Docker Image LifecycleFree lesson

Conditional Stage Execution With Build Targets

You will use the --target flag to build specific stages, enabling separate workflows for development, testing, and production image generation.

In this lesson, you’ll learn how to use the --target flag to selectively build specific stages of your Dockerfile to optimize your CI/CD workflows.

Why Target Specific Stages?

When using multi-stage builds, your Dockerfile often contains stages for different environments: a builder stage for compiling code, a tester stage for running unit tests, and a production stage for the final artifact.

By default, when you run docker build, Docker executes every instruction until it reaches the final stage. However, in a CI/CD pipeline, you don't always need to build the production image just to run your test suite. By using the --target flag, you can instruct Docker to stop building once a specific stage is completed.

Practical Application

Imagine a Dockerfile structured like this:

# Stage 1: Build
FROM node:18 AS builder
WORKDIR /app
COPY . .
RUN npm install && npm run build

# Stage 2: Test
FROM builder AS tester
RUN npm test

# Stage 3: Production
FROM nginx:alpine AS production
COPY --from=builder /app/dist /usr/share/nginx/html

To run your automated tests in a CI pipeline without building the final production image, you simply add the flag to your command:

docker build --target tester -t my-app-tests .

Docker will build up to the tester stage and stop there. If the tests pass, your CI pipeline can then run a second command to build the production stage:

docker build --target production -t my-app-prod .

Efficiency in CI/CD

This approach is incredibly powerful for keeping your pipeline fast. You can split your build process into independent jobs:

  1. Test Job: Build to the tester target. If this fails, the process stops, saving you the time and resources required to build the production image.
  2. Production Job: Build to the production target only after the test job succeeds.

By targeting specific stages, you ensure that your CI/CD pipeline only performs the necessary work for each environmental requirement.

Key Takeaway: The --target flag allows you to build a Docker image up to a specific stage, enabling you to isolate and execute environment-specific tasks like testing or compiling without generating unnecessary production artifacts.