Let's cut the fluff. Here is exactly what you need to know about this concept to survive in a real production environment.
1The Container State Machine
Look, if you've ever dealt with this in production, you know exactly what the problem is. You know how to build Images and run them. Now, we dive into what happens while the container is alive. A Docker container is fundamentally a State Machine. It transitions between specific states: Created, Running, Paused, Stopped (Exited), and Dead. Understanding exactly how a container moves between these states is critical for operating production workloads and debugging failures. This isn't just academic theory—understanding the *why* behind this is what separates junior devs from senior engineers. When you deploy to a cluster, this is the mechanic that prevents catastrophic failure.
# 1. Created (Allocated, not started)
# 2. Running (Actively executing CMD)
# 3. Exited (Process finished or crashed)
# 4. Dead (Permanently deleted)
Status: OK
Success: Operation completed.
2The PID 1 Rule
Look, if you've ever dealt with this in production, you know exactly what the problem is. Why does a container transition from 'Running' to 'Exited'? The answer lies in the 'PID 1 Rule'. Every container has a primary process (defined by the CMD instruction in the Dockerfile). This primary process is assigned Process ID 1 inside the container. If PID 1 is running, the container is running. The exact millisecond that PID 1 finishes, crashes, or terminates, the Docker Daemon immediately powers off the entire container. This isn't just academic theory—understanding the *why* behind this is what separates junior devs from senior engineers. When you deploy to a cluster, this is the mechanic that prevents catastrophic failure.
# Scenario A: Web Server
CMD ["nginx", "-g", "daemon off;"]
# Runs forever -> Container stays UP.
# Scenario B: Batch Script
CMD ["echo", "Task Complete"]
# Echo finishes in 0.1s -> Container EXITs immediately.
Status: OK
Success: Operation completed.
3Restart Policies
Look, if you've ever dealt with this in production, you know exactly what the problem is. If a container powers off when the process crashes, what happens to your production web server if it encounters an unhandled exception at 3:00 AM? Without intervention, your website stays offline until you wake up. To fix this, Docker provides 'Restart Policies'. By passing the --restart=always flag, you command the Docker Daemon to act as a watchdog. If the container crashes, the Daemon will automatically reboot it instantly. This isn't just academic theory—understanding the *why* behind this is what separates junior devs from senior engineers. When you deploy to a cluster, this is the mechanic that prevents catastrophic failure.
# 1. No restart policy (Stays dead if crashes)
> docker run -d nginx
# 2. Watchdog Enabled (Auto-reboots on crash)
> docker run -d --restart=always nginx
Status: OK
Success: Operation completed.
