DevOpsLesson
DevOpsLesson

Free, comprehensive DevOps tutorials and learning roadmaps. Master Docker, Kubernetes, CI/CD, and more.

Stay Updated

Get notified about new tutorials and features.

Tutorials

  • What is DevOps?
  • Docker Tutorial
  • Terraform Tutorial
  • CI/CD Pipeline
  • All Tutorials

Roadmaps

  • DevOps Engineer
  • Cloud Engineer
  • SRE Path
  • All Roadmaps

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 DevOpsLesson. All rights reserved.

DOCKERKUBERNETESTERRAFORMAWSCI/CDLINUXGITDEVOPS ROADMAPCLOUD ROADMAPSRE ROADMAPGIT CHEATSHEETDOCKER CHEATSHEETK8S CHEATSHEETTF CHEATSHEETLINUX CHEATSHEETDOCKERFILE LINTERYAML VALIDATORCRON PARSERREGEX TESTER

Docker Tutorial

Introduction to docker
Why Use Docker?
Docker vs Virtual Machines
Installing Docker
Key Docker Concepts
Docker Images
Docker Containers
Writing Dockerfiles
Docker Volumes

Lifecycle Management

PreviousPrev
Next

Control every stage of a container's life including start, stop, restart, pause, kill, and understand the difference between each.

Docker Container Lifecycle

Creating a container with docker run is just the beginning. Once it's running, you need to know how to stop it safely, bring it back up, pause it temporarily, and understand what happened when it exits unexpectedly.

The most important thing to get right here is the difference between docker stop and docker kill, getting this wrong with a database can corrupt your data.


Container States at a Glance

A container moves through different states during its lifetime. Here's the full picture:

Docker Container Lifecycle

created
docker start
running
docker pause
paused
docker stop / kill
docker unpause
stopped
docker restart → running
docker rm
(deleted)

Both stop and kill lead to stopped — but stop sends SIGTERM first

Understanding this diagram saves a lot of confusion. The key insight is that stop and kill both lead to the same "stopped" state, but they take very different paths to get there.


Stopping a Container: stop vs kill

docker stop

docker stop sends a SIGTERM signal to the main process inside the container. This is like a polite request to shut down, and it gives your application time to finish what it's doing, save its state, flush any data to disk, and close open connections cleanly.

If the application doesn't exit within 10 seconds, Docker then sends SIGKILL to force it closed.

# Graceful stop with default 10-second timeout
docker stop my-container

# Give it more time (important for databases doing a clean shutdown)
docker stop --time 30 my-container

# Stop multiple containers at once
docker stop web-server db-server cache-server

Always use docker stop for databases, message queues, or anything writing to disk. A graceful shutdown means no corrupted files, no partial transactions, no lost messages.

docker kill

docker kill sends SIGKILL directly. The process is terminated instantly which means there is no cleanup, no flushing, no graceful anything. It's the equivalent of yanking the power cord.

# Immediate termination
docker kill my-container

Use docker kill only when a container is completely unresponsive to docker stop, or when you're running a stateless service where data loss doesn't matter.

Quick Decision Guide

Is the container responding?
   │
   ├─ Yes → docker stop
   │        (sends SIGTERM, waits, then SIGKILL if needed)
   │
   └─ No  → docker kill
            (sends SIGKILL immediately)

Does data integrity matter?
   │
   ├─ Yes (database, queue, file writes) → docker stop --time 30
   │
   └─ No  (stateless web server, simple script) → docker stop (10s default is fine)

Starting a Stopped Container

Once a container is stopped, you don't need to recreate it from scratch. docker start brings it back using the exact same configuration, volumes, and network settings it had before:

# Start a stopped container
docker start my-container

# Start it and attach to its output at the same time
docker start -a my-container

# Start several containers at once
docker start web db cache

One important distinction that confuses: docker start and docker run are not the same thing. docker run creates a brand new container from an image. docker start resumes an existing container that was previously stopped. Think of it like the difference between installing an app and reopening one you already had.


Restarting a Container

docker restart is simply docker stop followed by docker start in one command. It's useful when you've changed a config file or environment variable and need the container to pick up the change:

# Restart with the default stop timeout
docker restart my-container

# Give it more time to stop cleanly before restarting
docker restart --time 15 my-container

# Restart multiple containers
docker restart web db

Pausing a Container (Without Stopping It)

docker pause is a lesser-known but useful command. It freezes all processes inside the container. All processes stop executing completely, using no CPU, but everything stays in memory exactly as it was. No shutdown, no cleanup.

# Freeze the container
docker pause my-container

# Resume it exactly where it left off
docker unpause my-container

This is useful in a few specific scenarios: taking a consistent snapshot of a running container, temporarily freeing up CPU during a maintenance window, or freezing a container mid-execution to inspect its state. Unlike stop, when you unpause there's no re-initialization, the container resumes as if no time passed.


