Run Docker in Detached Mode

Detached Running of Docker Containers

Overview

Running Docker containers in detached mode (-d flag) allows them to operate in the background, freeing up your terminal for other tasks. This is particularly useful for long-running services such as web servers, databases, and background processes.

Key Features

  • Background Operation: The container runs independently in the background.
  • Log Access: Container logs are accessible using docker logs.
  • Process Management: Docker manages the container process, allowing you to start, stop, and restart it.
  • Monitoring: Detached containers can be monitored with Docker commands.

Basic Command

To run a container in detached mode:

docker run -d --name <container_name> <image_name>

Example: Running an SSH Server in Detached Mode

Dockerfile:

# Use Alpine Linux as a parent image
FROM alpine:latest

# Install necessary packages
RUN apk update && \
    apk add --no-cache git openssh && \
    rm -rf /var/cache/apk/*

# Set the working directory in the container.
WORKDIR /app

# Create a Git user
RUN adduser -D -s /bin/sh git && \
    mkdir -p /home/git/.ssh && \
    chown git:git /home/git/.ssh && \
    chmod 700 /home/git/.ssh

# Set up SSH server
RUN mkdir /var/run/sshd && \
    echo 'git ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers && \
    sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config && \
    sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin no/' /etc/ssh/sshd_config && \
    echo 'AllowUsers git' >> /etc/ssh/sshd_config

# Generate SSH host keys
RUN ssh-keygen -A

# Expose SSH port
EXPOSE 22

# Start SSH server and keep the container running
CMD ["/bin/sh", "-c", "/usr/sbin/sshd && while :; do sleep 2073600; done"]

Build and Run:

  1. Build the Docker image:

    docker build -t git-ssh-server .
    
  2. Run the container in detached mode:

    docker run -d -p 2222:22 -e SSH_KEY="$(cat ~/.ssh/id_rsa.pub)" --name git-ssh-server-container git-ssh-server
    

Managing Detached Containers

  • List Running Containers:

    docker ps
    
  • View Logs:

    docker logs <container_id>
    
  • Attach to Container:

    docker attach <container_id>
    
  • Stop Container:

    docker stop <container_id>
    
  • Remove Container:

    docker rm <container_id>
    

Advantages

  • Resource Management: Run multiple containers without blocking the terminal.
  • Automation: Ideal for scripts that need to start containers and perform other tasks concurrently.
  • Background Services: Perfect for long-running services that need continuous operation.

Running containers in detached mode enhances efficiency, allowing for better resource management and multitasking capabilities in your development and production environments.