Docker Container Lifecycle Explained: Understanding Container States
Understanding how Docker containers transition between different states is fundamental to building, debugging, and maintaining containerized applications. This guide breaks down the container lifecycle from creation to deletion, explaining the underlying mechanisms, transition commands, and real-world debugging implications.
1. The Problem: Why Do Containers Suddenly Stop?
When developers first start working with Docker, they often encounter a frustrating scenario: they containerize an application, run it, verify that it works, and then suddenly find that the container has stopped.
Without a clear understanding of the container lifecycle, this behavior can trigger unnecessary panic:
- Did the application crash?
- Is there a configuration error?
- Is Docker broken?
In reality, a stopped container is often behaving exactly as designed. Lacking this foundational knowledge makes debugging painful, log files confusing, and production issues feel completely random. Mastering the container lifecycle makes Docker predictable, giving you the confidence to diagnose issues systematically rather than relying on guesswork.
2. The Core Mental Model: The Human Analogy
To understand how a container behaves, it is helpful to compare it to a familiar real-world lifecycle.
Real-Life Analogy: The Human Lifecycle
Just like humans, containers follow a structured biological progression:
- Birth (Created): The container is prepared and configured but has not yet started executing.
- Active Work (Running): The container actively consumes resources (CPU, memory) to perform its primary task.
- Rest (Paused): The container's processes are temporarily frozen in time, consuming no CPU resources, but retaining their state in memory.
- Expiration (Stopped/Removed): The container finishes its job or is terminated, eventually being cleaned up permanently.
3. The 5 Stages of the Container Lifecycle
A Docker container can exist in one of five primary states. Understanding these states prevents common misconceptions about what is happening to your application behind the scenes.
4. Stage 1: Created (The Prepared State)
In the Created state, Docker prepares the container environment, but the application inside does not yet run.
- Under the Hood: Docker sets up the read-write container file system layer, configures network settings, prepares environment variables, and maps ports.
- Resource Consumption: No CPU or memory is consumed because no processes have started.
Real-Life Analogy
Think of the Created state as a meal that has been fully cooked and packaged inside a delivery box, but has not yet been dispatched to the customer. Everything is ready to go, but nothing is actively moving.
Note: A common beginner mistake is assuming that once a container is "created," it is actively running. A created container is merely a configured blueprint waiting for an execution signal.
5. Stage 2: Running (The Active State)
The Running state is the active phase of the container's lifecycle. This is where your application executes its code and handles traffic or background tasks.
- Under the Hood: Docker starts the container's primary process (defined by the
ENTRYPOINTorCMDinstruction in the Dockerfile). - Resource Consumption: The container actively utilizes host CPU, memory, and disk I/O.
- The Golden Rule of Container Lifespans: A container remains in the running state only as long as its main process (PID 1) is alive.
If the main process finishes its execution or crashes, the container immediately transitions to the **Stopped** state.
Real-Life Analogy
A running container is like an employee actively working at their desk. As long as there is work to do and the employee is active, the job continues. Once the task is complete or the employee leaves, the desk becomes quiet.
6. Stage 3: Paused (The Frozen State)
The Paused state allows you to temporarily suspend a container's execution without terminating its processes or losing its in-memory state.
- Under the Hood: Docker uses the Linux kernel's
cgroupsfreezer subsystem to suspend all processes inside the container. The processes are frozen in their exact state. - Resource Consumption:
- CPU: Drops to .
- Memory: Remains allocated. The RAM state is preserved so the container can resume instantly.
Real-Life Analogy
Pausing a container is exactly like pausing a movie on Netflix. The frame freezes instantly. When you hit play (resume), the movie continues from the exact millisecond you paused it, without needing to reload or restart from the beginning.
7. Stage 4: Stopped (The Dormant State)
In the Stopped state, the container's processes are completely terminated, but the container's configuration, file system changes, and history remain intact on the host disk.
Why Do Containers Stop?
There are four primary reasons a container transitions to the stopped state:
- Task Completion: The application finished its designated job (e.g., a database migration script or data processing job completed successfully).
- Application Crash: The application encountered a fatal error or ran out of memory (OOM), causing the main process to exit with a non-zero code.
- System Error: An underlying infrastructure or Docker daemon error occurred.
- Manual Intervention: A developer or orchestration tool explicitly stopped the container.
Note: Stopping a container is normal behavior. Containers are designed to be ephemeral. If a container's job is finished, it should stop to free up host system resources.
8. Stage 5: Removed (The Terminated State)
The Removed state is the final phase of the lifecycle.
- Under the Hood: Docker permanently deletes the container's writeable layer, metadata, logs, and execution history from the host system.
- What Survives? The read-only Docker Image used to create the container remains completely untouched. You can use this image to spin up a brand-new container at any time.
Real-Life Analogy
Removing a container is like throwing a cardboard shipping box into the recycling bin. The box (container) is gone forever. However, if you have the original blueprint or manufacturing mold (the Docker Image), you can easily manufacture an identical new box. Note that any custom items you stored in the old box are lost unless you backed them up externally (e.g., using Docker Volumes).
9. Command-to-State Transitions
Docker provides a set of commands to transition containers between these lifecycle states.
1. docker run
This command performs two operations under the hood: it creates the container from the specified image and immediately starts it.
# Creates and starts an Nginx container in detached mode
docker run -d --name web-server nginx
2. docker start
This command takes an existing, Stopped container and transitions it back to the Running state. It preserves the container's previous writeable file system layer.
# Starts a previously stopped container
docker start web-server
3. docker stop
This command gracefully shuts down a Running container. It sends a SIGTERM signal to the main process (PID 1), giving it time to clean up connections and save state. If the process does not exit within a grace period (typically 10 seconds), Docker sends a SIGKILL signal to force termination.
# Gracefully stops a running container
docker stop web-server
4. docker rm
This command permanently deletes a Stopped container.
# Deletes a stopped container
docker rm web-server
Note: If you attempt to run
docker rmon a running container, Docker will throw an error. You must either stop the container first or force-remove it usingdocker rm -f.
10. Tabular Synthesis: Container States and Commands Reference
The following table summarizes the key characteristics of each container state:
11. Real-World Debugging & Production Mindset
Understanding the container lifecycle changes how you approach debugging in production environments:
1. The "Exited (0)" vs. "Exited (137)" Diagnostic
When a container stops, Docker records an exit code. Checking this code tells you why the container stopped:
- Exit Code
0: The main process completed successfully and exited voluntarily (e.g., a backup script finished its work). This is healthy behavior. - Exit Code
137: The container was terminated abruptly, often because it ran out of memory (OOM Killed) or was stopped viaSIGKILL. - Exit Code
1or other non-zero codes: The application crashed due to an internal runtime error, unhandled exception, or misconfiguration.
2. Decoupling Data from the Lifecycle
Because containers are designed to be removed (docker rm), never store persistent application data inside a container's writable layer. Always mount external storage (Docker Volumes or Bind Mounts) to ensure your data survives when a container is destroyed and recreated.
12. Summary and Key Takeaways
- Containers are Ephemeral: A container's life is directly tied to its primary process (PID 1). When that process ends, the container stops.
- Created Running: The
Createdstate means the file system and configurations are ready, but no processes are running and no CPU/RAM is being consumed. - Stopping is Normal: A stopped container is not necessarily a broken container; it often means the application simply finished its designated job.
- Pause Saves RAM State, Stops CPU: Pausing freezes processes using OS-level controls, dropping CPU usage to zero while keeping the RAM state intact for instant resumption.
- Removal is Permanent: Removing a container (
docker rm) deletes its writable layer and history. However, the underlying read-only Docker Image remains safe and can be used to spin up identical new containers. docker runis a Compound Command: It automates both the creation and startup phases of a container in a single step.