Best practices when building container images

2 minute read

CloudBees recommends the following best practices for building container images:

  • Don’t install unnecessary packages

  • Decouple applications

  • Minimize the number of layers

  • Sort multi-line arguments

  • Leverage build cache

For details about best practices for Dockerfiles, see Best practices for writing Dockerfiles

For details about using agents for running builds, see Managing agents

Example container images based on usage

Rather than building a container image from scratch, there are quite a few images available based on your build requirements.

Using these images helps save time, as they are maintained, tested, and widely used.

Multi-stage builds

Multi-stage builds reduce image size and make them easier to maintain.

With multi-stage builds, you use multiple FROM statements in your Dockerfile.

Each FROM instruction can use a different base, and each of them begins a new stage of the build.

You can selectively copy artifacts from one stage to another, leaving behind everything you don’t want in the final image.

To show how this works, the following example adapts the Dockerfile from the previous section to use multi-stage builds.


FROM golang:1.7.3
WORKDIR /go/src/
RUN go get -d -v
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=0 /go/src/ .
CMD ["./app"]