Stopping and removing containers
- Version
- 29
- Review
- Draft
Summary#
docker stop signals the main process, SIGTERM unless the image or container sets another stop signal, and sends SIGKILL if it is still running after the grace period. docker rm removes a stopped container. Stopping alone keeps the container and its writable layer.
Syntax#
docker stop --timeout 30 CONTAINER
docker kill --signal HUP CONTAINER
docker rm CONTAINER
docker rm --force --volumes CONTAINER
Example#
The example uses a local alpine:3 image.
(
set -eu
clean="dlr-docker-commands-stop-clean-$$"
stuck="dlr-docker-commands-stop-stuck-$$"
trap 'docker rm -f "$clean" "$stuck" >/dev/null 2>&1 || true' EXIT
docker run --pull never --detach --name "$clean" --log-driver local alpine:3 sh -c \
'trap "echo received SIGTERM; exit 0" TERM; echo ready; while :; do sleep 1; done' >/dev/null
docker run --pull never --detach --name "$stuck" --log-driver local alpine:3 sh -c \
"trap '' TERM; echo ready; exec sleep 60" >/dev/null
tries=0
until docker logs "$clean" | grep -qx ready && docker logs "$stuck" | grep -qx ready; do
tries=$((tries + 1))
[ "$tries" -lt 30 ]
sleep 1
done
docker stop "$clean" >/dev/null
docker stop --timeout 1 "$stuck" >/dev/null
docker logs "$clean"
docker inspect --format 'handled signal: exit {{.State.ExitCode}}' "$clean"
docker inspect --format 'ignored signal: exit {{.State.ExitCode}}' "$stuck"
docker rm "$clean" "$stuck" >/dev/null
echo "removed"
)
Expected output#
ready
received SIGTERM
handled signal: exit 0
ignored signal: exit 137
removed
Common mistakes#
A shell script used as the entry point often keeps the application as a child process that never receives the stop signal. End the script with exec your-program so the program becomes the main process. docker kill sends SIGKILL by default. docker rm --force sends SIGKILL to a running container, then deletes its writable layer.
Version applicability#
Checked with Docker Engine 29. The default grace period is 10 seconds for Linux containers unless the container sets one. Exit status 137 means the process ended on SIGKILL, which can have causes other than docker stop. docker rm --volumes removes anonymous volumes only.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0