How do I run a Docker container in the background?

Updated October 2026 · How we answer

Short answerUse the -d (detached) flag with docker run, e.g., 'docker run -d my-image'. The container runs in the background and prints the container ID.

Detached Mode Basics

Adding -d to your docker run command starts the container in the background (detached mode). Docker prints the full container ID and returns you to the shell. The container keeps running until it exits or you stop it.

You'll often combine -d with other flags: -p to publish ports, --name to give a friendly name, and -v to mount volumes. For example: 'docker run -d --name web -p 80:80 nginx' runs an Nginx container in the background, reachable on port 80.

  • docker run -d nginx — run nginx in background
  • docker run -d --name myapp -p 3000:3000 myapp:latest — named container with port mapping
  • docker ps — list running containers
  • docker logs myapp — view output from a detached container
  • docker stop myapp — stop it gracefully

Managing Background Containers

To check what's running, use 'docker ps'. To see all containers including stopped ones, use 'docker ps -a'. You can view logs with 'docker logs <container>' (add -f to follow live). To stop a container, use 'docker stop <container>'; to remove it, 'docker rm <container>'.

If you started a container without -d and want to detach, press Ctrl+P then Ctrl+Q. This leaves the container running. To reattach later, use 'docker attach <container>', but be careful: attaching to a container with a shell can be tricky, and exiting may stop it.

Common mistakes

  • Forgetting to publish ports with -p, then wondering why the service isn't reachable from the host.
  • Using 'docker run -d' with an image that exits immediately (e.g., a one-off script) and expecting it to stay up.
  • Stopping a container with 'docker stop' but then trying to start it again with 'docker run' — use 'docker start' instead.
From our shopsTitan Case: Premium MagSafe iPhone cases with a precision fit.