Running Containers in Detached Mode

Learn how to run Docker containers in the background using detached mode (-d flag). Understand container lifecycle management, log access, and how to reattach to running containers.

Basic Commands

Detailed Explanation

Background Containers with -d

By default, docker run attaches your terminal to the container's standard output and standard error streams. The detached mode flag (-d) runs the container in the background, freeing your terminal for other work:

docker run -d nginx

Docker prints the full container ID and returns you to the shell prompt immediately. The Nginx server continues running in the background.

Container ID and Naming

When a detached container starts, Docker outputs a 64-character hexadecimal container ID:

a3f5b7c9e1d2f4a6b8c0e2d4f6a8b0c2e4d6f8a0b2c4e6d8f0a2b4c6e8d0f2

You can reference the container by its full ID, a short prefix (first 12 characters), or a name. Naming is strongly recommended for production use:

docker run -d --name my-webserver nginx

Viewing Logs

Since the container output is not attached to your terminal, use docker logs to view it:

docker logs my-webserver        # All logs
docker logs -f my-webserver     # Follow (like tail -f)
docker logs --tail 50 my-webserver  # Last 50 lines

Reattaching to a Container

You can reattach your terminal to a detached container:

docker attach my-webserver

Caution: Pressing Ctrl+C while attached sends SIGINT to the container's PID 1, which may stop the container. Use Ctrl+P, Ctrl+Q to detach without stopping.

Executing Commands in a Running Container

Instead of attaching, you can run additional commands inside a running detached container:

docker exec -it my-webserver bash

This starts a new bash session inside the container without affecting the main Nginx process.

When to Use Detached Mode

  • Web servers (Nginx, Apache) that should run continuously.
  • Databases (PostgreSQL, MySQL, Redis) running as background services.
  • Message queues (RabbitMQ, Kafka) and other long-running infrastructure.
  • CI/CD agents that need to persist between jobs.

Use Case

Deploying a web server or database that needs to run continuously in the background on a development machine or production server, without tying up a terminal session.

Try It — Docker Run Command Builder

Open full tool