Skip to content
shellhacks.dev
DevOps

Run a Docker Container in the Background with -d

Start a container in the background with docker run -d. It prints the container ID and returns, and the container stops the moment its main process exits.

1 min read
Summarize in AI

A container started with -d exists for a moment and is gone from docker ps, and the command printed only an ID.

Shell
docker run -d --name web alpine:3.20 sh -c 'echo started; sleep 30' > /dev/null
docker ps --filter name=web --format '{{.Names}}: {{.State}}'
docker logs web
docker run -d --name quick alpine:3.20 echo hi > /dev/null
sleep 1
docker inspect -f '{{.Name}}: {{.State.Status}}, exit code {{.State.ExitCode}}' quick
docker rm -f web quick > /dev/null
Text
web: running
started
/quick: exited, exit code 0

-d detaches the client: the daemon starts the container, docker run prints its ID and returns, and the output goes to the log driver, which docker logs reads. A container lives exactly as long as its main process, so sleep 30 keeps web running while echo hi ends at once and leaves the container in the exited state, visible only with ps -a. See the docker run reference.

A service has to run in the foreground inside the container, since a daemon that forks itself looks like an exit to Docker and the container stops. -d and --rm can be combined, and then the logs disappear with the container. Use docker wait to block until a detached container finishes and to read its exit code.

Taggeddocker
Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.