Module 4 Lesson 2: Managing Container Lifespans
Master the lifecycle management of Docker. Learn the technical difference between stop and kill, and how to safely prune your environment of abandoned containers.
Module 4 Lesson 2: Managing Container Lifespans
As you develop with Docker, you will quickly end up with hundreds of containers in various states. Managing this "Zoo" of processes correctly is essential for system health.
1. Stop vs. Kill (The Polite vs. The Violent)
docker stop
Sends a SIGTERM signal to the process inside.
- This is "Polite." It says: "Hey app, finish your current database save, close your files, and then quit."
- Docker waits 10 seconds. If the app hasn't quit, it then sends a "Kill."
docker kill
Sends a SIGKILL signal.
- This is "Violent." It instantly stops the process. This can lead to Data Corruption in databases because the app didn't have time to finish its work.
2. Restarting vs. Recreating
docker restart: Simply stops and starts the same container instance. The writable layer (and any files you created there) is preserved.- The "Docker Way" (Recreation): Usually, when we want to "Restart," we actually Delete the old container and Run a new one from the same image. This ensures we start with a "Fresh" environment.
Visualizing the Process
graph TD
Start[Input] --> Process[Processing]
Process --> Decision{Check}
Decision -->|Success| End[Complete]
Decision -->|Retry| Process
3. The Grand Cleanup: Pruning
Your disk space is finite. Docker creates a lot of garbage:
- Stopped containers
- Unused networks
- Dangling images (Images with no name)
- Build cache
The Commands:
docker container prune: Deletes all stopped containers.docker image prune: Deletes all unused images.docker system prune: The "Nuke" Option. Deletes everything unused. (Add-ato delete all images not actively used by a container).
4. Bulk Actions in the CLI
Need to stop every container on your machine at once? Use command substitution:
# Stop all running containers
docker stop $(docker ps -q)
# Delete all containers
docker rm $(docker ps -aq)
-q: "Quiet" mode. Returns only the IDs.
Exercise: The Cleanup Drill
- Start 5 containers running
nginxin detached mode. Give them the namestest1,test2, etc. - List them using
docker ps. - Stop only
test1andtest3. - Run
docker container prune. Look at the output. Which containers were deleted? Which ones remain? - Why is it dangerous to run
docker system prune -ain a production environment?
Summary
Managing container lifespans is about balance. You need to know when to be "Polite" with a stop and when to "Nuke" your environment with a prune. Keeping your system clean ensures that your disk space remains available for the images that actually matter.
Next Lesson: Connecting the dots: Container networking basics.