Sub topic 9
Removing containers automatically with --rm
Earlier chapters showed how to stop a container and remove it with docker rm. Many containers are throwaway: a one-off script, a quick shell in an image, a test run. Removing each of these by hand adds up. The --rm flag on docker run tells Docker to remove the container for you as soon as it exits.
This chapter assumes you know the container lifecycle (created, running, exited, removed), can read docker ps -a output, and understand what docker rm and docker stop do. It also assumes you know the difference between an image and a container.
What --rm does
Add --rm to docker run and Docker removes the container when its main process exits.
docker run --rm alpine echo "hello"
docker ps -aThe first command prints hello and exits. The second command does not list the container, because Docker deleted it the moment echo finished.
Without --rm, the same run leaves an exited container behind:
docker run alpine echo "hello"
docker ps -a --filter "status=exited"You will see one alpine container with a randomly generated name and a status like Exited (0) 2 seconds ago. Run this a hundred times and you have a hundred stopped containers, each holding a small writable layer and a log file.
The removal is done by the Docker daemon, not by the docker client. That detail matters in the cases below.
The lifecycle with and without --rm
A normal container passes through an exited state and stays there until you remove it. A --rm container skips that resting state.
The consequence is that an auto-removed container can never reach the "stopped, waiting to be restarted" state. You cannot docker start it afterward, and you cannot inspect it.
Checking whether a container uses --rm
The setting is stored in the container's host configuration. You can read it while the container is running:
docker run -d --rm --name sleeper alpine sleep 60
docker inspect --format '{{.HostConfig.AutoRemove}}' sleepertrueA container started without --rm prints false. This is a quick way to confirm why a container vanished.
Combining --rm with stop, kill, and detached mode
--rm works with detached containers (-d). The container runs in the background, and Docker removes it when it stops, whether the process finished on its own or you stopped it.
docker run -d --rm --name web nginx:alpine
docker ps
docker stop web
docker ps -aAfter docker stop web, the container is gone from docker ps -a. The same happens with docker kill web. Both commands end the main process, and the daemon then removes the container.
This changes a habit from the previous chapters. For a normal container, the sequence is stop, then rm. For a --rm container, docker stop is the whole cleanup. If you run docker rm web right after docker stop web, you get an error such as No such container: web, because there is nothing left to remove.
The name is released immediately
A container name must be unique among existing containers, including stopped ones. A stopped container named web blocks you from creating another one named web:
docker run -d --name web nginx:alpine
docker stop web
docker run -d --name web nginx:alpineThe last command fails with a conflict error saying the name /web is already in use. You must run docker rm web first.
With --rm, the name is freed when the container exits, so this pattern works repeatedly:
docker run -d --rm --name web nginx:alpine
docker stop web
docker run -d --rm --name web nginx:alpine
docker stop webThis makes --rm a good fit for scripts and test runs that start a container with a fixed name each time.
Exit codes still reach you
Removing the container does not lose the exit status. In the foreground, docker run exits with the same code as the container's main process:
docker run --rm alpine sh -c 'exit 3'
echo $?3The shell prints 3. This is why --rm is common in CI jobs and Makefiles: the step passes or fails based on the command inside the container, and nothing is left to clean up afterward.
Where --rm fits and where it does not
| Situation | Use --rm? | Reason |
|---|---|---|
| One-off command such as `docker run --rm alpine date` | Yes | Nothing to keep. |
| Interactive shell to explore an image (`-it`) | Yes | You do not need the container afterward. |
| Test or CI job | Yes | The exit code is enough, and cleanup is automatic. |
| Long-running service you will stop and start | No | You need `docker start` to work later. |
| Container that crashes and you must debug it | No | You lose `docker logs` and `docker inspect` after exit. |
| Container with a restart policy (`--restart`) | Not allowed | Docker rejects the combination. |
The restart policy conflict follows from the lifecycle. A restart policy tells Docker to bring a container back after it exits. --rm tells Docker to delete it after it exits. The two requests contradict each other, so docker run returns an error if you pass both.
What you lose when the container is removed
Once a --rm container exits, everything attached to the container object is deleted:
- Its logs.
docker logs namefails withNo such container. - Its metadata.
docker inspect namefails the same way, so you cannot read the exit code, the OOM-killed flag, or the finish time. - Its writable layer, which holds every file the process created or changed inside the container.
- The ability to run
docker start,docker restart,docker cp, ordocker commiton it.
The loss of logs is the one that surprises people. Suppose a container crashes right after you start it:
docker run -d --rm --name api my-api:latest
docker logs apiIf the process crashed at startup, the second command can fail because the container is already gone, and the crash message went with it. To debug, run the same command without --rm, read docker logs, and add --rm back once it works.
--rm and volumes
The earlier chapter on what removal deletes covered volumes. --rm follows the rules of docker rm -v: it removes the container's anonymous volumes, but not named volumes or bind mounts.
| Mount type | Example | Removed by --rm? |
|---|---|---|
| Anonymous volume | `-v /data` | Yes |
| Named volume | `-v appdata:/data` | No |
| Bind mount | `-v "$PWD/out:/data"` | No, host files are untouched |
You can see the difference by counting volumes before and after. First, a normal container with an anonymous volume, removed with plain docker rm:
docker volume ls -q | wc -l
docker run --name keep -v /data alpine sh -c 'echo hi > /data/note.txt'
docker rm keep
docker volume ls -q | wc -lThe second count is one higher than the first. The volume survived docker rm and is now an unnamed leftover with a long hexadecimal name. Now the same run with --rm:
docker volume ls -q | wc -l
docker run --rm -v /data alpine sh -c 'echo hi > /data/note.txt'
docker volume ls -q | wc -lBoth counts match. Docker removed the anonymous volume along with the container.
For data you want to keep, use a named volume or a bind mount. Both are safe to combine with --rm:
docker run --rm -v appdata:/data alpine sh -c 'echo saved > /data/note.txt'
docker run --rm -v appdata:/data alpine cat /data/note.txtsavedEach container is deleted on exit, but the named volume appdata keeps the file, and the second container reads it.
--rm in Docker Compose
Compose has the same idea for one-off commands. docker compose run starts a new container for a service and, by default, leaves it behind after it exits. Add --rm to remove it:
docker compose run --rm web python manage.py migrateContainers created by docker compose up are not affected by this flag. They are managed with docker compose down.
Cleaning up after containers started without --rm
You will still meet containers that were started without --rm. Two commands from the earlier chapters handle them:
docker ps -a --filter "status=exited" --format "table {{.Names}}\t{{.Status}}\t{{.Image}}"
docker container pruneThe first lists them so you can see what will go. The second removes all stopped containers after a confirmation prompt. Habitual use of --rm for throwaway runs keeps this list short.
Common mistakes
- Using --rm on a service, then trying to restart it. After
docker stop, the container no longer exists, sodocker startfails. Recreate it withdocker run, or leave--rmoff. - Expecting logs after a crash. The logs are deleted with the container. Reproduce without
--rm. - Writing results inside the container. Output saved to the container's own filesystem disappears. Write to a bind mount or named volume.
- Combining with --restart. Docker rejects it. Pick one behavior.
- Assuming a named volume is cleaned up. It is not. Remove it yourself with
docker volume rm NAMEwhen you no longer need it.
Exercise
You run docker run -d --rm --name job -v results:/out alpine sh -c 'date > /out/time.txt; sleep 30' and wait for it to finish. Which of these still exist afterward: the container job, the file /out/time.txt in the volume results, and the container's logs? Why?
Show answer
Only the file in the named volume results remains. --rm removed the container job and its logs when the process exited. Named volumes are not removed by --rm, so time.txt is still in results. You can read it with docker run --rm -v results:/out alpine cat /out/time.txt.
Exercise
A teammate says: "I started my test database with docker run -d --rm --name testdb postgres. It stopped, and now docker start testdb says there is no such container." Explain what happened and give two ways to prevent it.
Show answer
Because of --rm, Docker deleted the container as soon as it stopped, so there is nothing to start. To prevent it, either run the container without --rm and remove it yourself with docker rm when finished, or keep --rm and put the database files on a named volume so you can create a new container with docker run and reuse the data. Note that a restart policy is not an option, because --rm cannot be combined with --restart.
Exercise
Write a command that runs ls /data inside an alpine container, lists the files of a host directory named reports in the current directory, and leaves no container behind.
Show answer
docker run --rm -v "$PWD/reports:/data" alpine ls /data
The bind mount shows the host directory inside the container, and --rm deletes the container when ls exits. The host files are not touched.