Skip to main content

Running and Managing Docker Containers

Learn the Docker container lifecycle: docker run flags, states, stop vs kill, restart policies, and safe cleanup that never destroys data.

44 Terms

Overview and What You Will Learn

A Docker container moves through a small set of states, from created to running to exited to removed, and each state change is triggered by a specific command or by the container's main process ending. Knowing those states, and the difference between docker stop and docker kill, is what lets you manage containers calmly in production.

In this lab you will:

  • Use the docker run flags that matter: detach, name, ports, environment, volumes, limits, and restart policy.
  • List, inspect, and monitor running containers.
  • Stop containers gracefully, and understand how signals reach your application.
  • Choose the right restart policy for services and for jobs.
  • Remove containers and volumes without losing data you need.

Why This Matters in Production

When a service container misbehaves at 2am, the operator's first minutes decide how long the incident lasts. Someone who knows that docker stop lets an application flush and close connections, while docker kill does not, avoids turning a restart into data loss. Someone who knows that removing a container deletes its writable layer, but not a named volume, avoids deleting evidence or data by accident.

These habits matter for any team running containers on a single host, such as the payment, trading, and order services at companies like Razorpay, Zerodha, and Swiggy before they reach an orchestrator. The same commands also explain what Kubernetes does for you later: sends SIGTERM, waits a grace period, then sends SIGKILL.

Core Principles

A container is always in exactly one state, and most transitions are single commands.

stateDiagram-v2 [*] --> Created: docker create Created --> Running: docker start Running --> Paused: docker pause Paused --> Running: docker unpause Running --> Restarting: restart policy Restarting --> Running: start succeeds Running --> Exited: stop, kill, or exit Exited --> Running: docker start Exited --> [*]: docker rm

Keep these facts in mind:

  1. docker run is create plus start. It also pulls the image first if it is missing.
  2. Exited is not removed. A stopped container keeps its writable layer and its logs until you run docker rm.
  3. docker stop sends SIGTERM, waits, then SIGKILL. The default wait is 10 seconds. docker kill sends SIGKILL immediately unless you pass --signal.
  4. Your process is PID 1. Only the process that receives the signal can shut down cleanly, so use exec-form CMD ["node", "server.js"], not a shell wrapper.
  5. Named volumes outlive containers. Anonymous volumes and the writable layer do not, unless you keep the container.

Detailed Step-by-Step Practical Lab

How to Run a Container: The Flags That Matter
Bash
docker run nginx:1.27
# Detached with a name and a published port
docker run -d --name web -p 8080:80 nginx:1.27
curl -I http://localhost:8080
# Interactive shell in a throwaway container
docker run -it --rm ubuntu:24.04 bash
# One-off command, container removed afterwards
docker run --rm alpine:3.20 echo "hello from alpine"

A production-style run combines environment, storage, limits, and a restart policy. Put secrets in an env file instead of -e flags so they stay out of your shell history.

Bash
# Store settings outside the command line
cat > /opt/payment-api/api.env << 'ENVEOF'
NODE_ENV=production
DB_HOST=10.0.1.50
DB_PORT=5432
ENVEOF
chmod 600 /opt/payment-api/api.env
docker run -d \
--name payment-api \
--env-file /opt/payment-api/api.env \
--memory=512m --cpus=1.5 \
--restart=unless-stopped \
-p 127.0.0.1:8080:8080 \
registry.example.com/payment-api:v3.1.0
# Database with a named volume so data survives container removal
docker run -d --name postgres \
-e POSTGRES_PASSWORD_FILE=/run/secrets/db_password \
-v /opt/secrets/db_password:/run/secrets/db_password:ro \
-v postgres-data:/var/lib/postgresql/data \
postgres:16-alpine
How to List and Monitor Containers
Bash
docker ps # running containers
docker ps -a # include stopped ones
docker ps -q # IDs only, handy in scripts
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
docker ps -a --filter "status=exited" --filter "exited=1"
docker stats # live CPU, memory, network, I/O
docker stats --no-stream # one snapshot for scripts
docker top payment-api # processes inside the container
How to Stop a Container: stop vs kill
Bash
# Graceful: SIGTERM, wait 10s, then SIGKILL
docker stop payment-api
# Give a slow shutdown more time
docker stop --time 30 payment-api
# Immediate: SIGKILL, no cleanup. Use only for a frozen container
docker kill payment-api
# Send a different signal, for example to reload nginx config
docker kill --signal SIGHUP web

The effect on a stateful service is large. A trading or order service that handles SIGTERM can finish in-flight requests, flush buffers, and close database connections, then exit with code 0. The same service killed with SIGKILL loses whatever lived only in memory and leaves connections for the database to time out.

