✦ For everyone, free.

Practical knowledge for real and everyday life

Home

4.2.5.3 RUN Build Commands

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

Using RUN for build commands covers invoking a compiler, bundler, or other build tool as part of constructing an image, transforming source code into a compiled binary or bundled output that becomes part of the image's filesystem.

Compiling Source Code

For compiled languages, a RUN instruction invokes the compiler directly, producing a binary that later instructions can copy into a final, smaller image.

FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN go build -o app .
Bundling Frontend Assets

For frontend applications, a RUN instruction typically invokes a build tool that bundles, minifies, and transpiles source files into a smaller set of production-ready assets.

FROM node:20 AS build
WORKDIR /app
COPY . .
RUN npm install && npm run build
Running Build Commands as Part of a Multi-Stage Build

Build commands are typically run within an earlier, fuller-featured build stage, with only the resulting output copied into a smaller final stage, keeping the build tooling itself out of the production image.

FROM node:20 AS build
WORKDIR /app
COPY . .
RUN npm install && npm run build

FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
Passing Build-Time Configuration

Build commands sometimes need configuration values that differ between builds, which can be supplied through ARG, made available to the RUN instruction executing the build.

ARG BUILD_ENV=production
RUN npm run build -- --mode=$BUILD_ENV
docker build --build-arg BUILD_ENV=staging -t myapp .
Why Running Build Commands This Way Matters

Performing build commands within the Dockerfile itself, rather than requiring them to be run separately beforehand, ensures the build process is fully captured and reproducible — anyone with the source code and Docker can produce the exact same build output, without needing a separately documented build procedure.