Docker Containers
Containers are runnable instances of Docker images. This page covers all essential commands for managing Docker containers.
Quick Reference
| Task | Command |
|---|---|
| Create container | docker container create -it --name <name> <image> |
| List containers | docker container list --all |
| Start container | docker container start <container> |
| Stop container | docker container stop <container> |
| Execute command | docker container exec -it <container> <command> |
| View logs | docker logs --follow <container> |
| Copy files | docker cp <src> <container>:<dest> |
| Remove container | docker container rm <container> |
| Remove stopped | docker 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.1Common 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 myimageRunning 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 myappCommon 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 myimageReal-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/bashListing 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 -aFormatted 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 dotnet31Starting 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 cacheStop 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 myappExecuting 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/bashNon-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 installReal-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 FLUSHALLViewing 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 myappAdvanced 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 myappCopying 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/binCopy 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}}' myappResource Usage
bash
# Real-time resource stats
docker stats myapp
# All containers stats
docker stats
# Resource usage without streaming
docker stats --no-streamProcess List
bash
# List processes in container
docker top myapp
# With custom format
docker top myapp auxRemoving 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 cacheBulk 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 myimageHealth Checks
dockerfile
# In Dockerfile
HEALTHCHECK --interval=30s --timeout=3s \
CMD curl -f http://localhost/ || exit 1bash
# View health status
docker container inspect --format='{{.State.Health.Status}}' myappDebugging 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 myimagePermission Issues
bash
# Run as root
docker container exec -it -u root myapp /bin/bash
# Check file permissions
docker container exec myapp ls -la /appNetwork 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.comResource 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}}' myappBest Practices
Naming Conventions
- Use descriptive names:
projectname-service-env - Include environment:
myapp-prod,myapp-dev - Avoid special characters
Resource Management
- Set resource limits for production containers
- Use restart policies appropriately
- Monitor resource usage with
docker stats - Clean up stopped containers regularly
Security
- Don't run containers as root
- Use read-only filesystems where possible:
--read-only - Drop unnecessary capabilities:
--cap-drop=ALL - Use secrets management for sensitive data
Logging
- Use structured logging in applications
- Configure log rotation
- Use centralized logging for production
- Don't log sensitive information
See Also
- Docker Images - Image management
- Docker Compose - Multi-container orchestration
- Docker Overview - Docker introduction
- Linux System Monitoring - Container host monitoring