You can change the signal and grace period an image uses:

Dockerfile
STOPSIGNAL SIGINT
Bash
docker run -d --stop-timeout 30 --name worker order-worker:v2.0.0
How to Make Signals Reach Your Application
Dockerfile
# Shell form: /bin/sh is PID 1 and may not forward SIGTERM to node
CMD node server.js
# Exec form: node is PID 1 and receives SIGTERM directly
CMD ["node", "server.js"]
Bash
# For programs that do not reap child processes or handle signals, add a tiny init
docker run -d --init --name api payment-api:v3.1.0
How to Start, Restart, Pause, and Remove
Bash
docker start payment-api
docker restart payment-api # stop then start
docker restart --time 5 payment-api
docker pause payment-api # freeze processes, keep memory
docker unpause payment-api
docker rm payment-api # must be stopped
docker rm -f payment-api # kill then remove
docker rm -v payment-api # also remove its anonymous volumes
How to Choose a Restart Policy
Bash
docker run -d --restart=no job:latest
docker run -d --restart=on-failure:5 worker:latest
docker run -d --restart=unless-stopped payment-api:v3.1.0
docker update --restart=unless-stopped payment-api # change a running container
Policy Restarts when After manual stop
no Never Stays stopped
on-failure[:n] Non-zero exit, up to n times Stays stopped
always Any exit Starts again when the daemon restarts
unless-stopped Any exit Stays stopped, even after a reboot

Check for crash loops with docker inspect payment-api --format '{{.RestartCount}}'. A count that keeps rising means the application is broken, and no policy will fix that.

How to Clean Up Without Losing Data
Bash
# See what a container mounts before you delete it
docker inspect payment-api --format '{{range .Mounts}}{{.Type}} {{.Name}} {{.Source}} -> {{.Destination}}{{println}}{{end}}'
# Save logs before removal if you may need them
docker logs --timestamps payment-api > /tmp/payment-api-$(date +%F).log 2>&1
# Remove stopped containers
docker container prune
# Remove only containers older than a day
docker container prune --filter "until=24h"

docker rm deletes the container's writable layer. Named volumes stay until you run docker volume rm, but anything written outside a volume is gone.

Production Best Practices & Common Pitfalls

  • Default to docker stop: reserve docker kill for containers that ignore SIGTERM.
  • Name long-running containers: docker logs payment-api is clearer and safer than a hash.
  • Use --rm for one-off tasks: otherwise stopped containers pile up on build hosts.
  • Use unless-stopped for services, on-failure for jobs: always brings a container back after a reboot even when you stopped it for maintenance.
  • Set memory and CPU limits: an unbounded container can starve the host.
  • Keep data in volumes: the container filesystem is disposable by design.
  • Pass secrets through env files or secret mounts: values given with -e appear in shell history and in docker inspect.
Tip

docker run --rm -it --entrypoint sh <image> gives you a shell in the image without running the application, which is the fastest way to explore what an image contains.

Remember

docker rm removes the container's writable layer permanently. Check docker inspect for mounts and save logs first.

Common Mistake

Using --restart=always on a container that crashes at startup. It will restart in a loop, flooding logs and burning CPU. Check RestartCount and fix the cause.

Security

docker inspect shows environment variables in plain text, and docker exec runs as the container user, which is root by default. Treat both as privileged actions on production hosts, and prefer a non-root USER in your images.

Quick Reference & Troubleshooting Commands

Command Description
docker run -d --name <n> <image> Start a named container in the background
docker ps -a List all containers with state
docker stop <n> Graceful stop with SIGTERM then SIGKILL
docker kill <n> Immediate SIGKILL
docker restart <n> Stop and start again
docker rm -f <n> Force-remove a container
docker update --restart=unless-stopped <n> Change restart policy live
docker container prune Remove all stopped containers
Problem Likely cause Fix
Exits immediately with code 0 Process is a job, not a server Check the CMD, run with -it to test
Bind for 0.0.0.0:8080 failed Host port already in use Use another host port or free it with ss -tulpn
Stop takes 10 seconds every time App ignores SIGTERM Use exec-form CMD or handle the signal
Restarting (1) in docker ps Crash loop Read docker logs --tail 100 and fix the error
Data missing after recreate Wrote outside a volume Mount a named volume at the data path

Resources

Explore More in Docker Fundamentals and Container Lifecycle

All 4 Topics

Frequently Asked Questions

Is Running and Managing Docker Containers free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Running and Managing Docker Containers topic cover?

Learn the Docker container lifecycle: docker run flags, states, stop vs kill, restart policies, and safe cleanup that never destroys data.

Found a mistake, an outdated step or a broken link?