Operations 12 min read

Mastering Elegant Dockerfiles: From Basics to Multi‑Stage Builds

This article explains Docker containers and Dockerfiles, compares simple and compact Dockerfile examples, demonstrates single‑file versus multi‑file builds, and shows how multi‑stage builds can dramatically reduce image size while keeping Dockerfiles maintainable and efficient.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Elegant Dockerfiles: From Basics to Multi‑Stage Builds

Docker Containers

Containers are standard software units that run consistently across environments. Their key characteristics include:

Portability : Packages code, configuration, and dependencies to ensure identical execution anywhere.

High resource utilization : Process‑level isolation allows fine‑grained CPU and memory allocation.

Fast scaling : Containers start and stop quickly by sharing the host OS.

Docker is the dominant container engine, providing isolated processes whose files come from images, ensuring portability from development to production and speeding up deployment on various cloud platforms.

Dockerfile

A Dockerfile describes how to assemble an image using a series of commands. Writing a clean Dockerfile improves consistency for development and testing teams and simplifies operations.

Key guidelines for an elegant Dockerfile:

Keep the file short; fewer layers produce smaller images.

Avoid including unnecessary files such as logs or temporary build artifacts.

Use runtime‑only base images; do not copy build‑time steps into the final image.

Example comparisons:

FROM ubuntu:16.04
RUN apt-get update
RUN apt-get install -y apt-utils libjpeg-dev python-pip
RUN pip install --upgrade pip
RUN easy_install -U setuptools
RUN apt-get clean
FROM ubuntu:16.04
RUN apt-get update && apt-get install -y apt-utils \
  libjpeg-dev python-pip \
  && pip install --upgrade pip \
  && easy_install -U setuptools \
  && apt-get clean

Image size comparison:

$ docker images | grep ubuntu
REPOSITORY      TAG     IMAGE ID    CREATED     SIZE
ubuntu          16.04   9361ce633ff1 1 days ago 422MB
ubuntu          16.04-1 3f5b979df1a9 1 days ago 412MB

Using Multi‑Stage Builds

Docker 17.05+ supports multi‑stage builds, allowing you to keep only the final artifact in the resulting image.

Single‑File Build

A single Dockerfile that contains all build steps can become long, increase image size, and expose build‑time dependencies.

FROM golang:1.11.4-alpine3.8 AS build-env
ENV GO111MODULE=off
ENV GO15VENDOREXPERIMENT=1
ENV BUILDPATH=github.com/lattecake/hello
RUN mkdir -p /go/src/${BUILDPATH}
COPY ./ /go/src/${BUILDPATH}
RUN cd /go/src/${BUILDPATH} && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go install -v
CMD [/go/bin/hello]

This approach results in a 312 MB image.

Multi‑File Build

Separate Dockerfiles for build and runtime reduce image size but increase management overhead.

# Dockerfile.build
FROM golang:1.11.4-alpine3.8 AS build-env
ENV GO111MODULE=off
ENV GO15VENDOREXPERIMENT=1
ENV BUILDPATH=github.com/lattecake/hello
RUN mkdir -p /go/src/${BUILDPATH}
COPY ./ /go/src/${BUILDPATH}
RUN cd /go/src/${BUILDPATH} && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go install -v
# Dockerfile.run
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root
ADD hello .
CMD ["./hello"]
# build.sh
#!/bin/sh
docker build -t --rm hello:build . -f Dockerfile.build
docker create --name extract hello:build
docker cp extract:/go/bin/hello ./hello
docker rm -f extract
docker build --no-cache -t --rm hello:run . -f Dockerfile.run
rm -rf ./hello

Using this method reduces the final image size significantly, though three files must be maintained.

Multi‑Stage Build (Single Dockerfile)

By declaring multiple FROM statements with aliases, you can copy only the needed artifacts from earlier stages, keeping the final image minimal.

FROM golang:1.11.4-alpine3.8 AS build-env
ENV GO111MODULE=off
ENV GO15VENDOREXPERIMENT=1
ENV GITPATH=github.com/lattecake/hello
RUN mkdir -p /go/src/${GITPATH}
COPY ./ /go/src/${GITPATH}
RUN cd /go/src/${GITPATH} && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go install -v
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=build-env /go/bin/hello /root/hello
WORKDIR /root
CMD ["/root/hello"]

Building this Dockerfile yields a much smaller image while keeping the Dockerfile maintainable.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DockerDevOpscontainerizationmulti-stage-buildDockerfile
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.