Course contentsShow
← Cloud and Infrastructure
Lesson 1055 of 2,98920. Docker in DepthFree lesson

Build Configuration and Context

Use the build directive to build images from Dockerfiles with custom contexts, args, and target stages.

Build Configuration and Context

What you'll learn: How to instruct Docker Compose to build images dynamically from Dockerfiles using build directives, custom contexts, build arguments, and multi-stage target selection.

The Core Idea

So far you've worked with pre-built images in Docker Compose. But you can also tell Compose to build images on-the-fly using the build directive. This lets you specify where your Dockerfile lives (the context), pass in build-time variables (args), and even select specific stages from multi-stage builds (target).

Think of it like ordering a custom sandwich: the context is the kitchen where ingredients live, args are your special instructions ("extra pickles!"), and target is choosing which stage of preparation you want ("stop after toasting, skip the wrapping").

How It Works

In your docker-compose.yml, replace or supplement image: with build::

services:
  webapp:
    build:
      context: ./app          # Path to build context (where Dockerfile lives)
      dockerfile: Dockerfile   # Optional: custom Dockerfile name
      args:
        - NODE_ENV=production  # Build-time arguments
        - VERSION=1.2.3
      target: production       # Target stage in multi-stage build
    ports:
      - "3000:3000"

The context is the directory Docker sends to the build engine—everything inside becomes available to COPY and ADD instructions. Args let you parameterize your builds (remember ARG from Dockerfiles?). Target lets you stop at a specific stage, perfect for separating dev and prod builds.

Key Takeaway:
The build directive in Docker Compose transforms your service definitions into custom image factories, using context to locate files, args to customize builds, and target to select multi-stage outcomes—all without running docker build manually.