Sub topic 2
Stopping, Starting, and Removing Containers
Assume Docker is installed and the daemon is running. You should also know the difference between an image, which is a packaged template, and a container, which is a running or stopped instance of that image.
Stopping containers
docker stop asks a running container to exit cleanly:
docker stop webThe command accepts a container name or ID. A stopped container still exists, so you can start it again without creating a new container.
How stop works: signals, timeouts, and `docker kill`
Docker first sends SIGTERM, a signal that asks the main process to shut down. The process can catch this signal, close connections, and save state. Docker waits for a grace period, which is typically 10 seconds on Linux. If the process has not exited, Docker sends SIGKILL.
Set a different grace period with -t:
docker stop -t 30 webThis gives the application 30 seconds to exit. docker kill skips the graceful request and sends SIGKILL by default:
docker kill webUse docker kill when a container is unresponsive or when immediate termination is required. It can prevent cleanup code from running.
> callout warning > Stopping a container does not remove it. Removing it deletes the container's writable layer, so recreate anything that must persist through a volume or an external service.
Starting and restarting containers
Start an existing stopped container with docker start:
docker start webRestart combines stopping and starting:
docker restart webYou can provide a stop timeout to restart as well:
docker restart -t 30 webRemoving containers
Remove a stopped container with docker rm:
docker rm webA running container must be stopped first. For an immediate forced removal, use:
docker rm -f webThis forcefully stops the container before removing it. A named volume remains unless you explicitly remove the volume separately. Anonymous volumes are retained by default, but -v removes them with the container:
docker rm -v webExercise
Which command should you normally use for a clean shutdown, and what happens if the process does not exit before the timeout?
Show answer
Use docker stop. Docker sends SIGTERM first, then sends SIGKILL after the grace period expires.