Sub topic 3
Removing Docker Containers Automatically with `--rm`
Assume Docker is installed, the daemon is running, and you know the difference between an image and a container. A stopped container still has a writable layer and metadata. Removing the container deletes that container object.
Automatic removal with `--rm`
Use --rm for short-lived containers. Docker removes the container automatically when its main process exits.
docker run --rm alpine echo "hello"After echo finishes, docker ps -a does not show the container. This is useful for one-time commands, tests, and temporary jobs. Do not use it when you need to inspect the stopped container later.
What removal deletes and keeps
Removing a container deletes its writable container layer, configuration, logs, and metadata. It does not delete the image used to create it.
Volumes need separate care:
- A named volume is normally kept when its container is removed.
- An anonymous volume is also kept by a normal
docker rm. docker rm -vremoves anonymous volumes attached to that container.docker run --rmremoves anonymous volumes when the container exits, but it does not remove named volumes.
Pruning stopped containers
For containers created without --rm, remove all stopped containers with a confirmation prompt:
docker container pruneTo review candidates first:
docker ps -a --filter "status=exited"Pruning containers does not remove images or named volumes. Use --volumes only after confirming that unused anonymous volumes are safe to delete.
Troubleshooting removal
A running container cannot be removed with ordinary docker rm. Stop it first:
docker stop web
docker rm webIf it does not stop within the grace period, use:
docker kill web
docker rm webdocker kill sends SIGKILL by default, so the process cannot clean up gracefully. Use docker rm -f web only when force removal is acceptable.
Exercise
What happens to a named volume when its container is removed?
Show answer
The named volume remains unless you remove it separately.