Appearance
Everyday Docker Commands
38. What is the difference between docker create, docker start, docker run, docker stop, and docker rm?
The short answer
docker create builds a new container from an image but does not start it. docker start starts a container that already exists. docker run does both in one step, and pulls the image first if needed, so it always makes a brand-new container. docker stop asks a running container to shut down, politely first and by force after a timeout. docker rm deletes a stopped container and its writable layer.
The commands make sense once you see a container's life as a set of states. Each command moves the container from one state to another.
run always creates a new container. start reuses an existing one, with its writable layer and settings intact. rm only removes containers that are not running, unless you add -f.Walk through each command:
bash
docker create --name web nginx:1.27 # (1)
docker start web # (2)
docker stop web # (3)
docker start web # (4)
docker rm -f web # (5)
docker run -d --name web2 nginx:1.27 # (6)
docker run --rm alpine echo hello # (7)- create makes a container called
web: its writable layer, its settings and a network slot. The state iscreated. No process is running yet. - start launches the image's command inside that container. The state becomes
running. - stop sends the stop signal, usually
SIGTERM, waits up to 10 seconds for the app to exit, then sendsSIGKILL. The state becomesexited. The container and its files are kept. Question 104 explains the stop sequence in depth. - start again runs the same container. Any file it wrote before is still in its writable layer.
- rm deletes the container.
-fforces it: if the container is running, Docker kills it first. - run is
createplusstartin one command, pulling the image first if it is missing. Run it twice and you get two different containers. --rmtells Docker to delete the container as soon as it exits. It is perfect for one-off commands, so stopped containers do not pile up.
The classic mistake: using docker run when you meant docker start. Every run makes a new container, so you lose the old one's files and leave it lying around as an exited container.
39. What is the difference between stopping, killing, and removing a container?
The short answer
Stopping is polite: Docker sends a signal asking the app to shut down, waits for it, and only forces it after a timeout. Killing is immediate: by default Docker sends SIGKILL, which ends the process at once with no chance to clean up. Removing is different from both: it deletes the container record and its writable layer, and it only works on a container that is not running, unless you force it.
First, one idea: a signal is a short message the kernel delivers to a process. SIGTERM means "please finish up and exit". A program can catch it and close things neatly. SIGKILL means "stop now". A program cannot catch it, ignore it or clean up after it. The kernel simply ends it.
| Stop | Kill | Remove | |
|---|---|---|---|
| Command | docker stop | docker kill | docker rm |
| Signal | SIGTERM, then SIGKILL | SIGKILL by default | None |
| App can clean up | Yes, within the timeout | No | Not applicable |
| Container afterwards | Exited, kept | Exited, kept | Gone |
| Typical exit code | 0 or 143 | 137 | Not applicable |
Stop gives the app a chance to finish in-flight requests, close database connections and flush data to disk. The default wait is 10 seconds. Change it with docker stop -t 30 web.
Kill is for when the app is stuck and will not respond. It is fast but rough: requests in progress are dropped and half-written files may be left behind. docker kill can also send other signals. For example, docker kill -s HUP web asks nginx to reload its configuration without stopping.
Remove is about the container's existence, not its process. After removing, its writable layer, its logs and its settings are deleted. Volumes are not deleted. Named volumes survive on purpose, because they usually hold data you care about.
Reading the exit codes. When a process ends because of a signal, its exit code is 128 plus the signal's number. SIGTERM is signal 15, so 128 + 15 = 143. SIGKILL is signal 9, so 128 + 9 = 137. A well-written app catches SIGTERM, shuts down neatly and exits with 0. So after a docker stop, exit code 0 or 143 is normal, and 137 means the app ignored the polite request and had to be killed. Question 151 covers exit code 137 in detail.
40. Which commands list running containers, all containers, local images, and image layers?
The short answer
docker ps lists running containers, and docker ps -a lists all containers, including stopped ones. docker images, or docker image ls, lists the images stored locally. docker history shows the layers of one image, with the instruction that created each layer and its size.
bash
docker ps # (1)
docker ps -a # (2)
docker ps -a --filter status=exited # (3)
docker images # (4)
docker history checkout-api:1.4 # (5)
docker system df # (6)- Running containers: ID, image, command, how long ago it was created, status, published ports and name.
- Adds stopped containers. The
STATUScolumn shows things likeExited (137) 5 minutes ago, which tells you the exit code at a glance. - Filters the list. Other useful filters are
name=api,ancestor=nginx(made from this image), andhealth=unhealthy. - Local images: repository, tag, image ID, age and size.
- The layers of one image, newest first. Question 88 uses this to find what makes an image large.
- A summary of disk space used by images, containers, volumes and build cache, with how much could be reclaimed.
Two more forms are very handy in scripts:
bash
docker ps -q # (1)
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' # (2)-qprints only the IDs, so you can feed them to another command.--formatpicks exactly the columns you want. The words inside double braces are fields of each container.tablekeeps the header row.
A small detail: docker images hides intermediate build layers and shows dangling images as <none>:<none>. A dangling image is an old image whose tag was moved to a newer build, so nothing names it anymore. They are safe to delete. Question 45 covers clean-up.
41. How do you inspect a container's configuration and current state?
The short answer
docker inspect prints everything Docker knows about a container as JSON: its state and exit code, whether it was killed for using too much memory, its health, its command, environment variables, mounts, limits, restart policy and network settings. Add --format to pull out one field. docker stats shows live CPU and memory use, and docker top shows its processes.
bash
docker inspect checkout-api-1The output is long. These are the parts you will read most often:
| Section | What it tells you |
|---|---|
State | Status, exit code, OOMKilled, start and finish times, health |
Config | Image, command, entrypoint, environment, user |
HostConfig | Memory and CPU limits, restart policy, port bindings, privileged |
Mounts | Volumes and bind mounts, and where they appear |
NetworkSettings | Networks, IP addresses, published ports |
RestartCount | How many times Docker restarted it |
--format takes a template, so you get one answer instead of a page:
bash
docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' checkout-api-1 # (1)
docker inspect -f '{{json .Config.Env}}' checkout-api-1 # (2)
docker inspect -f '{{.HostConfig.Memory}}' checkout-api-1 # (3)
docker inspect -f '{{range .Mounts}}{{.Source}} -> {{.Destination}}{{"\n"}}{{end}}' checkout-api-1 # (4)- Prints, for example,
exited exit=137 oom=true. That one line answers "why did it die?": the kernel killed it for using too much memory. - The environment variables, as JSON. Useful to check that a setting really arrived.
- The memory limit in bytes.
0means no limit. - Every mount, one per line, showing where host files appear inside the container.
Live views:
bash
docker stats --no-stream # (1)
docker top checkout-api-1 # (2)
docker port checkout-api-1 # (3)- One snapshot of CPU, memory, network and disk use for every running container. Leave off
--no-streamto watch it update live. - The processes running inside the container, seen from the host.
- Which host ports lead to which container ports.
A habit worth mentioning: check State.OOMKilled and State.ExitCode before reading any logs. They often tell you the cause in one line.
42. How do you view a container's logs and follow new log output?
The short answer
docker logs <container> prints everything the app wrote to standard output and standard error. Add -f to follow new lines as they arrive, --tail 100 to start from the last hundred lines, --since 10m for a time window, and -t to add timestamps. It only works if the app writes its logs to standard output instead of to files inside the container.
bash
docker logs checkout-api-1 # (1)
docker logs -f --tail 100 checkout-api-1 # (2)
docker logs --since 10m -t checkout-api-1 # (3)
docker logs checkout-api-1 2>&1 | grep ERROR # (4)- Prints the whole log so far.
- Shows the last 100 lines, then keeps printing new lines until you press Ctrl+C. This is the command you use most while debugging.
- Shows only the last 10 minutes, with a timestamp on each line.
docker logssends the container's error stream to your terminal's error stream.2>&1merges the two sogrepsearches both.
Where the logs come from. Every process has two output streams: standard output for normal messages and standard error for errors. Docker captures both streams from the container's main process and hands them to a logging driver. The default driver, json-file, writes them to a file on the host, one JSON line per message. docker logs reads that file back. Question 472 covers logging drivers and how to stop these files from filling the disk.
Three things that surprise people:
- Logs written to files inside the container do not appear. If the app writes to
/var/log/app.log,docker logsshows nothing. The fix is to make the app log to standard output. The official nginx image does this with a trick: its log files are links to/dev/stdoutand/dev/stderr. - Logs of a stopped container are still there. You can read why a container crashed, as long as it has not been removed.
docker rmdeletes the logs too. - Logs survive restarts. If the restart policy restarts a container, the old output stays in the log, followed by the new output.
43. How do you execute a command inside a running container?
The short answer
docker exec -it <container> sh starts a shell inside a running container, so you can look around from the inside. docker exec starts a new, extra process in the same namespaces as the container's main process. It does not restart anything, and it only works while the container is running. If the image has no shell, you attach a separate debugging container to the same namespaces instead.
bash
docker exec -it checkout-api-1 sh # (1)
docker exec checkout-api-1 env # (2)
docker exec -u root checkout-api-1 id # (3)
docker exec -w /app checkout-api-1 ls -la # (4)
docker exec checkout-api-1 cat /etc/resolv.conf # (5)-ikeeps input open and-tgives you a terminal, so you get an interactive shell. Usebashif the image has it.- Runs one command and returns. Here it prints the environment the app actually sees.
-u rootruns the command as root, even if the container's app runs as a normal user.-wsets the folder the command runs in.- Shows which DNS servers the container uses. Question 117 uses this to debug name resolution.
What exec really does. The kernel lets a new process join existing namespaces. docker exec asks the runtime to start a process that joins the container's process, network, mount and other namespaces. So the new process sees exactly what the app sees: the same files, the same network, the same hostname. But it is not process 1. When you exit the shell, only that extra process ends. The app keeps running.
When there is no shell. Small production images, such as distroless images (question 70), contain no shell at all. docker exec ... sh fails with "executable file not found". Two ways around it:
bash
docker run -it --rm --network container:checkout-api-1 --pid container:checkout-api-1 busybox sh # (1)
docker cp checkout-api-1:/app/config.json ./config.json # (2)- Starts a throwaway
busyboxcontainer, a tiny image full of basic tools, that joins the target's network and process namespaces. You can see the app's processes and test its network as if you were inside, without changing the target image. docker cpcopies a file out of a container, even a stopped one. That is often all you need.
A word of caution. Changes you make with exec are temporary and unrecorded. Installing a tool or editing a config file "just to test" in production creates a container that no longer matches its image. Use exec to look. Fix things in the Dockerfile.
44. What do docker ps, docker images, docker inspect, docker logs, and docker exec help you investigate?
The short answer
Each answers a different question. ps tells you whether the container is running, restarting or exited, and with what exit code. images tells you which versions are present. inspect tells you the exact configuration and why it stopped. logs tells you what the app said. exec lets you check things from inside: files, settings and network. Used in that order, they take you from symptom to cause.
Think of them as five instruments, each answering one question:
| Command | The question it answers |
|---|---|
docker ps -a | Is it running, restarting or dead? Exit code? Since when? |
docker images | Which image versions are here, how big, how old? |
docker inspect | What exactly was it started with? Was it out of memory? |
docker logs | What did the app say before it failed? |
docker exec | What does it see from inside: files, variables, network? |
A good order for investigating, using a container that keeps failing:
docker ps -a. You seeRestarting (1) 4 seconds ago. So it starts, fails with exit code 1, and the restart policy brings it back. Exit code 1 means the app itself reported an error.docker logs --tail 50. The last lines sayError: connect ECONNREFUSED 127.0.0.1:5432. The app cannot reach its database.docker inspect. The environment showsDATABASE_HOST=localhost. Inside a container,localhostis the container itself, not the database. That is the cause. Question 119 explains why.docker exec, if needed, to confirm: from inside the container, try resolving and connecting to the real database name.docker imagesanswers a different kind of question: "is this host even running the version we think?" Compare the image ID with what the pipeline built.
Why they ask: they want to see a method. Jumping straight to exec and poking around is slow. Reading the state, then the logs, then the configuration finds most problems in a minute or two.
45. How do you clean up unused containers, networks, images, and build cache safely?
The short answer
First measure with docker system df. Then remove each kind of thing on purpose: docker container prune for stopped containers, docker image prune for dangling images (add -a for every unused image), docker network prune, and docker builder prune for build cache. Use filters such as --filter until=72h to keep recent things. Be very careful with volumes, because volumes hold data, and pruning them deletes it for good.
Docker keeps everything until you delete it: exited containers, old images, build cache, unused networks and volumes. On a busy build machine, this fills a disk in days.
Step 1: measure.
bash
docker system dfTYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 48 6 21.4GB 18.9GB (88%)
Containers 9 3 1.2GB 980MB (81%)
Local Volumes 5 3 6.3GB 1.1GB (17%)
Build Cache 212 0 14.7GB 14.7GBRECLAIMABLE is what is not in use. Here images and build cache are the problem, so clean those.
Step 2: remove each kind on purpose.
bash
docker container prune --filter until=24h # (1)
docker image prune # (2)
docker image prune -a --filter until=168h # (3)
docker network prune # (4)
docker builder prune --keep-storage 10GB # (5)
docker volume prune # (6)- Deletes stopped containers that stopped more than 24 hours ago.
- Deletes only dangling images, the untagged leftovers from rebuilds. This is always safe.
- Deletes every image not used by any container and older than a week. Safe on build machines, slower afterwards because images must be pulled again.
- Deletes networks no container uses.
- Deletes build cache but keeps the most recently used 10 GB, so builds stay fast.
- Deletes anonymous volumes no container uses. Since Docker 23, named volumes are kept unless you add
-a. Still treat this command with care.
The big shortcut, and its trap. docker system prune does containers, networks, dangling images and build cache in one go. It does not touch volumes unless you add --volumes. On a database server, docker system prune -a --volumes can delete the database's data if its container happened to be stopped at that moment. Never run it there.
Rules for doing it safely:
- Check which machine you are on with
docker context show, especially if you use remote contexts (question 464). - Look before deleting.
docker volume lsanddocker ps -ashow what is about to go. - Use filters instead of deleting everything.
until=keeps recent items. Labels let you protect things:--filter "label!=keep". - Automate it on CI runners with a scheduled job, so disks never fill in the middle of a release.
465. What is the difference between docker save and docker load, and docker export and docker import?
The short answer
docker save packs a whole image into a tar file, keeping every layer, its history, its tags and its configuration, and docker load restores that exact image. docker export packs a container's current filesystem into a flat tar file, with no layers, no history and no configuration, and docker import turns such a file into a new single-layer image. Use save and load to move images. Export and import are rarely the right tool.
save and load | export and import | |
|---|---|---|
| Works on | An image | A container |
| Layers kept | Yes, all of them | No, flattened into one |
| History kept | Yes | No |
| Start command kept | Yes | No, must be set again |
| Main use | Moving images without a registry | Flattening a filesystem |
Save and load are for moving images between machines without a registry, for example into an air-gapped network, which is a network with no connection to the internet at all.
bash
docker save -o checkout-api-1.4.tar checkout-api:1.4 # (1)
docker load -i checkout-api-1.4.tar # (2)- Writes the image, with all its layers and metadata, into one tar file. You can then copy the file on a USB drive or through a secure transfer.
- On the other machine, restores the identical image with its tag.
Export and import work on a container's merged filesystem, the view described in question 463.
bash
docker export checkout-api-1 -o rootfs.tar # (1)
docker import --change 'CMD ["node","dist/server.js"]' rootfs.tar flat:1.0 # (2)- Writes every file the container currently sees into one tar. Layers, history, environment variables and the start command are all lost.
- Creates a new image with a single layer from that tar.
--changeadds back the start command, because import has no way of knowing it.
Why they ask: people often mix these up. Using export to "back up an image" silently throws away its configuration, and the copy then fails to start.
466. Why should you not build production images with docker commit?
The short answer
docker commit saves a container's current changes as a new image. That image has no recipe: nobody can see how it was made, review it, or rebuild it the same way when a security patch arrives. It also captures whatever junk is lying in the container, such as caches, temporary files, shell history and sometimes secrets. Production images should come from a Dockerfile in Git, built by CI.
docker commit takes a container's writable layer and turns it into a new image layer on top of the original image.
bash
docker run -it --name tinker debian:12-slim bash # someone installs things by hand...
docker commit tinker myteam/tool:1.0 # ...and saves the result as an imageIt feels convenient. It causes real problems:
- It cannot be reproduced. The steps happened in someone's terminal and are not recorded anywhere. Next month, when the base image gets a security fix, nobody can rebuild this image with the fix.
- It cannot be reviewed. There is no file to put in a pull request. Nobody can check what was installed, from where, or why.
- It captures junk. Package caches, temporary downloads, the shell's command history, and any password typed or pasted into the terminal all go into the image. Secrets in a committed image are readable by anyone who can pull it.
- It grows on itself. Committing on top of committed images keeps stacking layers and nothing is ever cleaned out.
- Nobody can prove where it came from. Supply-chain checks such as provenance and signing (question 146) depend on an image coming from a known, automated build.
The one good use: saving evidence. If a production container is misbehaving and you need to examine its exact state later, docker commit captures the filesystem as it is, so you can study it on another machine after the container is replaced.
The right way is always: write the steps in a Dockerfile, keep it in Git, and let the CI pipeline build it. Then every image has a recipe, a review, and a record.