FROM and RUN
Every image is built on top of another image. FROM chooses that starting point, and RUN executes commands on top of it to install and prepare things. Together they decide most of your image's size, security and build speed.
FROM: choosing a base image
FROM python:3.12-slim
FROM node:22-alpine AS build
FROM --platform=linux/amd64 eclipse-temurin:21-jre
FROM scratchFROM image:tagstarts a new build stage from that image.AS namenames the stage so later stages can copy from it (see Multi-stage Builds).--platformchooses the CPU architecture when the base image has several.scratchis the special empty image: no shell, no libraries, nothing. Useful for single static binaries.
Official images usually come in several variants:
| Variant | Example tag | Based on | Trade-off |
|---|---|---|---|
| default | python:3.12 |
Debian with build tools | biggest; compilers available |
| slim | python:3.12-slim |
minimal Debian | good default for most apps |
| alpine | python:3.12-alpine |
Alpine Linux (musl libc) | tiny, but some binary wheels and glibc programs do not work |
| distroless | gcr.io/distroless/python3 |
just the runtime | no shell or package manager: small attack surface, harder to debug |
The model below picks the smallest base that satisfies an app's requirements. The sizes are typical compressed sizes, rounded.
bases = [
# name, MB, shell, glibc, compilers
("python:3.12", 400, True, True, True),
("python:3.12-slim", 45, True, True, False),
("python:3.12-alpine", 18, True, False, False),
("gcr.io/distroless/python3", 20, False, True, False),
]
def choose(needs_shell, needs_glibc, needs_compiler):
fits = [b for b in bases
if (b[2] or not needs_shell)
and (b[3] or not needs_glibc)
and (b[4] or not needs_compiler)]
return min(fits, key=lambda b: b[1])
apps = {
"pure-Python API": (True, False, False),
"API using numpy wheels": (True, True, False),
"builds a C extension": (True, True, True),
"locked-down runtime": (False, True, False),
}
for app, needs in apps.items():
name, mb, *_ = choose(*needs)
print(f"{app:<24} -> {name} (~{mb} MB)")pure-Python API -> python:3.12-alpine (~18 MB)
API using numpy wheels -> python:3.12-slim (~45 MB)
builds a C extension -> python:3.12 (~400 MB)
locked-down runtime -> gcr.io/distroless/python3 (~20 MB)
Tip: start with the
-slimvariant. Switch to Alpine only after checking that your dependencies work with musl libc, and pin the tag (3.12-slim, notlatest).
RUN: executing build commands
RUN executes a command inside a temporary container from the current image state, then saves the filesystem changes as a new layer.
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*This one RUN step does three things on purpose:
apt-get updateandapt-get installare in the same step. If they were separate, Docker could reuse a cached, weeks-oldupdatelayer and the install would fail or install stale packages.--no-install-recommendsskips optional extra packages.rm -rf /var/lib/apt/lists/*deletes the package index in the same layer, so it never ends up in the image.
Remember from the Images lesson that deleting files in a later step does not shrink the image. This model adds up the layer sizes for both approaches:
def build(steps):
image_size = 0
present = {}
for step, added, removed in steps:
layer = sum(added.values())
for path in removed:
present.pop(path, None) # hidden, but still stored below
present.update(added)
image_size += layer
print(f" {step:<34} layer {layer:>3} MB")
print(f" image size {image_size} MB, visible files {sum(present.values())} MB")
print("separate steps:")
build([
("RUN apt-get update", {"apt-lists": 40}, []),
("RUN apt-get install -y curl", {"curl": 8}, []),
("RUN rm -rf /var/lib/apt/lists/*", {}, ["apt-lists"]),
])
print("one combined step:")
build([
("RUN update && install && rm lists", {"curl": 8}, []),
])separate steps:
RUN apt-get update layer 40 MB
RUN apt-get install -y curl layer 8 MB
RUN rm -rf /var/lib/apt/lists/* layer 0 MB
image size 48 MB, visible files 8 MB
one combined step:
RUN update && install && rm lists layer 8 MB
image size 8 MB, visible files 8 MB
Both images contain the same visible files, but the first one carries 40 MB of hidden package lists forever.
Shell form, && and failing commands
Shell-form RUN runs under /bin/sh -c. The build fails if the last command's exit status is non-zero. Chaining with && stops at the first failure; chaining with ; keeps going and can hide errors:
def sh(commands, joiner):
status = 0
for name, exit_code in commands:
if joiner == "&&" and status != 0:
print(f" skip {name}")
continue
status = exit_code
print(f" run {name} -> exit {exit_code}")
return status
steps = [("download app.tar.gz", 22), ("tar -xzf app.tar.gz", 2), ("echo done", 0)]
for joiner in ("&&", ";"):
print(f"joined with '{joiner}':")
status = sh(steps, joiner)
print(" build", "FAILED" if status else "succeeded (the error was hidden!)")joined with '&&':
run download app.tar.gz -> exit 22
skip tar -xzf app.tar.gz
skip echo done
build FAILED
joined with ';':
run download app.tar.gz -> exit 22
run tar -xzf app.tar.gz -> exit 2
run echo done -> exit 0
build succeeded (the error was hidden!)
Note: pipes hide failures too:
RUN curl -fsSL URL | tar -xzonly reportstar's status. AddSHELL ["/bin/bash", "-o", "pipefail", "-c"]before such a step to make a failingcurlfail the build.
Test yourself
Why should apt-get update and apt-get install be in the same RUN instruction?
- It is required syntax
- So a cached old
updatelayer is never combined with a new install list - It makes the image use Alpine
- Because
RUNcan only appear once
Which base image contains no files at all?
- alpine
- busybox
- scratch
- debian:slim
RUN make build ; echo finished: make build fails with exit code 2. What happens?
- The build fails at this step
- The build continues, because the last command (
echo) succeeded - Docker retries the step
- The image is tagged
failed