Renaming a Container

You can rename any container irrespective of it's state, and at any time:

docker rename old-name new-name

Useful when you realize your container's name doesn't match what it actually does, or when you're reorganizing a project.


Hands-On Practice: Stop, Check, and Restart

# Step 1: Gracefully stop the container
docker stop my-web

# Step 2: Check its status (it should show "Exited")
docker ps -a

# Step 3: Bring it back up
docker restart my-web

# Step 4: Confirm it's running again
docker ps

Understanding Exit Codes

When a container stops, it leaves behind an exit code that tells you why it stopped. These are the ones you'll see most often:

Exit CodeWhat it means
0Exited cleanly (the process finished normally)
1Application error (something went wrong in your code)
137Killed by SIGKILL (either docker kill or the system ran out of memory (OOM))
143Terminated by SIGTERM (a clean docker stop)

Check the exit code of any stopped container with:

docker inspect my-container --format='{{.State.ExitCode}}'

If a container keeps restarting and you're not sure why, the exit code is the first thing to check.


Waiting for a Container to Finish

In scripts, you sometimes need to wait for a container to complete before moving on. docker wait does exactly that. It blocks until the container exits and then prints the exit code:

docker wait my-task-container
# Prints: 0

This is handy for running containers that do batch jobs, and then checking whether they succeeded before the next step in your script.


Keeping Containers Running Automatically

Instead of manually restarting containers after a crash or host reboot, set a restart policy when you first create the container:

# Restart automatically, but respect manual stops
docker run -d --restart unless-stopped nginx

# Restart only after a crash, up to 5 times
docker run -d --restart on-failure:5 my-worker

unless-stopped is the right choice for most long-running services, it survives host reboots but respects when you intentionally stop a container.


Key Takeaways

  • docker stop sends SIGTERM first to allow a graceful shutdown, then SIGKILL after a timeout. Always use this for databases and anything writing to disk.
  • docker kill sends SIGKILL immediately, no cleanup, no warning. Reserve it for unresponsive containers.
  • docker start resumes an existing stopped container. docker run creates a new one. They are not interchangeable.
  • docker restart is just stop + start in one command.
  • docker pause / docker unpause freeze and resume a container without shutting it down, everything in memory is preserved.
  • Exit code 137 means the container was force-killed (either by you or an out-of-memory event). Exit code 0 means a clean exit.

Frequently Asked Questions

If I docker stop a container and then docker start it, does it lose its data?

It depends on where the data is stored. Data inside the container's writable layer (files created inside the container) persists across stop/start cycles, the container is just paused, not deleted. But that data is lost if you delete the container with docker rm. For important data, always use volumes.

Why does docker stop wait 10 seconds before force-killing?

That's the default grace period. The window of your application gets to shut down cleanly. If 10 seconds isn't enough (for example, a database doing a large flush), use docker stop --time 30 or more. You can also change the default in your Compose file.

What's the difference between exit code 137 and 143?

Code 137 means SIGKILL was sent (force kill: either docker kill, an OOM event, or the OS terminating the process). Code 143 means SIGTERM was sent (docker stop), and the application exited in response to the polite request. If you see 137 on a container that should have been gracefully stopped, something went wrong during shutdown.

Can I stop a container from inside it?

Yes, running exit in an interactive shell, or any command that causes the main process to exit, will stop the container. The exit code will reflect whether it exited cleanly or with an error.

What happens to a paused container if the host restarts?

The container's in-memory state is lost as a host restart doesn't preserve RAM. The container will be in a stopped state when Docker starts back up, not a paused state.

PreviousPrev
Next

Continue Learning

Managing Images

Learn to tag, remove, save, load, and push Docker images, keeping your local environment clean and your registry organized.

7 min·Easy

Docker Containers

Learn the complete lifecycle of Docker containers - create, run, inspect, manage, and clean them up. The hands-on foundation for everything else in Docker.

30 min·Easy

Running Containers

Master docker run - the most important Docker command. Learn every essential flag for port mapping, naming, detached mode, and more.

10 min·Easy

Explore Related Topics

Ku

Kubernetes Tutorials

Orchestrate your Docker containers at scale

CI

CI/CD Tutorials

Automate Docker builds and deployments in pipelines

Try the Tool

Dockerfile Linter

Instantly lint your Dockerfile for best-practice violations and security issues.

On This Page

Container States at a GlanceStopping a Container: `stop` vs `kill`docker stopdocker killQuick Decision GuideStarting a Stopped ContainerRestarting a ContainerPausing a Container (Without Stopping It)Renaming a ContainerHands-On Practice: Stop, Check, and RestartUnderstanding Exit CodesWaiting for a Container to FinishKeeping Containers Running AutomaticallyKey TakeawaysFrequently Asked Questions