A container and its image are separate objects with separate delete commands.
image nginx:1.27 (read-only layers) docker rmi nginx:1.27
├── container web (writable layer) docker rm web
└── container old-web (writable layer) docker rm old-web| Command | Deletes | Keeps |
|---|---|---|
docker rm web | the container: writable layer, config, logs | the image |
docker rmi nginx:1.27 | the image | refuses while a container uses it |
Remove a stopped container
docker rm onceonceRemove a running container
docker rm refuses a running container:
Error response from daemon: cannot remove container "/web": container is running: stop the container before removing or force removeStop it first, or force it:
| Command | Effect |
|---|---|
docker stop web && docker rm web | clean shutdown, then remove |
docker rm -f web | SIGKILL, then remove |
Use -f for containers you do not need to shut down cleanly.
Remove every stopped container
docker container pruneWARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Deleted Containers:
6df65503b9904861b64e807f54c0a9ea9de1117f212819198963cddb08d64fa2
b4db45fbd84c20e79d6ef463d25229fa782b1d0b3463187c55b511b1ae755b2a
Total reclaimed space: 2.19kBRunning containers are not touched. -f skips the question. To remove a chosen set, pass IDs: docker rm $(docker ps -aq --filter status=exited).
Remove it automatically
--rm deletes the container as soon as its main process exits. Use it for one-off commands:
docker run --rm alpine:3.20 echo bye
docker ps -abye
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESThe logs go with it, so do not use --rm for a job you may need to debug.
Images stay
docker imagesREPOSITORY TAG IMAGE ID CREATED SIZE
nginx 1.27 9c00f3b0b0e0 2 weeks ago 192MB
alpine 3.20 73fa11e296d4 6 weeks ago 7.8MBThe next docker run nginx:1.27 starts at once without a download.
rmi refuses while a container uses the image
Error response from daemon: conflict: unable to remove repository reference "nginx:1.27" (must force) - container 011aea0e415a is using its referenced image 9c00f3b0b0e0The error names the container by short ID. Remove that container, then the image. Chapter 8 covers image cleanup.