Sub topic 13
Keeping disk usage down in the first place
Earlier chapters showed how to find and prune what Docker has already accumulated. This chapter covers the habits and settings that slow that accumulation, so each prune has less to remove.
This chapter assumes you can write a basic Dockerfile and run docker build and docker run. It also assumes you know that images are built from layers and that containers are created from images. You also need to be able to edit a file as root on a Linux host, or use the Docker Desktop settings screen.
Where growth comes from
Most disk growth has a small number of causes. Each one has a matching preventive habit.
| Source of growth | Preventive habit |
|---|---|
| Exited containers from one-off commands | Run them with `--rm` |
| Large build contexts and bloated layers | Use `.dockerignore` and clean up inside the same layer |
| Build tools shipped in the final image | Use multi-stage builds |
| Rebuilt tags leaving dangling images | Build less often, tag deliberately, prune on a schedule |
| Container logs that never rotate | Set log limits in `daemon.json` or per container |
Remove one-off containers automatically with --rm
A container that exits is not deleted. It stays in docker ps -a with its writable layer, and any anonymous volume it created stays too. Containers you start for a single task are the main source of this clutter.
docker run --rm alpine:3.20 echo "hello"With --rm, the daemon deletes the container when its main process exits. It also removes the container's anonymous volumes, which are volumes created by a VOLUME instruction or by -v /path without a name. Named volumes and bind mounts are not touched.
Use --rm for these cases:
- Scripts and CI jobs that run a tool and read its output.
- Debugging shells such as
docker run --rm -it ubuntu:24.04 bash. - Test runs that you do not want to inspect afterwards.
Do not use --rm for a container whose logs or filesystem you may need after a crash. Once the container is gone, docker logs and docker cp no longer work on it. For long-running services, set a restart policy and let your orchestrator or Compose manage the lifecycle.
In Compose, docker compose run --rm web pytest does the same for one-off service runs. Without --rm, each compose run leaves a container behind.
Keep the build context small with .dockerignore
When you run docker build ., the client sends the context (the directory) to the builder. A COPY . . instruction then copies everything it can see into a layer. Without a .dockerignore file, that includes .git, dependency folders, local build output, and sometimes secrets.
A .dockerignore file in the context root lists patterns to exclude:
.git
node_modules
dist
*.log
.env
**/__pycache__
Dockerfile
.dockerignoreThis helps in three ways:
- Smaller layers, because files you never need are not copied.
- Faster builds, because less data is sent to the builder.
- Better caching, because a change to an ignored file no longer invalidates the
COPY . .layer.
Patterns follow Go's filepath.Match rules with an extra ** wildcard. A line starting with ! makes an exception. To ignore everything except what you need, start with * and add exceptions:
*
!package.json
!package-lock.json
!srcBe careful with an allow-list like this. If you forget a needed file, the build fails or the image is missing it. Run docker build after changing the file to catch this.
Keep layers small
Every RUN, COPY, and ADD instruction creates a layer. A layer stores what that instruction added or changed. A later layer that deletes a file does not shrink the image, because the earlier layer still contains the file.
This pattern wastes space:
FROM debian:12-slim
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*The package index lands in the first RUN layer and stays there. Do the install and the cleanup in one instruction:
FROM debian:12-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*--no-install-recommends also avoids pulling in optional packages. You can see the cost of each layer with docker history:
docker history myapp:latestChoosing a smaller base image helps too. debian:12-slim and alpine variants are much smaller than full images. Alpine uses musl instead of glibc, so test your application on it before you switch.
Ship only what runs: multi-stage builds
A multi-stage build uses several FROM instructions in one Dockerfile. Early stages hold compilers and build tools. The final stage copies only the finished artifact from them. Only the last stage ends up in the image you tag and push.
Take a small Go program in main.go:
package main
import "fmt"
func main() {
fmt.Println("hello from a small image")
}Here is a Dockerfile with two stages:
FROM golang:1.22 AS build
WORKDIR /src
COPY main.go .
RUN go mod init example.com/hello \
&& CGO_ENABLED=0 go build -o /out/app .
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The golang image is several hundred megabytes because it contains the whole toolchain. The final image contains only a minimal base and one static binary. Compare the two:
docker build -t hello:multi .
docker image ls golang:1.22
docker image ls hello:multi
docker run --rm hello:multiThe same idea works for Node (build in a full image, copy dist and production dependencies into a slim one), Java (JDK to JRE), and front-end sites (Node build, then an nginx image serving static files).
The build stage is still cached on your machine. It does not appear in the final image, but it takes space in the build cache until you run docker builder prune. Multi-stage builds shrink what you ship and pull. They do not shrink your local build cache.
Cache mounts for package managers
If a build downloads many packages, BuildKit cache mounts keep the package cache out of the image layers entirely:
# syntax=docker/dockerfile:1
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]The pip cache lives in the build cache, not in the image. It speeds up repeat builds and is removed by docker builder prune.
Be deliberate with tags
When you rebuild an image under a tag that already exists, such as myapp:latest, the tag moves to the new image. The old image loses its tag and becomes dangling. Rebuilding many times a day therefore creates many dangling images.
Two habits reduce this:
- Tag with something meaningful, such as a version or commit hash (
myapp:1.4.2ormyapp:3f9c2ab), and remove the ones you no longer need withdocker image rm. - Run
docker image pruneafter a burst of local rebuilds, or let a scheduled prune handle it.
Pulling many versions of the same base image has the same effect. If your Dockerfiles use FROM node:20, the mutable tag moves as new patch releases appear, and each pull leaves the previous image dangling. Pinning to a specific tag stops the churn, but you then have to update it yourself.
Limit container log growth
By default, Docker uses the json-file logging driver. It writes each container's output to a JSON file on the host and does not rotate it. A chatty container that runs for months can fill a disk.
Set limits for every new container in /etc/docker/daemon.json:
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}Each container then keeps at most three files of 10 MB, so 30 MB at most. Restart the daemon to apply this, for example with sudo systemctl restart docker. A reload is not enough for log driver settings.
Existing containers keep their old settings. You must recreate them (stop, remove, and run again, or docker compose up -d --force-recreate) for the limits to apply.
You can also set limits for a single container:
docker run -d --name web \
--log-opt max-size=10m --log-opt max-file=3 \
nginx:1.27In a Compose file, use the logging key:
services:
web:
image: nginx:1.27
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"Docker also has a local log driver, which rotates logs by default and stores them in a more compact format. Both drivers work with docker logs. If you ship logs to a central service with a driver such as syslog or fluentd, check whether docker logs still works for that driver, because some remote drivers do not support reading.
Verify the active settings on a running container:
docker inspect --format '{{.HostConfig.LogConfig}}' webPrevention does not replace pruning
These habits slow the growth, but they do not stop it. Dangling images, build cache, and unused networks still appear over time. Combine the practices above with a scheduled, age-limited prune, which a later chapter covers. A prune that runs weekly on a host with rotated logs and small images has little to remove and little to get wrong.
Exercise
A CI job runs docker run alpine:3.20 sh -c "echo test" on every commit. After a month, docker ps -a shows thousands of exited containers. What single flag fixes this for new runs, and what extra thing does it remove besides the container itself?
Show answer
Add --rm (docker run --rm alpine:3.20 sh -c "echo test"). It removes the container's writable layer along with the container, and it also removes any anonymous volumes that the container created. Named volumes and bind mounts are not removed. The existing exited containers still need docker container prune.
Exercise
You set max-size and max-file in /etc/docker/daemon.json and restart Docker, but a container started last week keeps growing its log. Why, and what do you do?
Show answer
Log driver options are applied when a container is created. Containers that already exist keep their old settings. Recreate the container (stop and remove it, then run it again, or use docker compose up -d --force-recreate) so it picks up the new limits. You can confirm with docker inspect --format '{{.HostConfig.LogConfig}}' <name>.
Exercise
A Dockerfile installs build tools in one RUN and deletes them in a later RUN, but the image does not get smaller. Why, and how do you fix it?
Show answer
Each instruction creates its own layer, and the files added by the first RUN remain stored in that layer even after a later layer deletes them. Run the install and the cleanup in the same RUN instruction, or move the build tools into an earlier stage of a multi-stage build and copy only the finished artifact into the final stage.