After docker run, you manage a container with docker ps (list), docker stop / docker start / docker restart, docker rename, and docker rm (remove), plus kill, pause, and the auto-remove --rm flag. This page covers each of those, restart policies and health checks (including Compose's depends_on: condition: service_healthy), reading a container's output with docker logs, and diagnosing a container that exits immediately from its exit code.
The lifecycle states
A container moves between these states:
created → running → paused → running → exited → removed
↘ exited ↗
- created:
docker createran but the container hasn't been started. Rare; usually you go straight to running withdocker run. - running: the main process is alive.
docker psshows it. - paused: frozen via cgroups.
docker pauseanddocker unpause. - exited: the main process has stopped (either gracefully via
docker stopor because it crashed/finished). The container still exists; you can read logs, inspect, restart. - removed: the container's filesystem and metadata are gone.
docker rmdid this.
List running containers, docker ps
# Running containers
docker ps
# All containers, including stopped ones
docker ps -a
# Just the IDs (useful in scripts)
docker ps -q
# All IDs (running + stopped)
docker ps -aq
# Filter by status, name, image, label
docker ps --filter status=exited
docker ps --filter name=web
docker ps --filter ancestor=nginx:alpine
docker ps --filter label=env=production
# Custom format with Go templates
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
# Show file sizes (writable layer + image)
docker ps -sdocker ps is the inventory command. By default it only shows running containers; add -a to see everything including exited ones, that's how you find the container that died ten minutes ago so you can docker logs it.
The default columns are container ID, image, command, age, status, ports, and name. --format lets you pull just the columns you want; useful in scripts.
Stop a container, docker stop
docker stop CONTAINER_NAME
# Custom grace period (default is 10s)
docker stop -t 30 CONTAINER_NAME
# Stop all running containers
docker stop $(docker ps -q)docker stop sends SIGTERM to the container's main process, waits 10 seconds for it to exit gracefully, then sends SIGKILL if it hasn't. The 10-second wait is the most common reason a docker stop "feels slow", your app isn't reacting to SIGTERM, so Docker waits the full timeout before killing.
Two ways to fix that:
- Use exec form for CMD/ENTRYPOINT in your Dockerfile. Shell form (
CMD npm start) wraps your process in/bin/sh -c, which receivesSIGTERMbut doesn't pass it to your app. Exec form (CMD ["npm", "start"]orCMD ["node", "server.js"]) sends signals directly. See How to Write a Dockerfile. - Handle
SIGTERMin your app. Express, Fastify, FastAPI etc. all have graceful-shutdown patterns. Without one, your app gets killed mid-request.
docker kill CONTAINER_NAME skips the SIGTERM and sends SIGKILL immediately. Useful when an app is wedged and stop is taking too long.
Start and restart a stopped container, docker start, docker restart
# Start a stopped container (keeps the same name, same volumes, same env)
docker start CONTAINER_NAME
# Start AND attach my terminal to it
docker start -a CONTAINER_NAME
# Restart (stop + start)
docker restart CONTAINER_NAME
# Restart with custom grace period
docker restart -t 30 CONTAINER_NAMEA stopped container is not gone. docker start brings it back exactly as it was, same name, same network attachments, same volumes mounted, same env. This is the difference between docker start and docker run: run always creates a new container; start resurrects an existing one.
When to use which:
docker restartwhen a service is misbehaving and you want to reset it without losing its config. Database isn't responding to queries; bounce it.docker startwhen you previously stopped a container and want it back. Common after host reboots if you don't have a--restartpolicy set.docker runwhen you want a fresh container, possibly with different flags.
Restart policies, surviving crashes and reboots
If you want a container to come back automatically after a crash or a host reboot, set a restart policy:
docker run -d --name CONTAINER_NAME --restart unless-stopped IMAGE_NAME| Policy | Behavior |
|---|---|
no (default) | Never restart. |
on-failure[:max] | Restart only on non-zero exit. Optional max-attempts. |
always | Restart, including after host reboot. Restarts even if you manually stopped it. |
unless-stopped | Restart, including after host reboot. Does NOT restart if you stopped it manually. |
The same thing in Compose:
services:
web:
image: nginx:alpine
restart: unless-stoppedunless-stopped is the right default for almost every long-running service. It restarts on crashes and host reboots, but stays stopped when you docker stop it on purpose. always differs in exactly one place: after a docker stop, the next time the daemon starts (after a host reboot, say), always starts the container again even though you stopped it. That surprise is why I reach for unless-stopped.
on-failure and exit codes
on-failure only restarts on a non-zero exit, so the exit code decides what happens:
- Exit 0: normal, intentional exit.
on-failuredoes not restart. - Exit 1 to 126: application error.
on-failurerestarts. - Exit 137: OOMKilled.
on-failurerestarts, and the same OOM will probably happen again, so fix the memory limit. - Exit 143: SIGTERM (
128 + 15). It is non-zero, soon-failurerestarts it when something else sent the signal. When the 143 comes from your owndocker stop, nothing restarts, but that is because a manual stop suspends the restart policy (until the daemon restarts or you start the container again), not because of the exit code.
on-failure:5 retries up to 5 times before giving up, which suits an app that crashes on bad input: try a few times, don't loop forever. For services I want to stay running, unless-stopped; for workers that should die hard when something goes wrong, on-failure:N.
Docker health checks and depends_on
A restart policy reacts to the process exiting. A health check answers a different question: is the process inside actually doing its job? A web server whose process is running but returns 500 to every request is alive, but unhealthy.
In a Dockerfile:
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD curl -f http://localhost:3000/healthz || exit 1--interval=30s: check every 30 seconds.--timeout=5s: kill the check if it takes longer than 5 seconds.--start-period=10s: grace period after start during which failures don't count.--retries=3: flip to "unhealthy" only after this many consecutive failures.CMD ...: the command. Exit 0 = healthy, non-zero = unhealthy.
In Compose:
services:
web:
image: my-app
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/healthz"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10stest takes two forms: ["CMD", ...] runs directly without a shell, and ["CMD-SHELL", "..."] runs through a shell so pipes and redirects work. The Dockerfile HEALTHCHECK travels with the image; a Compose healthcheck: is per-service config and overrides the image's one. docker ps then shows the status in the STATUS column:
CONTAINER ID IMAGE ... STATUS NAMES
abc123def my-app ... Up 5 minutes (healthy) web
Healthcheck commands by service
# Web app with a /healthz route that returns 200 when healthy
test: ["CMD", "curl", "-f", "http://localhost:3000/healthz"]
# Postgres (pg_isready ships in the image, purpose-built for this)
test: ["CMD-SHELL", "pg_isready -U postgres"]
# MySQL
# $$ makes the shell inside the container expand the variable; a single $ is
# interpolated by Compose from your shell or .env, often to an empty string
test: ["CMD-SHELL", "mysqladmin ping -h localhost -uroot -p$$MYSQL_ROOT_PASSWORD"]
# Redis
test: ["CMD", "redis-cli", "ping"]
# MongoDB
test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ ping: 1 })"]
# Elasticsearch
test: ["CMD-SHELL", "curl -fs http://localhost:9200/_cluster/health || exit 1"]Alpine images don't ship curl by default, so a curl healthcheck on them fails forever. Use wget --spider, install curl, or write the check in the app's own runtime.
Wait for the database with depends_on: condition: service_healthy
Plain depends_on only controls start order. Postgres can take 5 to 30 seconds to initialize on first start; web boots faster than that, tries to connect, and crashes with connection refused. With the healthy condition, Compose waits for the dependency's healthcheck to pass:
services:
web:
depends_on:
db:
condition: service_healthy
db:
image: postgres:17
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 5The three conditions are service_started (the default), service_healthy, and service_completed_successfully (the dependency exits 0, for one-shot init containers). Without a healthcheck on the dependency, Compose can only wait for "started", never "healthy".
Inspect health-check status
docker inspect --format '{{json .State.Health}}' CONTAINER_NAME | jq
docker events --filter event=health_statusThe first shows the status plus the last 5 results with exit codes and output, which is where the reason for "unhealthy" lives. The second streams health transitions live.
Two pitfalls: an interval of 1s makes the check itself a load on the container (30s is fine, 60s or more for slow starters), and no start_period on an app that takes 20 seconds to boot means the first 20 seconds of failures count as retries and it is marked unhealthy from the start. Also note that a health check on its own never restarts anything: restart policies trigger on exit, not on health status.
Pause and unpause, docker pause
docker pause CONTAINER_NAME
docker unpause CONTAINER_NAMEpause uses the cgroups freezer to suspend every process inside the container. It is not the same as stop, the processes are still there, they just aren't scheduled. Memory is preserved. Useful for snapshotting / quiescing state without a full restart.
Not commonly needed in day-to-day work. The two cases I've actually used it: pausing a CPU-hungry container to let another finish first, and pausing a database briefly while taking a filesystem snapshot of its volume.
Rename a container, docker rename
docker rename OLD_NAME NEW_NAMEJust changes the name. The container ID, volumes, network attachments, everything else stays the same. Useful when you started with --name old_temp and want to give it a real name without recreating.
Remove a container, docker rm
# Remove a stopped container
docker rm CONTAINER_NAME
# Force-remove (stops it first if running)
docker rm -f CONTAINER_NAME
# Remove a container AND its anonymous volumes
docker rm -v CONTAINER_NAME
# Remove all stopped containers in one go
docker container prune
# Remove ALL containers (running and stopped): destructive
docker rm -f $(docker ps -aq)docker rm deletes the container's filesystem (the writable layer) and metadata. The image is unaffected; you can docker run again from the same image and get a fresh container.
By default, named volumes survive docker rm, that's the whole point of using a named volume. Anonymous volumes (volumes you didn't name, declared by VOLUME in a Dockerfile or just -v /path) survive by default too, but -v (or --volumes) on docker rm removes them. To clean them up later, docker volume prune.
The --rm flag, auto-remove on exit
# Container is deleted the instant its main process exits
docker run --rm IMAGE_NAME
# --rm + -it = the throwaway interactive shell pattern
docker run --rm -it IMAGE_NAME bash--rm is for one-shot containers, try a tool, run a quick command, get an interactive shell to poke around. Without --rm, every quick test leaves a stopped container behind, and a week later docker ps -a is a graveyard.
Do NOT use --rm on services you might want to inspect later. Once the container exits, docker logs is no longer available for it.
View container logs with docker logs
docker logs shows what the container's main process wrote to stdout and stderr. It works on running containers and on stopped ones until they're removed, so it's the first thing to check when something misbehaves.
# All logs since the container started
docker logs CONTAINER_NAME
# Follow live (tail -f)
docker logs -f CONTAINER_NAME
# Last 100 lines, then follow
docker logs --tail 100 -f CONTAINER_NAME
# Since the last 10 minutes
docker logs --since 10m CONTAINER_NAME
# Prepend ISO timestamps
docker logs --timestamps CONTAINER_NAMECONTAINER_NAME can be the name (my-app), full ID, or short ID prefix.
| Flag | Effect |
|---|---|
-f, --follow | Stream new log output as it arrives. Like tail -f. |
--tail N, -n N | Only show the last N lines before exiting (or before -f starts following). Default is all. |
--since DURATION_OR_DATE | Show logs newer than this. Accepts durations (10m, 2h, 7d) or absolute timestamps (2026-05-01 or 2026-05-01T08:00:00). |
--until DURATION_OR_DATE | Show logs older than this. Same format as --since. |
-t, --timestamps | Prepend an ISO 8601 timestamp to each line. |
The flags compose freely: --since 1h --tail 100 -f shows up to the last 100 lines from the past hour, then follows.
docker logs patterns I use
# Latest output of a long-running service (plain -f dumps the whole history first)
docker logs --tail 50 -f CONTAINER_NAME
# A crash a few minutes ago; timestamps tell you if events were 10ms or 10s apart
docker logs --since 10m --timestamps CONTAINER_NAME
# A specific window
docker logs --since 2026-05-21T08:00:00 --until 2026-05-21T09:00:00 CONTAINER_NAME
# Snapshot to a file (captures stdout and stderr)
docker logs CONTAINER_NAME > /tmp/container-logs.txt 2>&1
# Grep, with 2>&1 because errors usually come through stderr
docker logs CONTAINER_NAME 2>&1 | grep -i errorFor Compose stacks, docker compose logs takes the same flags and interleaves every service's output with a service-name prefix, which is exactly what you want for "did web log this before or after db logged that?":
docker compose logs -f web # one service
docker compose logs -t --tail 100 -f # all services, with timestampsWhy docker logs shows nothing
The app writes to a file inside the container, not to stdout/stderr. docker logs only captures the main process's standard streams. If your app logs to /var/log/app.log, docker logs knows nothing about it. This is the single most common "docker logs is empty" cause, and the reason the 12-factor "log to stdout" pattern exists. Fixes:
- Change the app config to log to stdout (most frameworks have a stdout logger).
- Symlink the log file to stdout in the Dockerfile:
RUN ln -sf /dev/stdout /var/log/app.log. - Mount a host directory and tail the file from outside, or
docker exec CONTAINER tail -f /path/to/file.
The container has just started and hasn't logged yet. Try again in a moment, or add -f to wait.
Other logging drivers (fluentd, gelf, awslogs, splunk, syslog and others, set with --log-driver or in /etc/docker/daemon.json) send logs to an external system. docker logs still works with them, because Docker keeps a local "dual logging" cache by default (up to five 20 MB files per container) for any driver that can't be read back. It stops working only if that cache is turned off (cache-disabled), in which case you get configured logging driver does not support reading. json-file, local and journald are read directly and don't need the cache.
Stop logs filling the disk
The default json-file driver writes each container's output to /var/lib/docker/containers/<id>/ and the file grows without bound. On a chatty container running for weeks, gigabytes of logs is a real outcome. Cap it per container:
docker run -d --name CONTAINER_NAME \
--log-opt max-size=10m --log-opt max-file=3 \
IMAGE_NAMEThat caps each log file at 10 MB and keeps at most 3 rotated files. 30 MB total per container is plenty for most apps. In docker-compose.yml:
services:
app:
image: my-app
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"Or daemon-wide in /etc/docker/daemon.json, then sudo systemctl restart docker. New containers inherit these defaults; existing containers keep their original config until recreated.
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}To reclaim disk from a container already using gigabytes without recreating it: stop the container, find /var/lib/docker/containers/<id>/<id>-json.log, and truncate it (sudo truncate -s 0 path). Don't rm it: the Docker daemon's file handle is still open and behaviour gets weird.
Docker container exits immediately
A container that exits right after docker run -d almost always has one of three causes: no foreground process to keep it alive, a main process that crashed on startup, or an OOM kill. It shows up in docker ps -a as "Exited" and nothing else happened. Each cause leaves a different signature, so start with the logs and the exit code:
docker logs CONTAINER_NAME
docker inspect --format '{{.State.ExitCode}}' CONTAINER_NAME
docker inspect --format '{{.State.OOMKilled}}' CONTAINER_NAME| Exit code | What it means |
|---|---|
0 | The process completed normally, it ran, did its thing, and exited. Usually means the container had no foreground service. |
1–125 | Application error. The process started but errored out. docker logs shows the message. |
126 | Command found but not executable. Usually a missing executable bit on a script. |
127 | Command not found. Often a typo or a missing binary on alpine. |
137 | SIGKILL (128 + 9). On --memory limits, this is OOMKilled. docker inspect's OOMKilled field confirms. |
143 | SIGTERM (128 + 15). From docker stop or similar. Usually expected. |
Exit code 0: no foreground process
The most common cause. The main process ran, did nothing useful, and exited cleanly:
- You ran a non-interactive command.
docker run -d ubuntu:24.04exits at once: the default CMD isbash, and without-itbash has no terminal and no input. Use-itfor an interactive shell, or pass a long-running command (docker run -d ubuntu:24.04 sleep 3600as a placeholder). - The image expects a command and you didn't give one. Some images ship a
CMD ["bash"]or similar that only makes sense interactively. - A server that doesn't actually start as a server.
CMD ["./my-server"]exits because it can't find its config, the port is taken, or it's really a CLI tool.
Empty logs plus exit code 0 means one of the first two. Errors in the logs mean the third.
A subtler version: shell-form CMD npm start runs /bin/sh -c "npm start", and with signal-handling weirdness or npm's "exit when the script exits" semantics, the container can exit even though node was alive. Use exec form for real servers (CMD ["node", "server.js"]), which runs the process directly as PID 1.
Exit codes 1 to 125: the app crashed
The error is in docker logs. Common ones:
Error: ENOENT: no such file or directory: your CMD references a path that doesn't exist in the image. Check that the build COPY put the file where the CMD expects.MODULE_NOT_FOUND(Node):node_modulesis missing or your bind mount overlaid it with empty / wrong-arch content.- Database connection refused: the service starts before the database is ready. Add a healthcheck with
depends_on: condition: service_healthy. See health checks and depends_on. bind: address already in use: port conflict. See Port is Already Allocated.- PHP fatal errors, Python tracebacks: a code bug, same as outside Docker.
Exit code 137: OOMKilled
If {{.State.OOMKilled}} is true, the kernel's OOM killer stopped the process: either the container exceeded its --memory limit (raise it or fix the leak), or the host ran out of memory. docker stats CONTAINER_NAME shows live memory use, and for an exited container docker inspect --format '{{.HostConfig.Memory}}' CONTAINER_NAME shows the limit that was set. It's common in Compose stacks where someone set mem_limit: 256m and the app needs 1 GB.
Exit code 143 is a clean SIGTERM, usually from docker stop. If you didn't stop it, something else sent the signal: Compose's down, a parent script, or an external process supervisor.
Debug a container that won't stay up
Run it in the foreground so the output streams to your terminal, and --rm cleans up when you Ctrl-C:
docker run --rm -it my-imageIf the logs are empty and nothing shows, override the entrypoint with a shell and run the original command by hand:
docker run --rm -it --entrypoint sh my-image
# then inside: ./my-serverTo keep a container alive so you can docker exec into it, replace the CMD with something that blocks forever:
docker run -d --name dbg --entrypoint tail my-image -f /dev/null
docker exec -it dbg sh
# Now you're inside a running container. Run the original command and watch.(sleep infinity works on coreutils-based images; not on alpine's BusyBox.) Two more causes worth ruling out: a bind mount that hides files the image needs (mounting ./local-dist:/app/dist over an image that had files in /app/dist makes them vanish from the container's view), and a USER that can't read the working files, which produces permission errors that look like crashes. On Apple Silicon, an amd64-only image can fail with exec format error and exit.
Common patterns
Find and stop a container by name pattern:
docker stop $(docker ps -q --filter name=web)Stop everything cleanly:
docker stop $(docker ps -q)Clean up all stopped containers:
docker container prune
# or, with no prompt:
docker container prune -fRestart a container that's stuck:
docker kill CONTAINER_NAME && docker start CONTAINER_NAMEWatch a container's lifecycle events live:
docker events --filter type=container --filter container=CONTAINER_NAMEUseful when debugging a container that keeps restarting, the events show every start, die, restart with timestamps and exit codes.
Common pitfalls
docker stoptaking 10 full seconds every time. Your app isn't handling SIGTERM. Either use exec form in your Dockerfile's CMD, or add a SIGTERM handler in the app. See How to Write a Dockerfile.- "Conflict. The container name '/web' is already in use." A container with that name still exists, even if stopped. Either
docker rm webfirst, ordocker run --rmto auto-clean, or use a different name. docker psdoesn't show my container: butdocker ps -adoes. It's not running. Either it crashed or it exited normally (single-shot command); see Docker container exits immediately. Restart withdocker start.-don a container that needs-it. Run interactively first to see what the image actually expects.- Containers piling up over time. Add
--rmto one-shot runs, and periodicallydocker container prune. Or use a restart policy and let Docker manage state. docker rmdoesn't delete the volume. Correct: named and anonymous volumes survive container removal by default. Usedocker rm -vto remove anonymous volumes, anddocker volume pruneto clean up unused ones.
FAQ
docker stop sends SIGTERM, waits 10 seconds for graceful shutdown, then sends SIGKILL if needed. docker kill sends SIGKILL immediately (or whatever signal you pass with --signal). Use stop for normal shutdowns and kill when the container is wedged and you don't want to wait.
docker run creates a brand-new container from an image and starts it. docker start starts a container that already exists (was created earlier and is now in the exited state). Re-running the same docker run command gives you a new container; docker start :container restarts the same one.
No. docker rm only removes the container. The image stays. To remove the image, use docker rmi IMAGE_NAME or docker image prune -a.
Only if your data is in the container's writable layer (no volume). If you used a named volume, which you should for any database, docker rm leaves the volume alone, and you can attach it to a new container later. docker rm -v removes anonymous volumes but still doesn't touch named volumes. The named-volume-explicit cleanup command is docker volume rm VOLUME_NAME.
Set a restart policy: docker run -d --restart unless-stopped IMAGE. unless-stopped is the right default for services, it survives crashes and host reboots but doesn't fight you when you manually stop a container. Compose: restart: unless-stopped in the service block.
By default, depends_on only waits for the container to be started, not ready. Add a healthcheck to the dependency and use condition: service_healthy on the depends_on entry. If the dependency never goes healthy within its start_period, retries and timeout budget, Compose fails the dependent service's startup.
No. HEALTHCHECK only changes the reported status. Restart policies trigger on exit code, not health status. To restart an unhealthy container you need an external supervisor (Docker Swarm, Kubernetes, or a small monitoring tool) that watches health status and acts on it.
Yes, until the container is removed. docker ps -a lists stopped containers; docker logs CONTAINER shows their final output, even if the container exited with code 1. That's why --rm is a bad idea on services you might need to investigate.
The image's default CMD is bash. With -d (detached, no TTY), bash has nothing to read from and exits immediately. To keep an interactive container: docker run --rm -it ubuntu bash. To run a background container with a real workload: pass a command, like docker run -d ubuntu sleep infinity.
The Linux signal SIGKILL (128 + 9 = 137), almost always sent by the OOM killer because the container exceeded its memory limit or the host ran out. docker inspect --format '{{.State.OOMKilled}}' confirms. Raise the memory limit or fix the leak.
For actual long-running processes (servers, daemons), yes, exec form (CMD ["node", "server.js"]) makes signals reach the process, so docker stop is fast and you avoid "container exits even though the process is running" issues. Shell form (CMD node server.js) wraps the process in /bin/sh -c, which usually works but can interfere with signal handling.
Sources
Authoritative references this article was fact-checked against.
- docker container, CLI referencedocs.docker.com
- docker inspect, official referencedocs.docker.com
- docker logs, official CLI referencedocs.docker.com
- Configure logging driversdocs.docker.com
- Dual logging (docker logs with remote drivers), Docker docsdocs.docker.com
- docker run --restart, officialdocs.docker.com
- HEALTHCHECK in Dockerfile referencedocs.docker.com
- Start containers automatically, Docker docsdocs.docker.com
- Variable interpolation, Docker Compose docsdocs.docker.com
- Interpolation, Compose file referencedocs.docker.com





