What is the difference between distroless and Alpine base images?
Alpine is a complete, if small, Linux distribution. It is built on musl libc and BusyBox, ships the apk package manager, and includes a shell (/bin/sh). You can apk add whatever you need at build time or exec into a running container to poke around. Its footprint stays small because the base itself contains very little.
Distroless images remove the distribution entirely. They contain only what a language runtime needs at execution time: CA certificates, timezone data, glibc where the runtime requires it, and an optional non-root user. There is no shell, no package manager, and no coreutils. You copy in your binary or application and run it directly. Because the standard images are built from Debian packages, they use glibc rather than musl.
Two other bases are useful for comparison. scratch is an empty image, suitable only for fully static binaries that bring their own certificates. "Slim" variants are trimmed glibc-based distributions that still keep a shell and package manager.
| Base | libc | Shell | Package manager | Typical use |
|---|---|---|---|---|
| scratch | none | no | no | Static binaries |
| Distroless | glibc (or none) | no | no | Runtime-only production images |
| Alpine | musl | yes | apk |
Small images that still need tooling |
| Slim | glibc | yes | yes | Broad compatibility with fewer packages |
Teams adopt minimal bases for practical reasons. Smaller images pull faster during deploys and autoscaling events, and they consume less registry storage. Fewer installed packages also means fewer CVEs to triage and fewer components to rebuild when an upstream fix lands.
How does a multi-stage build reduce Docker image size?
A single-stage build ships the entire toolchain to production. If you build a Go service on the official golang image, the final image contains the compiler, the module cache, your source tree and every package the build needed. The running service uses none of them.
A multi-stage build separates the two jobs. The builder stage has the full SDK and produces one artifact, in this case a static binary built with CGO_ENABLED=0. The runtime stage starts from a fresh base and copies in only that binary. Layers from the builder stage are discarded, so the compiler and cache never reach the final image.
Build the same service three ways:
- Single-stage on
golang. - Multi-stage onto Alpine. Create an unprivileged user with
adduser -S, copy the binary withCOPY --chown=app:app, and setUSER app. - Multi-stage onto distroless. Use a
:nonroottag, which already defines anonrootuser, and copy with--chown=nonroot:nonroot.
In both runtime variants, use exec-form ENTRYPOINT ["/app/server"]. Distroless has no shell to interpret shell form. On Alpine, exec form makes the binary PID 1, so it receives SIGTERM directly.
Illustrative estimate: the single-stage image can be several hundred megabytes. Both multi-stage variants usually land in the tens of megabytes, and the difference between Alpine and distroless is small compared with the drop from dropping the toolchain.
Don't rely on that estimate. Measure your own images. docker image ls shows the total size of each image, and docker history <image> shows which instruction added how many bytes.
# One Dockerfile, three targets. Build and measure:
# docker build --target single -t svc:single .
# docker build --target alpine -t svc:alpine .
# docker build --target distroless -t svc:distroless .
# docker image ls svc # total size per tag
# docker history svc:alpine # bytes added by each instruction
# Builder: full Go SDK, produces one static binary.
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/server ./cmd/server
# 1) Single-stage baseline: ships compiler, module cache and source.
FROM build AS single
ENTRYPOINT ["/out/server"]
# 2) Multi-stage onto Alpine: only the binary, owned by an unprivileged user.
FROM alpine:3.20 AS alpine
RUN addgroup -S app && adduser -S -G app app
COPY --from=build --chown=app:app /out/server /app/server
USER app
# Exec form: the binary is PID 1 and receives SIGTERM directly.
ENTRYPOINT ["/app/server"]
# 3) Multi-stage onto distroless: :nonroot already defines the nonroot user.
FROM gcr.io/distroless/static-debian12:nonroot AS distroless
COPY --from=build --chown=nonroot:nonroot /out/server /app/server
USER nonroot
# No shell in this image, so shell-form ENTRYPOINT would not work.
ENTRYPOINT ["/app/server"]
A single Dockerfile that builds one Go service as a single-stage image, a non-root Alpine image and a non-root distroless image, with the commands to compare their sizes using docker image ls and docker history.
Which base image should you use for Go, Java, Python and Node?
…contributed each layer. With that baseline, the right base depends mostly on how your language produces its runtime artifact.
| Language | Distroless option | Alpine option | What dominates image size |
|---|---|---|---|
| Go (CGO disabled) | static, or scratch |
Rarely needed | The binary itself |
| Java | Java variant (glibc JRE) | musl-built JRE | JRE plus application JARs |
| Python | Python variant | Official Alpine Python image | Interpreter plus installed packages |
| Node | Node.js variant | Official Alpine Node image | node_modules |
Go is the easy case. With CGO_ENABLED=0 the binary has no libc dependency, so it runs on distroless static or scratch. Prefer static: it already includes CA certificates, timezone data and a non-root user, which you would otherwise copy into scratch yourself.
Java, Python and Node behave differently. The runtime and dependencies account for most of the image, so the base layer is a small share of the total. Pruning dev dependencies, removing unused packages, or building a trimmed JRE with jlink usually saves more than switching from Alpine to distroless. Python on Alpine also often has to compile packages from source because fewer prebuilt wheels target musl. Section 4 covers this.
Distroless images are hard to customize because they have no package manager. To add a system library, such as an image codec for a Python package, you copy the .so file from a builder stage. You then have to resolve its transitive dependencies with ldd. Keep the builder on the same distribution release as the runtime so the glibc versions match.
# Build stage: full Go toolchain, discarded after the build
FROM golang:1.22-bookworm AS build
WORKDIR /src
# Download modules first so this layer is cached when only source changes
COPY go.mod go.sum ./
RUN go mod download
COPY . .
# CGO_ENABLED=0 produces a statically linked binary with no libc dependency.
# -trimpath removes local paths; -s -w strip symbol and debug tables.
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" \
-o /out/server ./cmd/server
# Runtime stage: distroless static has no shell, package manager or libc.
# It does include CA certificates, tzdata and a nonroot user (UID 65532),
# which you would have to copy in by hand if you used scratch.
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
# The :nonroot tag already defaults to this user; stating it keeps intent explicit
USER nonroot:nonroot
EXPOSE 8080
# Exec form is required: there is no shell in the image to parse a command string
ENTRYPOINT ["/server"]
A multi-stage Dockerfile that builds a CGO-disabled Go binary and runs it on distroless static, which already includes CA certificates, timezone data and a non-root user.
When should you avoid Alpine? musl vs glibc compatibility risks
Alpine replaces glibc with musl libc. Most application code never notices, but anything that links against libc directly, or depends on glibc-specific behavior, can fail or behave differently.
Native dependencies
Many prebuilt Python wheels target glibc (manylinux). A growing number of projects publish musllinux wheels, but not all of them do. When no matching wheel exists, pip falls back to building from source. That build needs a compiler and headers in the image, can take a long time, or can fail outright. Node is similar: native modules often ship glibc-only prebuilt binaries, so on Alpine they either recompile through node-gyp or fail to load at runtime.
Runtime behavior
musl's DNS resolver differs from glibc's. It queries the configured nameservers in parallel, and it handles search and ndots options from resolv.conf differently. In Kubernetes, which relies on search domains, this can show up as intermittent or slow lookups. musl's default thread stack size is also much smaller than glibc's, which can crash deeply recursive or thread-heavy code. Its memory allocator can be noticeably slower under allocation-heavy, multithreaded workloads.
Testing before you switch
None of these issues appear in a simple smoke test. They tend to surface under real traffic, which is why they usually reach production unnoticed. Before switching, check for problems in this order:
- Run the full integration suite against the Alpine image itself, not just the build.
- Check native dependencies. Try
pip install --only-binary=:all:to find packages that have no musl wheels, and runlddon bundled.sofiles. - Run load tests side by side with the current image, and compare latency, memory use and DNS error rates.
#!/usr/bin/env bash
# Pre-switch checks for an Alpine (musl) candidate image.
# Run from the repo root. Image names are placeholders.
set -euo pipefail
CANDIDATE="myservice:alpine-candidate"
# 1. Find Python dependencies that have no musllinux wheel.
# --only-binary=:all: forbids source builds, so pip fails and names
# the first package that would otherwise be compiled on Alpine.
# Match the Python version to the one in your real base image.
docker run --rm -v "$PWD/requirements.txt:/tmp/requirements.txt:ro" \
python:3.12-alpine \
pip install --only-binary=:all: -r /tmp/requirements.txt
# 2. Inspect every native library and Node addon inside the built image.
# glibc-only binaries show up as missing libraries ("not found") or,
# with musl's ldd, as "Error relocating" for missing glibc symbols.
docker run --rm --entrypoint sh "$CANDIDATE" -c '
find /app /usr/local/lib -type f \( -name "*.so*" -o -name "*.node" \) 2>/dev/null |
while read -r lib; do
out=$(ldd "$lib" 2>&1 || true)
if echo "$out" | grep -qE "not found|Error relocating"; then
echo "BROKEN: $lib"
echo "$out" | grep -E "not found|Error relocating"
fi
done
'
# 3. Run the integration suite inside the candidate image itself,
# so tests exercise musl at runtime, not just at build time.
# Replace the command with your project's test entry point.
docker run --rm --entrypoint "" "$CANDIDATE" \
python -m pytest tests/integration
# 4. Next: deploy the candidate next to the current image and run the
# same load test against both. Compare p99 latency, memory use and
# DNS errors in the target environment.
echo "Static checks passed. Run side-by-side load tests next."
A shell script that checks an Alpine candidate image before the switch: it finds dependencies without musl wheels, flags glibc-only native libraries and Node addons with ldd, and runs the integration suite inside the image.
Does a minimal base image improve container security?
Yes, but the gains are narrower than CVE dashboards suggest.
Fewer packages, fewer findings
A vulnerability scanner reports CVEs against the packages it can identify in an image. A distroless image has no shell, no package manager and few shared libraries, so it has fewer packages to report against. Alpine is also small, but it still ships BusyBox and apk. The practical benefit is less triage. When a scan returns a handful of findings instead of dozens, a team is more likely to read each one.
A lower count measures how many packages are installed. It does not measure how exploitable the service is. A single unpatched library that your service actually loads matters more than ten CVEs in utilities that never run. Scanner coverage of minimal images also varies. Scanners usually identify packages by reading package-manager metadata. If you copy a binary or runtime into an image without that metadata, the scanner may not report its CVEs at all, and an empty report can mean the scanner saw nothing rather than that nothing is there.
Less to work with after a compromise
The stronger argument concerns what happens after exploitation. On Alpine, an attacker who gets code execution can open a shell, run apk add to install tools, and use BusyBox utilities to explore or move data out. Distroless removes those tools, so the attacker has to bring their own. This raises the effort needed but does not prevent the attack.
What a minimal base does not cover
A minimal base image does not replace these other controls:
- patching the image regularly
- running the process as a non-root user
- mounting the root filesystem read-only
- dropping Linux capabilities the service does not need
# Kubernetes Deployment for a service built on a minimal base image.
# The base image reduces what is installed; these settings restrict
# what the running process is allowed to do.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
spec:
replicas: 2
selector:
matchLabels:
app: orders-api
template:
metadata:
labels:
app: orders-api
spec:
securityContext:
runAsNonRoot: true # kubelet refuses to start the container as UID 0
runAsUser: 65532 # unprivileged UID; match the user baked into the image
seccompProfile:
type: RuntimeDefault # use the container runtime's default syscall filter
containers:
- name: api
# Pin by tag or digest and rebuild on base-image updates; a minimal base still needs patching.
image: registry.example.com/orders-api:1.4.2
ports:
- containerPort: 8080
securityContext:
allowPrivilegeEscalation: false # block setuid binaries from gaining privileges
readOnlyRootFilesystem: true # attacker cannot write tools into the image filesystem
capabilities:
drop: ["ALL"] # the service binds 8080, so it needs no capabilities
volumeMounts:
- name: tmp
mountPath: /tmp # the only writable path, for files the app must create
volumes:
- name: tmp
emptyDir: {}
A Kubernetes Deployment that pairs a minimal base image with the controls it does not replace: non-root execution, a read-only root filesystem, dropped capabilities and no privilege escalation.
How do you debug and operate containers without a shell?
Without a shell, docker exec -it <container> sh stops working, so plan your debugging options before an incident.
Debugging options
- Debug variants. Distroless publishes
:debugtags that add a BusyBox shell. Use them in staging or for a temporary redeploy. Don't ship them as the default, because that brings back the tooling you removed. - Ephemeral containers.
kubectl debugattaches a container with its own tools to a running pod. With--target, it shares the process namespace of your app container, so you can inspect processes and reach the app's filesystem through/proc/<pid>/root. The production image stays unchanged. - Built-in observability. Structured logs, health and readiness endpoints, and metrics let you answer most questions without entering the container at all.
What breaks in minimal images
- CA certificates. Outbound TLS fails with certificate errors if there is no CA bundle.
scratchhas none. - Timezone data. Time zone lookups fail or silently fall back to UTC. Alpine needs the
tzdatapackage.scratchhas no zoneinfo at all. - Users.
scratchhas no/etc/passwd, so setUSERto a numeric UID. - Permissions. Files copied from the build stage are owned by root, so a non-root process can't write to them. Use
COPY --chown. - Shell-form CMD. Shell form runs through
/bin/sh -c, so the container won't start without a shell. Use exec form.
Effect on incident response
Suppose your cluster doesn't allow ephemeral containers and your logs are thin. During an outage, someone has to rebuild with a debug image and redeploy. That takes time, and the restart can clear the very state you were trying to inspect. Before you adopt shell-less images, set up ephemeral containers and good observability.
How should you patch and pin base images over time?
Neither base image patches itself. A running container keeps whatever libraries were in the image at build time, so the patching model is about how fixes reach the base image and how quickly you rebuild on top of it.
Alpine ships fixes as apk packages, and the official image tags are periodically republished with updated packages. You can run apk upgrade during your build, but that makes builds non-reproducible and hides drift. It is cleaner to adopt the refreshed base image.
Distroless images have no package manager. They are assembled from upstream Debian packages and republished when those packages change. The only way to get a fix is to pull a newer image and rebuild.
Either way, a tag like alpine:3 or distroless/static is a moving pointer. If you pin by tag, two builds a week apart can produce different images. If you pin by digest (image@sha256:...), builds are reproducible, but the pin freezes every CVE that existed on the day you chose it. A digest pinned months ago is a snapshot of old vulnerabilities.
The fix is to keep the pin and automate moving it:
- Automated update pull requests. Configure a dependency update bot to watch base image tags and open a PR that bumps the digest when the tag moves. CI then runs your tests against the new base before merge, and the change is reviewable and revertible.
- Scheduled rebuilds. Run a nightly or weekly CI job that rebuilds and rescans images even when your code hasn't changed. This catches services that rarely get commits, which are the ones most likely to go stale.
- Scan the result, not just the Dockerfile. Fail or flag builds whose final image contains known fixable vulnerabilities, so a stale digest shows up as a visible failure.
Distroless vs Alpine vs scratch vs slim: which should you choose?
The right base image is the one whose failure modes your team can absorb most cheaply. Smaller images save pull time and scanner noise. Every option below shifts some cost elsewhere, into compatibility debugging, manual setup or incident diagnosis.
| Base | Choose it when | Avoid it when | Main engineering cost |
|---|---|---|---|
| Distroless | Compiled or runtime-bundled services (Go, JVM, Node, Python) with a stable dependency set | You rely on shelling in during incidents and have no ephemeral debug-container workflow | Learning to debug from outside the container |
| Alpine | You want a small image that still has a shell and package manager, and musl compatibility is verified under load | Native extensions, DNS-sensitive code, or glibc-linked wheels and binaries | Time spent chasing musl-specific behaviour |
| Scratch | Fully static binaries, and the team reliably adds CA certificates, timezone data and a non-root user | Anything dynamically linked, or nobody owns those missing files | Outages from missing certs, wrong time zones or running as root |
| Slim (glibc) | Native dependencies, mixed toolchains, or limited debugging tooling | You need the smallest attack surface and can meet distroless's constraints | More packages to triage when scanners report CVEs |
Default to distroless for most backend services. Its CVE triage load is low and its runtime is predictable.
Move to slim when a musl bug or a missing system library has cost you more engineering hours than a larger image ever will. A few extra megabytes are cheaper than a week of intermittent failures.
Use Alpine and scratch on purpose, not by default. Both are good choices only after you have verified what they leave out.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to distroless vs alpine, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.