Sub topic 8
Removing containers
This chapter assumes you can start containers with docker run, you know the difference between an image and a container, and you can read docker ps output. Removing a container deletes the container object and its writable layer. It does not delete the image the container was created from.
Why removal is a separate step
Stopping a container does not delete it. A stopped container keeps its name, its configuration, its logs, and the changes it made to its filesystem. It still shows up in docker ps -a, and you can start it again.
That is useful for debugging, but stopped containers pile up. Each one holds disk space and reserves its name. Removal is the step that releases both.
The container lifecycle ends like this:
Removing a stopped container
The basic command is docker rm, followed by one or more names or IDs.
docker run -d --name web nginx:alpine
docker stop web
docker rm webOn success, Docker prints the name or ID you gave it. After that, docker ps -a no longer lists the container, and the name web is free for reuse.
You can pass several containers at once:
docker rm web db cacheIf one of them fails, Docker reports an error for that one and still tries the rest. The exit status is non-zero if any removal failed, which matters in scripts.
docker container rm is the same command as docker rm. The longer form is the current command-group style, and the short form is kept as an alias. Use whichever your team prefers, but be consistent.
What happens when the container is running
docker rm refuses to remove a running container. You get an error like this:
Error response from daemon: cannot remove container "/web": container is running: stop the container before removing or force removeYou have two choices.
- Stop it first, then remove it. This gives the main process a chance to shut down cleanly.
- Force removal with
-f.
docker rm -f webWith -f, Docker sends SIGKILL to the main process and then removes the container. The process gets no chance to flush buffers, close connections, or write final data. Use -f for throwaway containers and for containers that are stuck. For a database or anything that writes to disk, stop it gracefully first.
Removing by name, ID, or ID prefix
Everything that identifies a container works with docker rm.
- The full name, such as
web. - The full 64-character ID.
- Any unique prefix of the ID, such as
3f4a.
If a prefix matches more than one container, Docker returns an ambiguity error instead of guessing. Type a few more characters and try again.
Names are safer than IDs when you work by hand. A short prefix typed from memory can point at a container you did not intend, and removal cannot be undone.
What removal deletes and what it keeps
This is the part that causes the most surprises. A container has several pieces, and docker rm treats them differently.
| Piece | Removed by `docker rm`? | Notes |
|---|---|---|
| Container metadata and name | Yes | The name becomes available again. |
| Writable layer | Yes | Every file the container created or changed inside its own filesystem is lost. |
| Container logs (default json-file driver) | Yes | Logs are stored with the container. |
| Image | No | Other containers can still use it. Remove images with `docker rmi`. |
| Named volumes | No | They outlive the container. |
| Bind mounts (host directories) | No | Docker never deletes host paths. |
| Anonymous volumes | Only with `-v` | Otherwise they stay behind, unnamed. |
The writable layer
An image is read-only. When a container starts, Docker adds a thin writable layer on top. Anything the process writes to a path that is not a volume or bind mount goes there. When you remove the container, that layer is deleted.
You can see what a container changed before you remove it:
docker diff webThe output marks added files with A, changed files with C, and deleted files with D. If something in that list matters, copy it out first:
docker cp web:/etc/nginx/nginx.conf ./nginx.confVolumes
Data you want to keep belongs in a volume or a bind mount, not in the writable layer. A named volume is created and named by you, or by Docker Compose:
docker run -d --name db -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=example postgres:16
docker rm -f db
docker volume lsAfter docker rm -f db, the volume pgdata is still listed. A new container that mounts pgdata sees the same data.
An anonymous volume is one that Docker creates without a name. This happens when an image declares a VOLUME instruction, or when you use -v /path with no name on the left side. The postgres image declares a volume for its data directory, so running it without -v pgdata:... creates an anonymous one.
By default docker rm leaves anonymous volumes behind. They get long random names and accumulate. To delete them together with the container, add -v:
docker rm -f -v webThe -v flag removes only anonymous volumes that belong to that container. It never removes named volumes.
To find volumes that nothing uses any more, list the dangling ones:
docker volume ls --filter dangling=trueRemoving containers automatically with --rm
If you only need a container for one task, ask Docker to remove it when it exits:
docker run --rm alpine echo "hello"The container runs, prints hello, exits, and is deleted. docker ps -a shows nothing left over.
--rm also removes anonymous volumes that the container created, the same as docker rm -v. That makes it a good fit for one-off commands, test runs, and interactive shells:
docker run --rm -it alpine shKeep these points in mind.
--rmis set when the container is created. You cannot add it to an existing container.- It conflicts with the
--restartpolicy. Docker rejects the combination of--rmand--restarton the same container. - A container removed this way leaves no logs. If a short-lived container fails and you need to see why, run it without
--rmand inspect it withdocker logsafterwards. - With
docker run -d --rm, a crash removes the evidence immediately.
Removing many containers
Using filters
Combine docker ps filters with the quiet flag -q, which prints only IDs:
docker ps -a -q --filter "status=exited"Pass that list to docker rm using command substitution:
docker rm $(docker ps -a -q --filter "status=exited")Always run the inner docker ps command on its own first and read the list. If the list is empty, docker rm is called with no arguments and prints a usage error. This is harmless, but noisy in scripts. On Linux you can avoid it with xargs -r:
docker ps -a -q --filter "status=exited" | xargs -r docker rmOther useful filters are name= for a name pattern and ancestor= for an image:
docker ps -a -q --filter "ancestor=nginx:alpine" | xargs -r docker rm -fUsing docker container prune
docker container prune removes all stopped containers in one step. It asks for confirmation first.
docker container pruneWARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N]Answer y to proceed. Docker then prints the IDs it removed and the disk space it reclaimed.
Two options make it more selective:
docker container prune --filter "until=24h"
docker container prune -f--filter "until=24h"removes only containers that stopped more than 24 hours ago. It also accepts timestamps.-fskips the confirmation prompt, which is useful in scheduled cleanup jobs.
Prune considers every container that is not running. That includes containers in the created state and containers you stopped on purpose and meant to start again. Check docker ps -a before you confirm.
docker container prune does not remove anonymous volumes. If you want those cleaned up too, run docker volume prune separately and read its confirmation text, because it removes every volume that no container uses.
Troubleshooting removal problems
| Symptom | Likely cause | What to do |
|---|---|---|
| `container is running` | You used `docker rm` on a running container. | Run `docker stop` first, or use `docker rm -f`. |
| `No such container` | Wrong name or ID, or it was already removed (for example by `--rm`). | Check `docker ps -a`. |
| `Conflict. The container name "/web" is already in use` when starting a new one | A stopped container still holds the name. | Remove the old container, or choose a new name. |
| `removal of container ... is already in progress` | Another `docker rm` is still running for this container. | Wait, then check `docker ps -a`. |
| `Error response from daemon: Unable to remove filesystem` or `device or resource busy` | A process or mount still uses the container's filesystem. | Retry. If it persists, restart the Docker daemon and remove again. |
| Container keeps coming back after removal | A restart policy was not the cause, since removal deletes it. Something else, such as Docker Compose, a systemd unit, or an orchestrator, is recreating it. | Stop the tool that owns it, for example `docker compose down`. |
| Disk is still full after removal | Images, volumes, or build cache take the space, not containers. | Check `docker system df` to see where the space goes. |
The name-conflict error is the most common. It looks like this:
docker: Error response from daemon: Conflict. The container name "/web" is already in use by container "3f4a...". You have to remove (or rename) that container to be able to reuse that name.Either remove the old one, or keep it and rename it:
docker rename web web-oldA safe removal routine
This sequence works for most situations.
- List what exists with
docker ps -a. - Check whether anything in the container is worth keeping, with
docker diffanddocker inspect. - Stop it with
docker stop. - Remove it with
docker rm, adding-vonly if its anonymous volumes are disposable. - Confirm with
docker ps -aand, if volumes were involved,docker volume ls.
Exercise
You run docker run -d --name cache -v /data redis:7. Later you run docker rm -f cache. Does the data in /data survive, and how would you delete it along with the container?
Show answer
Yes, the data survives. The -v /data flag creates an anonymous volume, and docker rm without -v leaves anonymous volumes in place. They show up in docker volume ls under a random name. To delete the volume together with the container, run docker rm -f -v cache. Because -f sends SIGKILL, it would be safer to run docker stop cache first and then docker rm -v cache.
Exercise
A teammate runs docker run -d --rm --name job myimage. The job crashes after two seconds, and now docker logs job reports No such container. Why, and what would you change to investigate the failure?
Show answer
The --rm flag removes the container as soon as it exits, and the container's logs are removed with it. To investigate, run the container again without --rm. After it crashes, use docker logs job and docker inspect job to see the output and exit code, then remove it with docker rm job once you are done.