Skip to content

Docker Containers

Containers are runnable instances of Docker images. This page covers all essential commands for managing Docker containers.

Quick Reference

TaskCommand
Create containerdocker container create -it --name <name> <image>
List containersdocker container list --all
Start containerdocker container start <container>
Stop containerdocker container stop <container>
Execute commanddocker container exec -it <container> <command>
View logsdocker logs --follow <container>
Copy filesdocker cp <src> <container>:<dest>
Remove containerdocker container rm <container>
Remove stoppeddocker container prune

Creating Containers

Basic Creation

bash
# Create container from image
docker container create --name myapp ubuntu:22.04

# Create with interactive terminal
docker container create -it --name myapp ubuntu:22.04

# Create with command
docker container create --name myapp ubuntu:22.04 /bin/bash

# Example: .NET container
docker container create -it --name dotnet31 mcr.microsoft.com/dotnet/core/runtime:3.1

Common Options

bash
# Port mapping
docker container create -p 8080:80 --name web nginx

# Volume mounting
docker container create -v /host/path:/container/path --name app myimage

# Environment variables
docker container create -e "API_KEY=secret" --name app myimage

# Network
docker container create --network mynetwork --name app myimage

# Restart policy
docker container create --restart unless-stopped --name app myimage

Running Containers

Run vs Create + Start

bash
# Run (create + start in one command)
docker run -it --name myapp ubuntu:22.04 /bin/bash

# Equivalent to:
docker container create -it --name myapp ubuntu:22.04 /bin/bash
docker container start myapp

Common Run Patterns

bash
# Run interactively (foreground)
docker run -it ubuntu:22.04 /bin/bash

# Run in background (detached)
docker run -d --name web nginx

# Run with auto-remove (container deleted on exit)
docker run --rm -it ubuntu:22.04 /bin/bash

# Run with port mapping
docker run -d -p 8080:80 --name web nginx

# Run with volume
docker run -d -v $(pwd):/app --name app myimage

Real-World Examples

bash
# Web server with port and volume
docker run -d \
  --name mywebsite \
  -p 8080:80 \
  -v $(pwd)/html:/usr/share/nginx/html \
  nginx:latest

# Database with persistent storage
docker run -d \
  --name postgres \
  -e POSTGRES_PASSWORD=secret \
  -v pgdata:/var/lib/postgresql/data \
  -p 5432:5432 \
  postgres:15

# Development environment
docker run -it --rm \
  --name dev \
  -v $(pwd):/workspace \
  -w /workspace \
  node:20 \
  /bin/bash

Listing Containers

Basic Listing

bash
# List running containers
docker container list

# List all containers (including stopped)
docker container list --all

# Short forms
docker ps
docker ps -a

Formatted Output

bash
# Custom format
docker container list --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

# Show only container IDs
docker container list --quiet

# Filter by status
docker container list --filter "status=running"
docker container list --filter "status=exited"

# Filter by name
docker container list --filter "name=web"

Example Output

CONTAINER ID   IMAGE                                        STATUS         PORTS                  NAMES
abc123def456   nginx:latest                                 Up 2 hours     0.0.0.0:8080->80/tcp  web
def456ghi789   mcr.microsoft.com/dotnet/core/runtime:3.1   Up 5 minutes                          dotnet31

Starting and Stopping

Start Containers

bash
# Start container
docker container start myapp

# Start container and attach to it
docker container start -a myapp

# Start multiple containers
docker container start web db cache

Stop Containers

bash
# Stop container (sends SIGTERM, then SIGKILL after timeout)
docker container stop myapp

# Stop with custom timeout (seconds)
docker container stop -t 30 myapp

# Stop all running containers
docker container stop $(docker container list -q)

Restart Containers

bash
# Restart container
docker container restart myapp

# Restart all running containers
docker container restart $(docker container list -q)

Pause and Unpause

bash
# Pause container (freeze processes)
docker container pause myapp

# Unpause container
docker container unpause myapp

Executing Commands

Interactive Shell

bash
# Execute bash in running container
docker container exec -it myapp /bin/bash

# Execute sh (for Alpine-based images)
docker container exec -it myapp /bin/sh

# Execute as specific user
docker container exec -it -u root myapp /bin/bash

Non-Interactive Commands

bash
# Run single command
docker container exec myapp ls -la /app

# Run command with environment variable
docker container exec -e "DEBUG=true" myapp node app.js

# Run command in specific directory
docker container exec -w /app myapp npm install

Real-World Examples

