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 runflags 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.
Keep these facts in mind:
docker runis create plus start. It also pulls the image first if it is missing.- Exited is not removed. A stopped container keeps its writable layer and its logs until you run
docker rm. docker stopsends SIGTERM, waits, then SIGKILL. The default wait is 10 seconds.docker killsends SIGKILL immediately unless you pass--signal.- 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. - 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
docker run nginx:1.27 # Detached with a name and a published portdocker run -d --name web -p 8080:80 nginx:1.27curl -I http://localhost:8080 # Interactive shell in a throwaway containerdocker run -it --rm ubuntu:24.04 bash # One-off command, container removed afterwardsdocker 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.
# Store settings outside the command linecat > /opt/payment-api/api.env << 'ENVEOF'NODE_ENV=productionDB_HOST=10.0.1.50DB_PORT=5432ENVEOFchmod 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 removaldocker 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-alpineHow to List and Monitor Containers
docker ps # running containersdocker ps -a # include stopped onesdocker ps -q # IDs only, handy in scriptsdocker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"docker ps -a --filter "status=exited" --filter "exited=1" docker stats # live CPU, memory, network, I/Odocker stats --no-stream # one snapshot for scriptsdocker top payment-api # processes inside the containerHow to Stop a Container: stop vs kill
# Graceful: SIGTERM, wait 10s, then SIGKILLdocker stop payment-api # Give a slow shutdown more timedocker stop --time 30 payment-api # Immediate: SIGKILL, no cleanup. Use only for a frozen containerdocker kill payment-api # Send a different signal, for example to reload nginx configdocker kill --signal SIGHUP webThe 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:
STOPSIGNAL SIGINTdocker run -d --stop-timeout 30 --name worker order-worker:v2.0.0How to Make Signals Reach Your Application
# Shell form: /bin/sh is PID 1 and may not forward SIGTERM to nodeCMD node server.js # Exec form: node is PID 1 and receives SIGTERM directlyCMD ["node", "server.js"]# For programs that do not reap child processes or handle signals, add a tiny initdocker run -d --init --name api payment-api:v3.1.0How to Start, Restart, Pause, and Remove
docker start payment-apidocker restart payment-api # stop then startdocker restart --time 5 payment-api docker pause payment-api # freeze processes, keep memorydocker unpause payment-api docker rm payment-api # must be stoppeddocker rm -f payment-api # kill then removedocker rm -v payment-api # also remove its anonymous volumesHow to Choose a Restart Policy
docker run -d --restart=no job:latestdocker run -d --restart=on-failure:5 worker:latestdocker run -d --restart=unless-stopped payment-api:v3.1.0docker 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
# See what a container mounts before you delete itdocker inspect payment-api --format '{{range .Mounts}}{{.Type}} {{.Name}} {{.Source}} -> {{.Destination}}{{println}}{{end}}' # Save logs before removal if you may need themdocker logs --timestamps payment-api > /tmp/payment-api-$(date +%F).log 2>&1 # Remove stopped containersdocker container prune # Remove only containers older than a daydocker 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: reservedocker killfor containers that ignore SIGTERM. - Name long-running containers:
docker logs payment-apiis clearer and safer than a hash. - Use
--rmfor one-off tasks: otherwise stopped containers pile up on build hosts. - Use
unless-stoppedfor services,on-failurefor jobs:alwaysbrings 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
-eappear in shell history and indocker 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 rmremoves the container's writable layer permanently. Checkdocker inspectfor mounts and save logs first.
Common MistakeUsing
--restart=alwayson a container that crashes at startup. It will restart in a loop, flooding logs and burning CPU. CheckRestartCountand fix the cause.
Security
docker inspectshows environment variables in plain text, anddocker execruns as the container user, which is root by default. Treat both as privileged actions on production hosts, and prefer a non-rootUSERin 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 |