6.1.4.2 Automatic Container Removal
A focused guide to Automatic Container Removal, connecting core concepts with practical Docker and container operations.
Automatic container removal, enabled through the --rm flag, deletes a container's writable layer and metadata immediately upon its exit, without requiring a separate, explicit removal step afterward — a convenient default for containers known to be temporary.
Enabling Automatic Removal
The --rm flag, supplied at creation time, instructs Docker to remove the container as soon as its main process exits, regardless of whether it exited successfully or with an error.
docker run --rm myapp:1.0 run-tests.sh
docker ps -a
After this container exits, it does not appear in the container listing at all, having been automatically removed the moment it stopped.
Why This Is Ideal for One-Off Commands
Containers created purely to perform a single, self-contained task — running a script, executing a one-off database migration — rarely need to persist after completing that task, making automatic removal a sensible default that prevents unnecessary accumulation.
docker run --rm myapp:1.0 python manage.py migrate
Why Automatic Removal Is Inappropriate for Long-Running Services
A long-running service container that might need its logs or final state inspected after an unexpected crash benefits from NOT being automatically removed, since investigating why it stopped becomes much harder once the container (and its logs accessible through docker logs) no longer exists.
docker run -d --name myapp myapp:1.0
Omitting --rm here preserves the container after it stops, allowing its logs and final state to still be inspected if needed.
Combining --rm With Interactive Use
--rm is particularly common for interactive, exploratory container sessions, where cleanup after the session ends is clearly desired.
docker run --rm -it ubuntu:22.04 bash
Why Automatic Container Removal Matters
Deliberately choosing --rm for genuinely temporary containers, while omitting it for containers whose state or logs might need to be inspected after stopping, keeps the local environment clean without sacrificing the ability to investigate unexpected failures when they matter.