Dockerfile Guide: From Understanding to Practical Use
About 4586 words
Understanding It in One Sentence
A Dockerfile is an image's recipe: each instruction leaves a trace in the final image (a read-only layer). Two principles underpin a good Dockerfile: combine instructions where possible to reduce layers, and put stable content first to use the cache.
If you have read Docker Filesystems Explained, you know that every
RUNproduces a new read-only layer. Dockerfile techniques are essentially ways of working with this layer mechanism.
1. Hands-On Experiment: Build an Image and Examine Every Layer
Here is a fully reproducible example. Run it from beginning to end on a Linux machine to see how each layer is created.
Step 1: Prepare the project files
# Create the project directory
mkdir -p /tmp/dockerfile-lab/src
cd /tmp/dockerfile-lab
# Create a simple "application": just a shell script
cat > src/app.sh << 'EOF'
#!/bin/sh
echo "Hello from Docker!"
echo "App version: ${APP_VERSION:-unknown}"
echo "Running as user: $(whoami)"
echo "Working directory: $(pwd)"
# Simulate a long-running process
while true; do sleep 3600; done
EOF
chmod +x src/app.sh
# Check the file structure
find . -type f
# .
# └── src/
# └── app.shStep 2: Write the Dockerfile
cat > Dockerfile << 'EOF'
# ===== Dockerfile Layer-by-Layer Experiment =====
FROM alpine:3.19
# ↑ FROM itself creates no layer (the alpine base image already has 1, visible in docker history)
# ARG: build arguments, available only during the build
ARG APP_VERSION=1.0.0
# LABEL: image metadata (no filesystem layer)
LABEL maintainer="[email protected]" \
version="${APP_VERSION}"
# ENV: environment variables (no filesystem layer, but retained in the image JSON)
ENV APP_VERSION=${APP_VERSION} \
PORT=8080
# WORKDIR: create a directory in the image and set it as the working directory
# (creates a small layer of about 8KB containing directory inode metadata)
WORKDIR /app
# COPY: copy application code into the image — filesystem layer 1
COPY src/ ./src/
# RUN: make the script executable — filesystem layer 2
RUN chmod +x src/app.sh
# EXPOSE: declare a port (no filesystem layer)
EXPOSE 8080
# USER: create a non-root user and switch to it — filesystem layer 4 (RUN) + metadata (USER)
RUN adduser -D appuser
USER appuser
# ENTRYPOINT: program executed at container startup (no filesystem layer)
ENTRYPOINT ["/app/src/app.sh"]
EOFStep 3: Build the image and observe layer creation
docker build -t layer-lab .
# Example output (Docker 29.6.0, containerd snapshotter mode):
# [+] Building 3.1s (9/9) FINISHED
# => [1/5] FROM docker.io/library/alpine:3.19@sha256:6baf4358...
# => [2/5] WORKDIR /app
# => [3/5] COPY src/ ./src/ ← Layer 1
# => [4/5] RUN chmod +x src/app.sh ← Layer 2
# => [5/5] RUN adduser -D appuser ← Layer 3Why [1/5] through [5/5]? BuildKit numbers filesystem-changing Dockerfile instructions (WORKDIR, COPY, and two RUN instructions) as build steps. FROM is step 1; the remaining four steps correspond to four filesystem layers.
Step 4: Verify with docker history: which instructions have a file size, and which are 0B?
docker history layer-lab
# IMAGE CREATED CREATED BY SIZE
# 7a1c4b327582 2 minutes ago ENTRYPOINT ["/app/src/app.sh"] 0B ← Metadata
# <missing> 2 minutes ago USER appuser 0B ← Metadata
# <missing> 2 minutes ago RUN |1 APP_VERSION=1.0.0 /bin/sh -c adduser … 41kB ← Layer 5! (RUN)
# <missing> 2 minutes ago EXPOSE [8080/tcp] 0B ← Metadata
# <missing> 2 minutes ago RUN |1 APP_VERSION=1.0.0 /bin/sh -c chmod +x… 4.1kB ← Layer 4! (RUN)
# <missing> 2 minutes ago COPY src/ ./src/ # buildkit 16.4kB← Layer 3! (COPY)
# <missing> 2 minutes ago WORKDIR /app 8.19kB← Layer 2! (directory metadata)
# <missing> 2 minutes ago ENV APP_VERSION=1.0.0 PORT=8080 0B ← Metadata
# <missing> 2 minutes ago LABEL [email protected] version=1.0.0 0B ← Metadata
# <missing> 2 minutes ago ARG APP_VERSION=1.0.0 0B ← Metadata
# <missing> 9 months ago CMD ["/bin/sh"] 0B ← Metadata
# <missing> 9 months ago ADD alpine-minirootfs-3.19.9-x86_64.tar.gz /… 8.08MB← alpine base layer
#
# Key observations:
# SIZE > 0B → filesystem layer (RUN, COPY, and WORKDIR each occupy a small layer)
# SIZE = 0B → metadata-only instruction (ARG, LABEL, ENV, EXPOSE, USER, ENTRYPOINT, CMD...)
# "|1 APP_VERSION=1.0.0" in CREATED BY is BuildKit inlining the ARG value into RUNStep 5: Inspect the complete metadata with docker inspect
docker inspect layer-lab[
{
"Id": "sha256:7a1c4b32758245dfc80ebcea0dc6a978028719da4c0923bab611a9c0376cd561",
"RepoTags": ["layer-lab:latest"],
"Comment": "buildkit.dockerfile.v0",
"Config": {
"User": "appuser", // ← USER is stored here
"ExposedPorts": { "8080/tcp": {} }, // ← EXPOSE is stored here
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"APP_VERSION=1.0.0", // ← ENV is stored here
"PORT=8080"
],
"Entrypoint": [ "/app/src/app.sh" ], // ← ENTRYPOINT is stored here
"WorkingDir": "/app", // ← WORKDIR is stored here
"Labels": {
"maintainer": "[email protected]", // ← LABEL is stored here
"version": "1.0.0"
}
// Note: Config has no ARG (discarded after the build)
// Note: Config has no HEALTHCHECK (omitted in this example)
// Note: Config has no Cmd (replaced by ENTRYPOINT)
},
"RootFS": {
"Type": "layers",
"Layers": [ // ← Chain of filesystem layer IDs
"sha256:0b44b2151d78267ab6f2c76208c3be18688f49b2b0afd6852a9533f2cce121c5", // alpine base layer
"sha256:a533cc96bb5ee32feecc5dc29e4e29340054346534aa2030f7b22b80fd0a292a", // WORKDIR /app (8.19kB)
"sha256:773eeaabf70ad200638ca1663c2086a83c2f447d299a76157c06a2169d1beeed", // COPY src/ ... (16.4kB)
"sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef", // RUN chmod ... (4.1kB)
"sha256:8121549a86f0c96e911eec33b6b428a800f58ae98a8a9515fe39330b655377d9" // RUN adduser ... (41kB)
]
}
}
]The key distinction:
RootFS.Layers(five layers) stores files;Configstores configuration. They do not overlap: no instruction appears in both.
Step 6: Run a container to verify
docker run --rm layer-lab
# Hello from Docker!
# App version: 1.0.0
# Running as user: appuser
# Working directory: /appStep 7: Recap—count the layers
This Dockerfile has 14 instructions:
Instructions producing filesystem layers (5):
├── WORKDIR /app → Layer 2 (8.19kB, directory inode metadata)
├── COPY src/ ... → Layer 3 (16.4kB)
├── RUN chmod ... → Layer 4 (4.1kB)
└── RUN adduser ... → Layer 5 (41kB)
(+ 1 alpine base layer)
Metadata-only instructions (10):
├── ARG, LABEL, ENV, EXPOSE, USER, ENTRYPOINT, CMD
└── All have SIZE = 0B; data is stored in the image JSON configuration
Final image = 1 (base) + 4 (WORKDIR/COPY/RUN) = 5 layers
⚠️ Note: WORKDIR is not purely metadata! It creates a small disk layer of about 8KB.The main takeaway: the SIZE column in
docker historyis the definitive way to distinguish filesystem layers from metadata. Values greater than 0B occupy disk space; 0B entries are only lines of JSON in the image configuration.
Step 8: Where is each layer actually stored on disk?
Every sha256 in RootFS.Layers corresponds to a real directory on disk. There are two ways to inspect it:
Method 1: Export the image with docker save and inspect the layer tar files
# Export the image to a tar archive; each layer is a separate tar file
docker save layer-lab -o /tmp/layer-lab.tar
tar -tf /tmp/layer-lab.tar
# blobs/
# sha256/
# 17a39c0ba978... ← alpine base layer (tar containing bin/ etc/ lib/ ...)
# 6c9f82e228dc... ← WORKDIR /app (tar containing the app/ directory)
# 8fe2d3a5e83b... ← COPY src/ ... (tar containing src/app.sh)
# 4f4fb700ef54... ← RUN chmod ... (tar containing only app.sh permission changes)
# 2037c0fe711a... ← RUN adduser ... (tar with changes to /etc/passwd and other system files)
# ec32fca1c255... ← Image Config JSON
# 7a1c4b327582... ← Image Manifest
# ... (also a manifest list, attestation, etc.)
# index.json
# manifest.json
# oci-layout
# ⚠️ Note: docker save exports OCI format. Blob sha256 values hash compressed contents,
# unlike RootFS.Layers sha256 values in docker inspect (uncompressed hashes / diff_id)!
# Their correspondence is recorded in manifest.json and the Config JSON.
# Inspect manifest.json to find the blob-to-layer mapping:
tar -xf /tmp/layer-lab.tar manifest.json -O | python3 -m json.tool
# [{
# "Config": "blobs/sha256/ec32fca1c255...",
# "Layers": [
# "blobs/sha256/17a39c0ba978...", ← Layer 1: alpine base
# "blobs/sha256/6c9f82e228dc...", ← Layer 2: WORKDIR
# "blobs/sha256/8fe2d3a5e83b...", ← Layer 3: COPY
# "blobs/sha256/4f4fb700ef54...", ← Layer 4: RUN chmod
# "blobs/sha256/2037c0fe711a..." ← Layer 5: RUN adduser
# ]
# }]
# Inspect one layer (the COPY layer here):
tar -tzf /tmp/layer-lab.tar blobs/sha256/8fe2d3a5e83bb8b166f361f530033da7e542d700cf230455cfbbd62874631ace
# src/
# src/app.sh ← Contents of the COPY src/ ./src/ layer!Method 2: Inspect how containerd manages these layers on the host, using this lab environment
The lab uses Ubuntu 22.04 + Docker 29.6.0 in containerd snapshotter mode, rather than traditional overlay2 mode. Actual layer files reside under /var/lib/containerd/.
⚠️ Important: in containerd snapshotter mode, the KEY shown by
ctr snapshot lsis not the same value as the sha256 indocker inspect→RootFS.Layers.
RootFS.Layerssha256 = diff_id (hash of uncompressed contents)ctr snapshot lsKEY = hash of compressed blob contents (the same as blob sha256 values exported bydocker save)
# Step 1: List snapshots (KEY hashes compressed content; PARENT records the parent relationship)
ctr -n moby snapshot ls | grep -E "^sha256:" | head -10
# sha256:17a39c0ba978... sha256:... Committed ← alpine base layer
# sha256:6c9f82e228dc... sha256:17a39c... Committed ← WORKDIR, parent is alpine
# sha256:8fe2d3a5e83b... sha256:6c9f82e... Committed ← COPY, parent is WORKDIR
# sha256:4f4fb700ef54... sha256:8fe2d3a... Committed ← RUN chmod
# sha256:2037c0fe711a... sha256:4f4fb7... Committed ← RUN adduser
# ...
# ↑ KEY = sha256 of compressed layer content (≠ RootFS.Layers sha256)
# ↑ PARENT = the layer underneath this one (forming a chain)
# Step 2: Inspect a layer with ctr (the COPY layer here)
ctr -n moby snapshot info sha256:8fe2d3a5e83bb8b166f361f530033da7e542d700cf230455cfbbd62874631ace
# {
# "Kind": "Committed",
# "Name": "sha256:8fe2d3a5e83bb8b166f361f530033da7e542d700cf230455cfbbd62874631ace",
# "Parent": "sha256:6c9f82e228dcfdc2dadcbada0530e2e51b86fdd51366a6e21d7c6949c28edc56"
# }
# ↑ Confirms that the COPY layer's PARENT is the WORKDIR layer
# Step 3: The mapping between sha256 and disk directory numbers lives in metadata.db
# The containerd snapshotter stores this mapping in a separate BoltDB.
# Method A: Install a boltdb browser (recommended, a one-time setup)
go install github.com/br0xen/boltbrowser@latest
~/go/bin/boltbrowser /var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/metadata.db
# In the TUI:
# → Select the "snapshots" bucket
# → The left side shows numeric IDs ("1", "2", "3"...)
# → The right side shows corresponding sha256 values (ctr snapshot ls KEY)
# → Numeric ID = directory name under snapshots/
# For example: ID "3" → sha256:8fe2d3a5... ← The COPY layer's directory!
# Method B: No Go environment? Search with xxd + grep (no installation needed)
xxd /var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/metadata.db | grep -A2 -B2 "8fe2d3a5"
# The sha256 appears near a numeric ID; that number is the directory name
# Once you know the numeric ID, inspect the files directly:
ls /var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/3/fs/
# src/
# └── app.sh ← COPY layer contents; sha256:8fe2d3a5... = number 3The relationship between the two sha256 values:
RootFS.Layersindocker inspecthashes uncompressed content (diff_id); thectr snapshot lsKEY hashes compressed content. Blobs exported bydocker saveuse compressed hashes and therefore match thectr snapshot lsKEY. For everyday use, identify layers withRootFS.Layersfromdocker inspect.
2.1 How docker pull Works: It Also Downloads Layer Files
Pulling an image sounds mysterious, but it simply downloads layers (tar files) built by someone else into your local snapshots directory. They occupy the same location as layers produced by docker build.
# Pull a small uncached image and observe what happens
docker pull alpine:3.19
# Output on the first pull:
# 3.19: Pulling from library/alpine
# 0b44b2151d78: Pull complete ← Downloaded one layer
# Digest: sha256:6baf43584bcb78f2e5847d1de515f23499913ac9f12bdf834811a3145eb11ca1
# Status: Downloaded newer image for alpine:3.19
# After pulling, where is that layer?
docker inspect alpine:3.19 | jq '.[0].RootFS.Layers'
# [
# "sha256:0b44b2151d78267ab6f2c76208c3be18688f49b2b0afd6852a9533f2cce121c5" ← Only 1 layer
# ]
# This sha256 matches "0b44b2151d78...: Pull complete" in the docker pull output!
# It is the layer downloaded locally. Where can you inspect it?
# containerd snapshotter mode:
ctr -n moby snapshot ls | grep "0b44b215"
# sha256:0b44b2151d78... Committed ← Here it is!
# Traditional overlay2 mode:
ls /var/lib/docker/overlay2/0b44b2151d78.../diff/
# bin/ etc/ lib/ ... ← These are the downloaded files
docker pull= download tar files → extract into snapshots/ or overlay2/.docker build= execute instructions locally → store results in the same snapshots/ or overlay2/ directory. Their output format is identical: layer sha256 directories. This explains whydocker pullcan reuse local layers ("Already exists") and why some layers finish instantly when pulling common base images.
2.2 What Exactly Does a Layer Contain?
A layer is not a complete filesystem. It stores only the delta relative to the preceding layer: added and modified files.
Layer 0 (alpine base image) Layer 3 (RUN echo "layer3" >> /layer1.txt)
┌──────────────────────┐ ┌──────────────────────────┐
│ /bin/ │ │ /layer1.txt │ ← Only the modified layer1.txt
│ /etc/ │ │ (content: layer1\nlayer3) │ Other files (bin/, etc/) are not duplicated
│ /lib/ │ └──────────────────────────┘
│ ... │
└──────────────────────┘ Layer 2 (COPY script.sh /script.sh)
┌──────────────────────────┐
Layer 1 (RUN echo "layer1" > /layer1.txt) │ /script.sh │ ← Only the new file
┌──────────────────────┐ └──────────────────────────┘
│ /layer1.txt │ ← Just this one new file
│ (content: layer1) │
└──────────────────────┘Each layer is a directory on disk:
# Inspect all image layers (a chain of IDs)
docker inspect layer-demo | jq '.[0].RootFS.Layers'
# [
# "sha256:7e01a...", ← Layer 0: alpine base image
# "sha256:b2c3d...", ← Layer 1: RUN echo "layer1"...
# "sha256:e4f5a...", ← Layer 2: COPY script.sh...
# "sha256:9a8b7..." ← Layer 3: RUN echo "layer3"...
# ]These four sha256 values identify four directories. Inspect them on disk:
# Traditional overlay2 path
ls /var/lib/docker/overlay2/
# 7e01a.../ ← Layer 0 (alpine)
# b2c3d.../ ← Layer 1
# e4f5a.../ ← Layer 2
# 9a8b7.../ ← Layer 3
# Each directory has a diff/ containing that layer's changed files
ls /var/lib/docker/overlay2/b2c3d.../diff/
# layer1.txt ← The only output of layer 1
# containerd snapshotter path
ls /var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/
# 56/fs/ ← Layer 0
# 57/fs/ ← Layer 1
# 58/fs/ ← Layer 2
# 59/fs/ ← Layer 32.3 How Do These Layers Become a Container Filesystem?
Recall the core idea from Docker Filesystems Explained:
What Docker does for docker run layer-demo:
mount -t overlay overlay \
-o lowerdir=layer0:layer1:layer2:layer3,upperdir=container-writable-layer,workdir=work \
/merged
Layer 3 (top image layer) ─┐
Layer 2 ──────────────────┤
Layer 1 ──────────────────┤── lowerdir (read-only)
Layer 0 (base image) ──────┘
Container writable layer ─── upperdir (read/write)
───────────────────────────
merged = / as seen inside the containerdocker build executes instructions one at a time, saving each RUN/COPY/ADD result in a new directory. docker run stacks those directories with OverlayFS.
Wait: does every instruction produce a layer? No. Instructions fall into three groups:
| Always create a layer | Only write metadata | Special: create a small layer |
|---|---|---|
RUN — execute commands | CMD — default startup command | WORKDIR — create a directory (≈8KB) |
COPY — copy files | ENTRYPOINT — entry program | |
ADD — copy and extract | EXPOSE — declare ports | |
ENV — environment variables | ||
USER — switch users | ||
LABEL — labels | ||
ARG — build arguments |
WORKDIRis special: it does not produce substantial file changes likeRUNorCOPY, but it does create a small layer of about 8KB for directory inode metadata. With BuildKit,docker historyshows SIZE ≈ 8KB. In contrast,EXPOSE,ENV, andCMDare entirely zero-byte operations: they only modify the image's JSON metadata, visible withdocker inspect, and create no overlay2 directory on disk.
2.4 Why Does Order Matter? Caching from a Layer Perspective
# Scenario: you modify the app.py source
# ❌ Poor order
COPY . /app # Layer 2: source changed → rebuild this layer
RUN pip install -r requirements.txt # Layer 3: forced rebuild, even when dependencies are unchanged!
# ✅ Good order
COPY requirements.txt /app/ # Layer 2: requirements.txt unchanged → cache hit, skip
RUN pip install -r /app/requirements.txt # Layer 3: cache hit, skip
COPY app.py /app/ # Layer 4: only this layer rebuildsEach layer's cache key combines the instruction contents and the preceding layer's ID. Any earlier layer changing forces all later layers to rebuild, like falling dominoes. Put the least frequently changing operations (installing system dependencies) first, and the most frequent changes (copying source) last.
2.5 How Many Layers Does a Dockerfile Produce?
Total image layers = base image layers + the number of RUN/COPY/ADD instructions you write.
FROMitself creates no new layer. It only specifies which image to start from. The base image already has layers, visible indocker history, and those become the first layers of your image unchanged. Think ofFROMas saying "bring that stack of books over," rather than "add another book."
FROM python:3.12-alpine # Base image; assume it has 4 layers
RUN adduser -D app # Layer 1 (RUN)
WORKDIR /app # ← Small layer (~8KB, directory inodes)
COPY requirements.txt ./ # Layer 2 (COPY)
RUN pip install -r requirements.txt # Layer 3 (RUN)
COPY . . # Layer 4 (COPY)
ENV APP_ENV=production # ← No layer!
EXPOSE 8000 # ← No layer!
USER app # ← No layer!
CMD ["python", "main.py"] # ← No layer!
# ───────────────────────────────────────────
# Filesystem layers: 4 base layers + your additions (RUN×2 + COPY×2 + WORKDIR) = 5 new layers
# Total = 4 (base image) + 5 (yours) = 9 layersRule of thumb: count
RUN,COPY, andADD;WORKDIRadds a small layer of about 8KB. Entries with Size > 0B indocker historyare filesystem layers.
How can you check an image's exact layer count? You can count with
docker history, but the more precise method is to inspect the filesystem layer ID array directly:# View every filesystem layer ID docker inspect <image-name> | jq '.[0].RootFS.Layers' # [ # "sha256:7e01a...", # "sha256:b2c3d...", # ... # ] # Count the layers directly docker inspect <image-name> | jq '.[0].RootFS.Layers | length' # 9Each sha256 in
RootFS.Layersis a filesystem layer, excluding metadata instructions. This is the number of lowerdir layers used bydocker run, with an additional upperdir for the container itself.
3. Core Instructions at a Glance
FROM — Choose a Base Image
FROM ubuntu:22.04 # Start from an existing image
FROM golang:1.21-alpine AS builder # Name a stage (used with COPY --from)
FROM scratch # Start with nothing (suitable for statically compiled binaries)RUN — Execute Commands in an Image Layer
# Each RUN creates a new layer
RUN apt-get update
RUN apt-get install -y nginx # ❌ Two RUN instructions leave apt cache that cannot be removed
# ✅ Combine into one instruction and clean up immediately after installation
RUN apt-get update && \
apt-get install -y nginx && \
rm -rf /var/lib/apt/lists/*COPY vs ADD — Copy Files into the Image
COPY app /app/ # ✅ Recommended: straightforward copying of local files into the image
COPY --from=builder /out / # Copy from a previous build stage
ADD archive.tar.gz /app/ # ADD automatically extracts tar archives; otherwise behaves like COPY
ADD https://example.com/file /app/ # ADD can download URLs (not recommended; RUN curl offers more control)Principle: use COPY whenever possible; its behavior is more predictable than ADD.
CMD vs ENTRYPOINT — What Runs at Container Startup?
# CMD: the default command, replaced by arguments after docker run
CMD ["nginx", "-g", "daemon off;"]
# docker run my-image → executes nginx -g "daemon off;"
# docker run my-image /bin/bash → overrides CMD and executes /bin/bash
# ENTRYPOINT: entry program, with docker run arguments appended to it
ENTRYPOINT ["nginx"]
CMD ["-g", "daemon off;"]
# docker run my-image → nginx -g "daemon off;"
# docker run my-image -t → nginx -t (CMD is replaced; ENTRYPOINT stays)| Combination | Behavior |
|---|---|
CMD only | docker run <img> [args] → args replace CMD directly |
ENTRYPOINT only | docker run <img> [args] → ENTRYPOINT + args |
ENTRYPOINT + CMD | docker run <img> [args] → ENTRYPOINT + args (args replace CMD) |
Practical rule: put the program name in
ENTRYPOINTand default arguments inCMD. Users can then rundocker run my-image --debugwith only arguments, without repeating the program name.
WORKDIR — Set the Working Directory
WORKDIR sets a directory inside the image, not on your local machine. Think of it as cd inside the image: it tells Docker where subsequent RUN, CMD, and ENTRYPOINT instructions should start executing.
Why use WORKDIR? Consider what happens without it:
# ❌ Without WORKDIR, everything happens under the root directory /
COPY app / # Files scattered under /
RUN ls # Lists /, mixing bin, etc, and application files into a mess
CMD ["python", "/app/server.py"] # Requires absolute paths every time
# ✅ With WORKDIR, operations stay in the project directory
WORKDIR /app # Create /app in the image; subsequent operations happen here
COPY . . # Copy files into /app/
RUN ls # List /app/: clean and clear
CMD ["python", "server.py"] # Relative paths work because the directory is already /appHow does WORKDIR differ from RUN cd? This often confuses beginners:
# ❌ Wrong: cd applies only to this RUN's shell; the next RUN returns to /
RUN cd /app
RUN touch file.txt # Creates file.txt in /, not /app!
# ✅ Correct: WORKDIR persists
WORKDIR /app
RUN touch file.txt # Creates /app/file.txt
RUN ls # Lists /app/Each RUN launches a new shell, so cd does not persist across instructions. WORKDIR changes image-layer metadata, making all subsequent RUN, CMD, and ENTRYPOINT operations start from that directory.
Recommendation: always use absolute paths (
WORKDIR /app, notWORKDIR app). They are clearer and avoid behavior depending on whether a previous WORKDIR was/or another directory.
Does
WORKDIRcreate a layer? With BuildKit,WORKDIR /appcreates a small layer of about 8KB containing directory inode metadata (.and..entries). It is not purely metadata (SIZE ≠ 0B), yet much smaller than layers produced by RUN/COPY. Strictly speaking, it occupies the middle ground between pure metadata and a substantial filesystem layer: it uses a little disk space, but the amount is effectively negligible. This explains why the hands-on example has fiveRootFS.Layersentries instead of four.
ENV vs ARG — Variables
# ARG: build-time variables, available only during docker build and not retained in the image
ARG VERSION=1.0.0
RUN echo "Building version $VERSION"
# ENV: environment variables, retained in the image and readable at runtime
ENV APP_ENV=production
ENV PATH="/app/bin:$PATH" # Often used to extend PATH
# docker build --build-arg VERSION=2.0.0 . ← Override ARG at build time
# docker run -e APP_ENV=staging my-image ← Override ENV at runtimeEXPOSE — Declare Ports
EXPOSE 8080 # ⚠️ Only documentation and support for -P random port publishing; does not publish the port
# To actually publish it, use docker run -p 8080:8080VOLUME — Declare Mount Points
VOLUME /data # Declare that /data should be mounted from the host
# ⚠️ Creates a new layer here; later RUN modifications to /data are discarded
# Actual mounting still uses docker run -v or compose volumesUSER — Switch Users
RUN useradd -m appuser
USER appuser # All subsequent RUN/CMD/ENTRYPOINT instructions use this user4. Layer Caching—Why Order Matters
Docker caches the result of each build instruction. On the next build, if the instruction and context are unchanged, it reuses the cache instead of executing again.
# ❌ Poor cache use
COPY . /app # Any source change invalidates this layer
RUN apt-get install -y nodejs # Forces this layer to run again too, wasting time
# ✅ Effective cache use
RUN apt-get install -y nodejs # 1. Install dependencies first (rarely changes, nearly always cached)
COPY package.json package-lock.json /app/ # 2. Copy dependency manifests
RUN npm ci # 3. Install npm packages (cached if package.json is unchanged)
COPY . /app # 4. Copy source last (changes often, but earlier layers stay cached)Core principle: frequently changing content goes later; stable content goes earlier.
5. Multi-Stage Builds—A Powerful Way to Shrink Images
The biggest problem with compiled languages (Go, Rust, Java, C++) is that the build environment is large and heavy, while the final output is only a binary.
# ❌ Single stage: the entire compiler toolchain stays in a huge image
FROM golang:1.21
COPY . .
RUN go build -o server .
CMD ["./server"]
# Final image ≈ 800MB (Go toolchain + source + binary)
# ✅ Multiple stages: separate building from running
FROM golang:1.21 AS builder # Stage 1: compile
COPY . .
RUN go build -o server .
FROM alpine:3.19 # Stage 2: run (a fresh base image)
COPY --from=builder /go/server /server # Copy only the build output
CMD ["/server"]
# Final image ≈ 15MB (only alpine + one binary)Why is the final image smaller? The key: every
FROMis a reset button.Stages 1 and 2 are two entirely independent images, not images glued together. Installing the Go toolchain, downloading dependencies, and compiling all happen in the temporary "builder" image. At stage 2,
FROM alpine:3.19means "discard everything above and start again from alpine." ThenCOPY --from=builderselects only the compiled binary to copy into the new image.Imagine cooking in a kitchen (stage 1), with pots, utensils, oil, and seasonings covering the counter. When you move to the dining room (stage 2), you carry only the finished dish; the kitchen equipment does not come to the table. The final image has no Go compiler, source code, or packages downloaded by
go mod download, only a clean, small binary.Verify this directly with
docker history: the final layer list contains only alpine layers plus one COPY layer. None of stage 1'sRUN go buildlayers appears.
Multi-stage builds also work for frontend projects, not just compiled languages:
# Multi-stage build for a React/Vue/Angular frontend
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build # Produces the dist/ directory
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
# Final image ≈ 40MB (nginx + static files only); build-time node_modules is discarded6. Common Practical Patterns
Pattern 1: Run as a Non-Root User
FROM alpine:3.19
RUN adduser -D appuser
COPY app /app
RUN chown -R appuser:appuser /app
USER appuser
CMD ["/app/server"]Pattern 2: Health Checks
FROM nginx:alpine
COPY default.conf /etc/nginx/conf.d/
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD curl -f http://localhost/health || exit 1Pattern 3: Reduce Build Context with .dockerignore
# .dockerignore file (alongside Dockerfile)
node_modules/
.git/
*.md
.env
dist/During a build, Docker sends the entire directory to the daemon as the build context. .dockerignore excludes unnecessary files, speeding up builds and preventing sensitive files such as .env from accidentally entering the image.
Pattern 4: Handle Signals Correctly with tini
FROM alpine:3.19
RUN apk add --no-cache tini
COPY app /app
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["/app/server"]tini is a lightweight init process that forwards signals such as SIGTERM and reaps zombies. If docker stop takes ten seconds, the application probably does not handle PID 1 signals correctly. Adding tini can solve this.
Docker 1.13+ can inject tini automatically with
docker run --init ..., without installing it in the image.
Pattern 5: Use Build Cache Mounts
# BuildKit's --mount=type=cache lets package-manager caches survive across builds
# syntax=docker/dockerfile:1
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci
COPY . .
RUN npm run buildBuildKit's --mount=type=cache persists cache directories for package managers such as npm ci, apt-get, and pip install across builds, greatly accelerating repeated builds.
7. Common Mistakes and Fixes
| Problem | Cause | Fix |
|---|---|---|
| Very large image (>1GB) | Build toolchain was not removed | Use multi-stage builds, or install and clean up in the same RUN |
docker build downloads dependencies every time | COPY . . comes before RUN npm install | COPY package.json → RUN npm install → COPY . . |
| Container exits immediately | No foreground process keeps running | Ensure CMD/ENTRYPOINT starts a foreground process (nginx needs daemon off;) |
docker stop takes a long time | Process does not handle SIGTERM | Use tini, docker run --init, or proper application signal handling |
Environment variable empty during docker build | ARG and ENV confused | ARG is available only at build time; ENV at build time and runtime |
COPY --from=builder cannot find a file | Misspelled stage name or incorrect path | Check the AS alias and use a path inside that stage |
/data is empty in later RUN instructions | Changes after a VOLUME declaration are discarded | Do not modify that directory after declaring VOLUME |
8. Quick Reference
| Instruction | Purpose | Creates a layer? | Notes |
|---|---|---|---|
FROM | Select a base image | - | Must come first |
RUN | Execute a command | ✅ | Main layer-producing instruction |
COPY | Copy local files | ✅ | Recommended, predictable behavior |
ADD | Copy and automatically extract | ✅ | Prefer COPY where possible |
CMD | Default startup command | ❌ | Can be replaced by docker run arguments |
ENTRYPOINT | Entry program | ❌ | Not replaced; arguments are appended |
WORKDIR | Change working directory | ✅ (≈8KB) | Small layer for directory inodes; absolute paths recommended |
ENV | Set environment variables | ❌ | Writes only image JSON metadata and stays in the image |
ARG | Build arguments | ❌ | Exists only at build time |
EXPOSE | Declare ports | ❌ | Documentation only; does not publish ports |
VOLUME | Declare mount points | ✅ | Initializes a volume; later RUN changes to the directory are discarded |
USER | Switch users | ❌ | Affects all subsequent instructions |
HEALTHCHECK | Health check | ❌ | Tells Docker how to determine container health |
SHELL | Select the shell | ❌ | Windows images may need ["powershell", "-Command"] |
Summary
Three core principles for good Dockerfiles:
- Reduce layers: combine
RUNinstructions where possible; install and clean up within one layer. - Use the cache: stable content first (system dependencies), frequent changes last (application code).
- Use multi-stage builds: separate build and runtime environments, keeping only runtime requirements in the final image.
Revisit Docker Filesystems Explained and you will see that each Dockerfile
RUN/COPYsimply adds a directory under/var/lib/docker/overlay2/or containerd'ssnapshots/. An image is this collection of directories; a container stacks them withmount -t overlay. Writing Dockerfiles well means managing those layers well.