Docker Compose — Build Args

1 minute read

Build arguments (args:) let you parameterize your Dockerfile at build time — like passing variables to the build process.

Defining Build Args

Dockerfile:

ARG NODE_VERSION=20
FROM node:${NODE_VERSION}-alpine

ARG APP_ENV=production
ENV APP_ENV=${APP_ENV}

WORKDIR /app
COPY . .
RUN npm ci
CMD ["node", "server.js"]

compose.yml:

services:
  api:
    build:
      context: ./api
      args:
        NODE_VERSION: "20"
        APP_ENV: staging

Map vs List Syntax

# Map syntax (recommended)
args:
  NODE_VERSION: "20"
  APP_ENV: staging

# List syntax
args:
  - NODE_VERSION=20
  - APP_ENV=staging

Pass from .env

services:
  api:
    build:
      context: ./api
      args:
        NODE_VERSION: ${NODE_VERSION}

.env:

NODE_VERSION=20

Pass from Host

services:
  api:
    build:
      context: ./api
      args:
        - NODE_VERSION    # Pass from host: export NODE_VERSION=20

Args vs Environment

Feature args: environment:
Available during Build (Dockerfile) Runtime (container)
Scope docker compose build docker compose up
Persist in image? Only if copied to ENV Always in container
Use case Build customization App configuration

Build Args for Base Image Selection

services:
  api:
    build:
      context: .
      args:
        BASE_IMAGE: node:20-alpine

  api-debug:
    build:
      context: .
      args:
        BASE_IMAGE: node:20    # Full image with debug tools

Dockerfile:

ARG BASE_IMAGE=node:20-alpine
FROM ${BASE_IMAGE}

Verify Build Args

docker compose build --progress=plain api 2>&1 | grep "ARG"

Summary

Feature Detail
Define build.args: in compose.yml
Receive ARG in Dockerfile
Override CLI, .env, or host shell
Scope Build-time only
Persist Only via ENV APP_ENV=${APP_ENV}

Quick Reference

Item Detail
args: Build-time variables
ARG Dockerfile instruction to receive
Map syntax KEY: value (recommended)
From .env args: { KEY: ${KEY} }
Pass-through - KEY (from host)
vs environment args=build, environment=runtime