Docker foreground vs detached containers
Quick answer
By default, docker run attaches the terminal to the container’s output and waits while the container runs. Add -d to return control to your terminal while the container runs separately. Detached mode does not make a short-lived program stay alive.
Before you run commands
Use an approved disposable Linux-container Docker lab. Confirm the effective context and permissions; use a reviewed, locally preloaded busybox:1.37 image whose digest/platform the lab owner has recorded. This tag is mutable. Do not download an image automatically; --pull=never requires it locally. The new containers use --network none, with no host mounts or published ports; the CLI still connects to the selected engine. Verify the approved image tag still resolves to the recorded image before creating containers. Check docker ps -a for all names used below. If any is occupied, choose fresh names consistently. Run commands one at a time and stop on any unexpected failure; never act on resources you did not create. Expected results are predictions, not measured execution.
How it works
Use the same small job in two modes. sleep 3 waits for three seconds; the shell then prints a final message. The first command keeps the terminal occupied until completion. The detached command prints a container ID. docker wait waits for completion and prints the program exit code; docker logs reads captured output in this lab. A fast job may already have finished by the time you list it. A detached launch is not a readiness check; no terminal attachment is required for a container to keep running while its main program is active.
docker run --rm --pull=never --network none busybox:1.37 sh -c 'echo begin; sleep 3; echo done'Expect begin, a short wait, and done before control returns.
docker run -d --pull=never --network none --name bm02-detach busybox:1.37 sh -c 'echo begin; sleep 3; echo done'docker wait bm02-detachdocker logs bm02-detachdocker rm bm02-detachThe ID is printed first, then wait prints 0 on normal completion. Logs should contain both messages.
Common mistake
Do not infer that a container is running merely because a detached launch returned an ID. Inspect state and logs. Do not treat a backgrounded application process as a substitute for a suitable main process.
Try it yourself
Change the delay to five seconds and predict the difference in terminal behavior. Compare the messages from both modes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Docker foreground vs detached containers — knowledge check
Apply the lifecycle concepts and interpret the lab behavior.
What does -d change?
A detached command prints a message and exits. What happens?
Which command retrieves captured output after the job ends?