docker run, ps, stop, rm and logs
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)You started ShopLite's order service in a container and walked away. Is it still running? Why did it stop? How do you clean up? Five commands answer all of that.
docker run flags that matter: -d, --name, --rm, -it
docker run creates a new container from an image and starts its main process. Flags such as -d, --name, --rm and -it go before the image name; everything after the image name is the command the container runs.
ShopLite's order ticker is a small Java program. Below is its code, then the command that runs it in a container in the background, and a throwaway interactive container.
Example 1 · The program inside the container: OrderTicker
public class OrderTicker { public static void main(String[] args) throws InterruptedException { int orders = args.length > 0 ? Integer.parseInt(args[0]) : 3; System.out.println("[ticker] ShopLite order ticker started"); for (int i = 1; i <= orders; i++) { Thread.sleep(500); System.out.println("[ticker] order #" + (1000 + i) + " placed"); } System.out.println("[ticker] done after " + orders + " orders"); }}[ticker] ShopLite order ticker started [ticker] order #1001 placed [ticker] order #1002 placed [ticker] order #1003 placed [ticker] done after 3 orders
What this code does
- It prints one log line to stdout every half second. With no argument it stops after 3 orders, so you can run it on your own computer first.
- In the container we pass
100000, so it keeps running for a long time and we can watch it withdocker psanddocker logs.
Example 2 · Starting containers with -d, --name, --rm and -it
Runs in: a terminal with Docker installed
# run OrderTicker.java from the current folder, in the background, named tickerdocker run -d --name ticker -v "$PWD":/app -w /app eclipse-temurin:25-jdk java OrderTicker.java 100000# a throwaway interactive container: deleted when jshell endsdocker run -it --rm eclipse-temurin:25-jdk jshell4f9c2d1a7b3e8c5d6e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d | Welcome to JShell -- Version 25.0.1 | For an introduction type: /help intro jshell> /exit | Goodbye
What this code does
-dprints the full 64-character container ID and returns at once;docker psshows the first 12 characters.-v "$PWD":/app -w /appshares the current folder as/appand works there, as in the Running your first container lesson (the Volumes lesson explains-v). In PowerShell write${PWD}.java OrderTicker.java 100000comes after the image name, so it is the container's command and100000is the program's argument. The JDK 25 image runs our Java 17 code without changes.- The jshell container has
-itbecause you type into it, and--rmbecause you will not need it again. After/exitit is gone fromdocker ps -atoo. Your version numbers will differ.
Four flags cover most runs:
-d(detached): run in the background and print the new container's ID. Your terminal is free again.--name ticker: give the container a fixed name. Without it, Docker picks a random one such aselated_raman.--rm: delete the container as soon as its main process ends. Good for one-off runs.-it:-ikeeps input open and-tgives a terminal. Use it for interactive programs such asjshellorsh.
Flags go before the image name. Everything after the image name is the command the container runs, plus that command's own arguments.
java OrderTicker.java ends, the container stops too.docker ps and ps -a: reading STATUS and PORTS
docker ps lists the containers that are running now. docker ps -a (all) also lists stopped ones, which still exist until you remove them.
List what is running now, then list everything, including containers that have stopped.
Example 3 · docker ps and docker ps -a
Runs in: a terminal with Docker installed
docker psdocker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4f9c2d1a7b3e eclipse-temurin:25-jdk "/__cacert_entrypoin…" 2 minutes ago Up 2 minutes ticker CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4f9c2d1a7b3e eclipse-temurin:25-jdk "/__cacert_entrypoin…" 2 minutes ago Up 2 minutes ticker 9b1e7c3a2f60 hello-world "/hello" 3 hours ago Exited (0) 3 hours ago elated_raman
What this code does
docker psshows onlytickerbecause it is the only running container.docker ps -aalso shows the oldhello-worldcontainer, which ended normally (Exited (0)) and was never removed.- COMMAND is cut to 20 characters: the Temurin image first runs a small certificate script, which then starts our
javacommand. PORTS is empty because nothing is published yet.
Read two columns first. STATUS says Up 2 minutes for a running container and Exited (143) 5 seconds ago for a stopped one; the number in brackets is the main process's exit code. PORTS lists published ports such as 0.0.0.0:8080->8080/tcp; it is empty when nothing is published. The next lesson, Port mapping, fills it in.
STATUS values you will see:
Created: made but never started.Up 3 minutes: running.Exited (0): the program ended normally. Any other number means an error or a signal.Restarting (1): Docker keeps restarting a crashing container because of a restart policy.
Predict the output
Read the STATUS column
Each row is from docker ps -a. Pick what happened to that container.
Round 1 of 2
ShopLite's nightly report job shows this row.
docker stop vs docker kill: SIGTERM, 10-second grace, SIGKILL
SIGTERM is the polite "please stop" signal that docker stop sends to a container's main process. The JVM answers it by running shutdown hooks. If the process is still alive after 10 seconds, Docker sends SIGKILL, which ends it at once.
Stopping is a short conversation between Docker and the process. This Java shutdown hook shows what the JVM does when the polite signal arrives; then come the commands.
Example 4 · A shutdown hook: what the JVM does on SIGTERM
public class GracefulShutdownDemo { public static void main(String[] args) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.out.println("[shutdown] hook started"); System.out.println("[shutdown] finishing order #1002"); System.out.println("[shutdown] closing database connections"); System.out.println("[shutdown] bye"); }));
System.out.println("[app] started, taking orders"); System.out.println("[app] order #1001 done"); System.out.println("[app] order #1002 in progress");
// docker stop sends SIGTERM; here we end the JVM ourselves so the demo stops System.exit(0); }}[app] started, taking orders [app] order #1001 done [app] order #1002 in progress [shutdown] hook started [shutdown] finishing order #1002 [shutdown] closing database connections [shutdown] bye
What this code does
- The hook is a
Threadthat the JVM starts when it is shutting down: onSystem.exit, whenmainends, or when the process gets SIGTERM fromdocker stop. - Here
System.exit(0)stands in fordocker stop, so the demo ends on its own. In a container, SIGTERM runs the same hook and the exit code becomes 143. - A hook should finish quickly: by default Docker sends SIGKILL after 10 seconds, and then the hook is cut off.
Example 5 · stop, kill, start and restart
Runs in: a terminal with Docker installed
docker stop ticker # SIGTERM, wait up to 10 s, then SIGKILLdocker ps -a --filter name=tickerdocker start ticker # same container runs againdocker kill ticker # SIGKILL at once, no shutdown hooksdocker ps -a --filter name=tickerdocker stop -t 30 ticker # (when running) wait up to 30 s instead of 10ticker CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4f9c2d1a7b3e eclipse-temurin:25-jdk "/__cacert_entrypoin…" 10 minutes ago Exited (143) 4 seconds ago ticker ticker ticker CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4f9c2d1a7b3e eclipse-temurin:25-jdk "/__cacert_entrypoin…" 10 minutes ago Exited (137) 2 seconds ago ticker
What this code does
docker stopreturned in about a second because the JVM ended as soon as it got SIGTERM: exit code 143. A container still running after 10 seconds would get SIGKILL.docker killgave exit code 137: the process was killed with no chance to clean up. Use it only whendocker stopdoes not work.docker startreused the same container (same ID);docker stop,startandkillall print the container's name when they succeed.
A signal is a short message the operating system sends to a process. The JVM reacts to SIGTERM by running its shutdown hooks: code you register with Runtime.getRuntime().addShutdownHook(...) to finish work and close connections. SIGKILL cannot be caught, so no hook runs.
The exit code tells you which one happened: 143 = 128 + 15 (SIGTERM) and 137 = 128 + 9 (SIGKILL). docker kill sends SIGKILL straight away.
Order of execution
When the app ignores SIGTERM
Put what happens after docker stop in order.
docker start ticker starts the same stopped container again (same name, same files, its command runs from the beginning). docker restart ticker is stop + start.docker logs -f --tail 50, and why apps log to stdout
docker logs prints what a container's main process wrote to standard output (stdout, what System.out writes to) and standard error (stderr, System.err). Add -f to keep following new lines and --tail 50 to start at the last 50.
The ticker prints orders to the console. These commands read what it printed so far and keep watching for new lines.
Example 6 · Reading and following logs
Runs in: a terminal with Docker installed
docker logs --tail 3 tickerdocker logs -f --tail 50 ticker # Ctrl+C stops following, not the container[ticker] order #1046 placed [ticker] order #1047 placed [ticker] order #1048 placed [ticker] order #1001 placed ... [ticker] order #1050 placed [ticker] order #1051 placed [ticker] order #1052 placed ^C
What this code does
--tail 3printed only the last three lines.-f --tail 50printed the last 50 and then waited; each new order line appeared as the program printed it.- Logs are kept while the container exists, even after
docker stop. Afterdocker rm tickerthey are gone:docker logs tickerthen saysNo such container: ticker.
That is why a containerised app should log to stdout. A log file written inside the container is invisible to docker logs, and it is deleted with the container. Spring Boot already logs to the console by default, so docker logs shoplite-api just works.
Three forms you will use:
docker logs ticker: everything so far.docker logs -f --tail 50 ticker: the last 50 lines, then keep following. Ctrl+C stops following; the container keeps running.docker logs --since 10m ticker: only the last 10 minutes. Add-tto show timestamps.
Cleaning up: rm, image rm, system prune and "name already in use"
docker rm deletes a stopped container together with its writable files and its logs. docker rm -f stops (kills) and deletes a running one in one step. docker image rm deletes an image that no container uses any more.
Stopped containers pile up and keep their names. Remove them with docker rm; the first lines show the error you get when you forget.
# second run with the same name fails while the old container exists:# docker: Error response from daemon: Conflict. The container name "/ticker" is already in use by container "4f9c2d1a7b3e...". You have to remove (or rename) that container to be able to reuse that name.docker rm ticker # remove the stopped container (frees the name)docker rm -f ticker # or: kill and remove a running onedocker image rm hello-world # remove an image no container usesdocker system prune # stopped containers, unused networks, # dangling images and build cachedocker system prune -a # ...and every image not used by a containerA stopped container still owns its name. Running docker run --name ticker ... again then fails with a Conflict error saying the name /ticker is already in use. Fix it by removing the old container, choosing another name, or using --rm so the name is freed when the container ends.
Fix the error
Fix the name conflict
The second command fails. Pick the replacement for line 2.
An old container named ticker still exists.
Error
docker: Error response from daemon: Conflict. The container name "/ticker" is already in use by container "4f9c2d1a7b3e...". You have to remove (or rename) that container to be able to reuse that name.
docker system prune asks [y/N] and lists what it will delete. It does not touch volumes unless you add --volumes; the Volumes lesson explains why that matters for database data.Next step
Check your understanding
12 quick questions