bash
# Check application logs
docker container exec myapp cat /var/log/app.log

# Restart service inside container
docker container exec myapp supervisorctl restart app

# Database backup
docker container exec postgres pg_dump -U user dbname > backup.sql

# Clear cache
docker container exec redis redis-cli FLUSHALL

Viewing Logs

Basic Log Viewing

bash
# View logs
docker logs myapp

# Follow logs in real-time
docker logs --follow myapp

# Show timestamps
docker logs --timestamps myapp

# Show last N lines
docker logs --tail 100 myapp

Advanced Log Options

bash
# Logs since specific time
docker logs --since 2024-01-01T00:00:00 myapp

# Logs from last N minutes
docker logs --since 30m myapp

# Logs until specific time
docker logs --until 2024-01-01T23:59:59 myapp

# Combine options
docker logs --follow --tail 50 --timestamps myapp

Copying Files

Copy to Container

bash
# Copy file to container
docker cp file.txt myapp:/app/

# Copy directory to container
docker cp ./config myapp:/etc/app/

# Copy from README example
docker cp bin/. dotnet31:/home/bin

Copy from Container

bash
# Copy file from container
docker cp myapp:/app/output.log ./

# Copy directory from container
docker cp myapp:/app/logs ./logs/

# Copy with archive mode (preserve attributes)
docker cp -a myapp:/app/data ./backup/

Inspecting Containers

Container Information

bash
# Full inspection (JSON)
docker container inspect myapp

# View specific fields
docker container inspect --format='{{.State.Status}}' myapp

# View IP address
docker container inspect --format='{{.NetworkSettings.IPAddress}}' myapp

# View mounted volumes
docker container inspect --format='{{.Mounts}}' myapp

Resource Usage

bash
# Real-time resource stats
docker stats myapp

# All containers stats
docker stats

# Resource usage without streaming
docker stats --no-stream

Process List

bash
# List processes in container
docker top myapp

# With custom format
docker top myapp aux

Removing Containers

Remove Specific Containers

bash
# Remove stopped container
docker container rm myapp

# Force remove running container
docker container rm -f myapp

# Remove multiple containers
docker container rm web db cache

Bulk Removal

bash
# Remove all stopped containers
docker container prune

# Remove without confirmation
docker container prune -f

# Remove containers older than 24 hours
docker container prune --filter "until=24h"

Remove All Containers

bash
# Stop and remove all containers
docker container stop $(docker container list -q)
docker container rm $(docker container list -aq)

# Or in one line
docker container rm -f $(docker container list -aq)

Container Lifecycle Management

Auto-Restart Policies

bash
# Never restart
docker run --restart no myimage

# Always restart
docker run --restart always myimage

# Restart on failure
docker run --restart on-failure myimage

# Restart unless stopped manually
docker run --restart unless-stopped myimage

Health Checks

dockerfile
# In Dockerfile
HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost/ || exit 1
bash
# View health status
docker container inspect --format='{{.State.Health.Status}}' myapp

Debugging and Troubleshooting

Container Won't Start

bash
# Check logs for errors
docker logs myapp

# Inspect exit code
docker container inspect --format='{{.State.ExitCode}}' myapp

# Try running with shell override
docker run -it --entrypoint /bin/bash myimage

Permission Issues

bash
# Run as root
docker container exec -it -u root myapp /bin/bash

# Check file permissions
docker container exec myapp ls -la /app

Network Issues

bash
# Check container IP
docker container inspect --format='{{.NetworkSettings.IPAddress}}' myapp

# Test connectivity
docker container exec myapp ping google.com

# Check DNS
docker container exec myapp nslookup google.com

Resource Constraints

bash
# Limit memory
docker run -m 512m myimage

# Limit CPU
docker run --cpus 2 myimage

# View current limits
docker container inspect --format='{{.HostConfig.Memory}}' myapp

Best Practices

Naming Conventions

  1. Use descriptive names: projectname-service-env
  2. Include environment: myapp-prod, myapp-dev
  3. Avoid special characters

Resource Management

  1. Set resource limits for production containers
  2. Use restart policies appropriately
  3. Monitor resource usage with docker stats
  4. Clean up stopped containers regularly

Security

  1. Don't run containers as root
  2. Use read-only filesystems where possible: --read-only
  3. Drop unnecessary capabilities: --cap-drop=ALL
  4. Use secrets management for sensitive data

Logging

  1. Use structured logging in applications
  2. Configure log rotation
  3. Use centralized logging for production
  4. Don't log sensitive information

See Also

Released under the MIT License.