6.2.1 Detached Mode
A focused guide to Detached Mode, connecting core concepts with practical Docker and container operations.
Detached mode, invoked with docker run -d, starts a container running in the background, immediately returning control of the terminal that launched it rather than streaming the container's output or waiting for it to exit.
Starting a Container in Detached Mode
The -d flag is the defining characteristic of detached mode, distinguishing it from the default foreground behavior.
docker run -d --name myapp myapp:1.0
This command returns immediately, printing the new container's ID, while the container itself continues running independently in the background.
Why Detached Mode Suits Long-Running Services
A web server, database, or other long-running service has no natural "completion" the terminal should wait for — detached mode reflects this, allowing the terminal to be used for other purposes immediately after launching the container.
docker run -d -p 8080:8080 myapp:1.0
docker ps
The container continues running and serving traffic, fully independent of the terminal session that started it.
Confirming a Detached Container Is Actually Running
Because detached mode doesn't display the container's output directly, separately confirming the container actually started successfully and remains running is a useful habit.
docker run -d --name myapp myapp:1.0
docker ps --filter "name=myapp"
Detached Mode Does Not Mean Disconnected From the Terminal Permanently
A detached container's output and behavior remain inspectable at any time afterward, despite not being streamed directly at launch.
docker logs myapp
docker exec -it myapp sh
Why Detached Mode Matters
Detached mode is the standard way to run long-lived services, decoupling the container's actual running lifetime from any specific terminal session, which is essential for any container meant to keep running independently of however it happened to be started.