Sub topic 12
Troubleshooting: Containers That Will Not Stop or Remove
This chapter assumes you can run docker ps, docker stop, docker start, and docker rm. It also assumes you know that stopping sends a signal and that removal deletes the container's writable layer. Here you will learn to read the symptoms when those commands misbehave, find the cause, and fix it without reaching for destructive commands too early.
The working model
Most stop and remove problems come from three facts:
docker stopsendsSIGTERMto the main process of the container (PID 1). It waits for the grace period, which is 10 seconds by default. If the process is still alive, Docker sendsSIGKILL.- The kernel treats PID 1 specially. A PID 1 process that has not installed a handler for a signal does not get the default action for that signal.
SIGTERMis silently ignored, and onlySIGKILLworks. docker rmonly works on containers that are not running, unless you add-f. Removal also fails if something else still holds the container's name, filesystem, or resources.
The diagram shows a practical order of investigation.
Start with evidence
Before changing anything, look at what Docker knows. These three commands answer most questions.
docker ps -a --filter "name=web"
docker inspect --format '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' web
docker logs --tail 20 webThe State.Status field is one of created, running, paused, restarting, removing, exited, or dead. A container in restarting is being brought back by a restart policy. A container in removing or dead is part of a failed or interrupted removal. The exit code also tells you how the process ended:
| Exit code | Meaning |
|---|---|
| 0 | The process exited cleanly on its own or after handling `SIGTERM`. |
| 137 | Killed by `SIGKILL` (128 + 9). Often means the grace period ran out, or the out-of-memory killer acted. |
| 143 | Ended by `SIGTERM` (128 + 15). The normal result of a stop with no handler. |
If the code is 137 and OOMKilled is true, memory pressure killed the container. A stop did not.
Problem: stop takes 10 seconds
A container that takes exactly the grace period to stop is almost always ignoring SIGTERM. You can reproduce this with sleep, which installs no signal handler.
docker run -d --name stubborn alpine sleep 300
time docker stop stubborn
docker inspect --format '{{.State.ExitCode}}' stubbornThe stop takes about 10 seconds, and the exit code is 137. sleep runs as PID 1, so the kernel ignores SIGTERM. Docker waits, then sends SIGKILL.
Run the same program under a small init process. --init makes Docker start a tiny init program as PID 1, which forwards signals to your command.
docker rm stubborn
docker run -d --init --name polite alpine sleep 300
time docker stop polite
docker inspect --format '{{.State.ExitCode}}' politeNow the stop returns almost immediately with exit code 143. The init process receives SIGTERM, passes it to sleep, and sleep is not PID 1 anymore, so the default action applies.
A second cause is the shell form of CMD or ENTRYPOINT in a Dockerfile. Written as CMD node server.js, the command runs as a child of /bin/sh -c. The shell is PID 1, and it often does not forward signals to its child. Use the exec form instead.
FROM node:20-alpine
WORKDIR /app
COPY server.js .
CMD ["node", "server.js"]With the exec form, node is PID 1. Your program must still handle SIGTERM itself, because PID 1 gets no default action. In Node.js, that means calling process.on("SIGTERM", ...) and closing servers and connections.
Some programs expect a different signal for graceful shutdown. Nginx, for example, shuts down gracefully on SIGQUIT. Images can declare this with STOPSIGNAL in the Dockerfile, and you can override it with docker run --stop-signal SIGQUIT.
Problem: the container comes back
You stop a container and it is running again a moment later, or after a Docker restart. Check the restart policy and the tool that created the container.
docker inspect --format '{{.HostConfig.RestartPolicy.Name}}' webThe result is one of no, on-failure, always, or unless-stopped. Behavior differs in an important way:
- With
always, a container you stopped by hand stays stopped until the Docker daemon restarts. Then it starts again. This surprises people after a reboot. - With
unless-stopped, a container you stopped by hand stays stopped even after a daemon restart. - With
on-failure, Docker restarts only after a non-zero exit code.
To change the policy on an existing container, use docker update.
docker update --restart=no web
docker stop webIf a container is recreated after you remove it, Docker is not the cause. Another tool is. Docker Compose, Swarm, or Kubernetes may be managing it. Remove the container through that tool, for example docker compose down, or it will be created again. You can often spot managed containers by labels.
docker inspect --format '{{json .Config.Labels}}' webA label such as com.docker.compose.project tells you Compose owns this container.
Problem: the process will not die at all
If docker stop returns an error or the container is still running afterward, escalate in steps.
- Run
docker kill web. This sendsSIGKILLimmediately. The process cannot catch or ignore it. - Run
docker inspect --format '{{.State.Status}}' webto confirm the state changed. - If it is still running, check whether the daemon is healthy with
docker info. A hung daemon needs a restart through your service manager, for examplesudo systemctl restart docker.
A process stuck in uninterruptible sleep (state D in ps) cannot receive any signal, including SIGKILL, until its kernel call returns. This usually points to a hung network filesystem mount or a failing disk. Docker cannot fix this. You need to resolve the underlying I/O problem.
Problem: removal errors
Cannot remove a running container
Error response from daemon: cannot remove container "/web": container is running: stop the container before removing or force removeEither stop first, or force the removal.
docker stop web && docker rm web
docker rm -f webdocker rm -f sends SIGKILL and removes the container in one step, so the process gets no chance to shut down cleanly. Prefer stop then remove for services that write data. Use -f for throwaway containers.
Name already in use
docker: Error response from daemon: Conflict. The container name "/web" is already in use by container "3f9a...". You have to remove (or rename) that container to be able to reuse that name.An old container, running or stopped, still has the name. Container names must be unique, even for stopped containers. Check with docker ps -a --filter "name=web", then remove it with docker rm web. If you want to keep it, use docker rename web web-old. For one-off runs, --rm prevents this problem because the container disappears when it exits.
No such container, or an ambiguous ID
Error response from daemon: No such container: web usually means a typo, or the container was already removed. It can also mean you are talking to a different Docker context or daemon. Check with docker context ls. If you use a short ID and get multiple IDs found with provided prefix, give more characters of the ID.
Removal already in progress, dead, or device busy
Sometimes an interrupted removal leaves a container in removing or dead state. You may see these messages:
Error response from daemon: removal of container web is already in progress
Error response from daemon: driver "overlay2" failed to remove root filesystem for web: device or resource busyThe first usually clears by itself. Wait a few seconds and list again. The second means another process still holds a mount from the container's filesystem. Common sources are a backup agent, an antivirus scanner, or another container that mounted the same path. Retry docker rm -f web. If it keeps failing, find what holds the mount with grep web /proc/*/mountinfo (on the host, as root, using part of the container ID), stop that program, and try again. A restart of the Docker daemon is the last resort. Containers that are restarting or running with a restart policy will return afterward, so check the policy first.
Permission denied
permission denied while trying to connect to the Docker daemon socket means your user cannot reach /var/run/docker.sock. It is not about the container. Add your user to the docker group and log in again, or use sudo. Remember that access to the Docker socket is effectively root access on the host.
Problem: disk space is not freed after removal
You removed containers but docker system df still shows large usage. docker rm deletes the writable layer, but named volumes and anonymous volumes survive unless you also pass -v. Images remain as well. Check volumes with:
docker volume ls --filter dangling=trueA dangling volume is not attached to any container. If you are sure the data is disposable, remove it with docker volume rm name. If Docker says the volume is in use, a container, even a stopped one, still references it. Find it with docker ps -a --filter volume=name.
A short checklist
- Read
State.Status, the exit code, and the restart policy first. - A stop that takes about 10 seconds means
SIGTERMwas ignored. Fix the PID 1 problem with exec form, a signal handler, or--init. - A container that returns was restarted by a policy or by Compose, Swarm, or Kubernetes.
- Use
docker killbefore more drastic steps. Usedocker rm -fonly when losing a graceful shutdown is acceptable. - Name conflicts mean a stopped container still exists. List with
docker ps -a.
Exercise
You run docker stop api and it always takes exactly 10 seconds. docker inspect --format '{{.State.ExitCode}}' api prints 137. The Dockerfile has CMD python app.py. Explain what is happening and give two ways to fix it.
Show answer
The shell form runs /bin/sh -c python app.py, so the shell is PID 1 and does not forward SIGTERM to Python. Docker waits out the 10 second grace period and then sends SIGKILL, which gives exit code 137. Fixes: change to the exec form CMD ["python", "app.py"] and add a SIGTERM handler in the program (Python's signal.signal), or run the container with docker run --init so an init process forwards signals. Raising the timeout with -t would only make the stop slower.
Exercise
After docker rm web succeeds, docker run --name web nginx:alpine works. Earlier, without the docker rm, the same run command failed. What was the error, and why did removal fix it?
Show answer
Docker reported a conflict: the container name "/web" was already in use by the old container. Names are unique across running and stopped containers, so a stopped container still holds its name until it is removed (or renamed with docker rename).