0
0
DockerHow-ToBeginner · 3 min read

How to Run a Docker Container in Background | Quick Guide

To run a Docker container in the background, use the docker run -d command. The -d flag stands for detached mode, which starts the container without attaching your terminal to it.
📐

Syntax

The basic syntax to run a container in the background is:

  • docker run: Command to create and start a container.
  • -d: Runs the container in detached mode (background).
  • image_name: The Docker image to use for the container.
bash
docker run -d image_name
💻

Example

This example runs an Nginx web server container in the background. You can check running containers with docker ps.

bash
docker run -d --name mynginx -p 8080:80 nginx
Output
a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ... mynginx nginx "/docker-entrypoint.…" 10 seconds ago Up 9 seconds 0.0.0.0:8080->80/tcp mynginx
⚠️

Common Pitfalls

Common mistakes when running containers in background include:

  • Forgetting the -d flag, which keeps the container attached and blocks the terminal.
  • Not mapping ports, so the service inside the container is not accessible.
  • Not naming containers, which makes managing multiple containers harder.
bash
docker run nginx
# This runs in foreground and blocks terminal

docker run -d nginx
# Correct way to run in background
📊

Quick Reference

OptionDescription
-dRun container in detached (background) mode
--name Assign a name to the container
-p :Map host port to container port
docker psList running containers
docker logs View logs of a container

Key Takeaways

Use -d flag with docker run to start containers in background.
Always map ports with -p to access container services from your host.
Name your containers with --name for easier management.
Check running containers with docker ps.
Without -d, the container runs attached and blocks your terminal.