Docker Command Line Tips - Complete Guide
Published: September 25, 2024 | Reading time: 19 minutes
Docker CLI Overview
Master Docker command line with essential tips and advanced techniques:
Docker Command Categories
# Container Management
- docker run, start, stop, restart
- docker exec, attach, logs
- docker ps, inspect, stats
# Image Management
- docker build, pull, push
- docker images, rmi, tag
- docker save, load
# Volume & Network
- docker volume, network
- docker-compose commands
Essential Docker Commands
Container Lifecycle
Basic Container Commands
# Run a container
docker run -d --name myapp nginx:latest
# Run with port mapping
docker run -d -p 8080:80 --name web nginx:latest
# Run with environment variables
docker run -d -e NODE_ENV=production --name app node:18
# Run with volume mount
docker run -d -v /host/path:/container/path --name data alpine:latest
# Start/stop containers
docker start myapp
docker stop myapp
docker restart myapp
# Remove container
docker rm myapp
# Remove running container (force)
docker rm -f myapp
Container Inspection
Container Information
# List running containers
docker ps
# List all containers (including stopped)
docker ps -a
# List containers with custom format
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
# Inspect container details
docker inspect myapp
# View container logs
docker logs myapp
# Follow logs in real-time
docker logs -f myapp
# View last N lines of logs
docker logs --tail 100 myapp
# Show container resource usage
docker stats myapp
# Show all containers stats
docker stats
Image Management
Building and Managing Images
Image Commands
# Build image from Dockerfile
docker build -t myapp:latest .
# Build with specific Dockerfile
docker build -f Dockerfile.prod -t myapp:prod .
# Build with build arguments
docker build --build-arg NODE_ENV=production -t myapp:prod .
# Pull image from registry
docker pull nginx:latest
# Push image to registry
docker push myapp:latest
# Tag image
docker tag myapp:latest myregistry.com/myapp:v1.0
# List images
docker images
# List images with custom format
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"
# Remove image
docker rmi myapp:latest
# Remove unused images
docker image prune
# Remove all unused images (including tagged)
docker image prune -a
Multi-Stage Builds
Dockerfile Multi-Stage
# Multi-stage build example
FROM node:18-alpine AS base
WORKDIR /app
COPY package*.json ./
FROM base AS deps
RUN npm ci --only=production
FROM base AS build
RUN npm ci
COPY . .
RUN npm run build
FROM node:18-alpine AS production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY package*.json ./
EXPOSE 3000
CMD ["npm", "start"]
# Build specific stage
docker build --target deps -t myapp:deps .
# Build all stages
docker build -t myapp:latest .
Volume Management
Docker Volumes
Volume Commands
# Create volume
docker volume create myvolume
# List volumes
docker volume ls
# Inspect volume
docker volume inspect myvolume
# Remove volume
docker volume rm myvolume
# Remove unused volumes
docker volume prune
# Run container with named volume
docker run -d -v myvolume:/data --name app alpine:latest
# Run container with bind mount
docker run -d -v /host/path:/container/path --name app alpine:latest
# Run container with tmpfs mount
docker run -d --tmpfs /tmp --name app alpine:latest
# Copy files to/from container
docker cp file.txt myapp:/path/to/destination
docker cp myapp:/path/to/file.txt ./local-file.txt
Network Management
Docker Networks
Network Commands
# Create network
docker network create mynetwork
# List networks
docker network ls
# Inspect network
docker network inspect mynetwork
# Remove network
docker network rm mynetwork
# Remove unused networks
docker network prune
# Run container on specific network
docker run -d --network mynetwork --name app1 nginx:latest
docker run -d --network mynetwork --name app2 nginx:latest
# Connect existing container to network
docker network connect mynetwork existing-container
# Disconnect container from network
docker network disconnect mynetwork existing-container
# Create network with custom driver
docker network create --driver bridge --subnet=172.20.0.0/16 mynetwork
Docker Compose
Compose Commands
Docker Compose
# Start services
docker-compose up
# Start services in background
docker-compose up -d
# Start specific service
docker-compose up web
# Build and start
docker-compose up --build
# Stop services
docker-compose down
# Stop and remove volumes
docker-compose down -v
# Stop and remove images
docker-compose down --rmi all
# View running services
docker-compose ps
# View logs
docker-compose logs
# Follow logs
docker-compose logs -f
# Execute command in service
docker-compose exec web bash
# Scale service
docker-compose up --scale web=3
# Restart service
docker-compose restart web
# Pull latest images
docker-compose pull
Advanced Docker Tips
Resource Management
Resource Limits
# Run container with memory limit
docker run -d --memory=512m --name app nginx:latest
# Run container with CPU limit
docker run -d --cpus=1.5 --name app nginx:latest
# Run container with both limits
docker run -d --memory=512m --cpus=1.0 --name app nginx:latest
# Run container with memory reservation
docker run -d --memory-reservation=256m --name app nginx:latest
# Run container with ulimits
docker run -d --ulimit nofile=1024:1024 --name app nginx:latest
# Run container with security options
docker run -d --read-only --name app nginx:latest
docker run -d --user=1000:1000 --name app nginx:latest
# Run container with restart policy
docker run -d --restart=unless-stopped --name app nginx:latest
Debugging and Troubleshooting
Debug Commands
# Execute command in running container
docker exec -it myapp bash
# Execute command as root
docker exec -it --user root myapp bash
# Execute command with specific working directory
docker exec -it -w /app myapp bash
# Attach to container's main process
docker attach myapp
# View container processes
docker exec myapp ps aux
# View container environment variables
docker exec myapp env
# View container network configuration
docker exec myapp ip addr
# View container disk usage
docker exec myapp df -h
# Check container health
docker inspect --format='{{.State.Health.Status}}' myapp
Docker Shortcuts and Aliases
Useful Aliases
Bash Aliases
# Add to ~/.bashrc or ~/.zshrc
# Container management
alias dps='docker ps'
alias dpsa='docker ps -a'
alias dstop='docker stop'
alias dstart='docker start'
alias drestart='docker restart'
alias drm='docker rm'
alias drmf='docker rm -f'
# Image management
alias dimg='docker images'
alias drmi='docker rmi'
alias dpull='docker pull'
alias dpush='docker push'
alias dbuild='docker build'
# Logs and inspection
alias dlogs='docker logs'
alias dlogsf='docker logs -f'
alias dinspect='docker inspect'
alias dstats='docker stats'
# Docker Compose shortcuts
alias dc='docker-compose'
alias dcu='docker-compose up'
alias dcd='docker-compose down'
alias dcb='docker-compose up --build'
alias dce='docker-compose exec'
alias dcl='docker-compose logs'
alias dclf='docker-compose logs -f'
# Cleanup commands
alias dclean='docker system prune -f'
alias dcleanall='docker system prune -a -f'
alias dcleanvol='docker volume prune -f'
alias dcleanimg='docker image prune -f'
Docker Best Practices
Performance Optimization
Optimization Tips
# Use .dockerignore file
echo "node_modules" >> .dockerignore
echo "*.log" >> .dockerignore
echo ".git" >> .dockerignore
echo "Dockerfile" >> .dockerignore
# Optimize Dockerfile layers
# Bad: Multiple RUN commands
RUN apt-get update
RUN apt-get install -y nodejs
RUN apt-get install -y npm
# Good: Single RUN command
RUN apt-get update && \
apt-get install -y nodejs npm && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# Use specific base images
# Bad: node:latest
# Good: node:18-alpine
# Copy package files first for better caching
COPY package*.json ./
RUN npm ci --only=production
COPY . .
# Use multi-stage builds for smaller images
FROM node:18-alpine AS builder
# ... build steps
FROM node:18-alpine AS production
COPY --from=builder /app/dist ./dist
Security Best Practices
Security Tips
# Run containers as non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
USER nextjs
# Use read-only filesystem
docker run --read-only --name app nginx:latest
# Limit container capabilities
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE --name app nginx:latest
# Use security options
docker run --security-opt=no-new-privileges --name app nginx:latest
# Scan images for vulnerabilities
docker scan nginx:latest
# Use secrets for sensitive data
echo "mysecret" | docker secret create my_secret -
docker service create --secret my_secret nginx:latest
# Use health checks
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:3000/health || exit 1
Docker Monitoring
Monitoring Commands
Monitoring
# Monitor container resource usage
docker stats --no-stream
# Monitor specific containers
docker stats container1 container2
# Monitor with custom format
docker stats --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}"
# View Docker system information
docker system df
# View Docker system events
docker events
# View Docker system events with filter
docker events --filter container=myapp
# View Docker daemon information
docker info
# View Docker version
docker version
# Monitor Docker Compose services
docker-compose ps
docker-compose top
Docker Troubleshooting
Common Issues and Solutions
Troubleshooting
# Container won't start
docker logs myapp
docker inspect myapp
# Container keeps restarting
docker inspect myapp | grep -A 10 "RestartPolicy"
# Out of disk space
docker system df
docker system prune -a
# Port already in use
docker ps | grep :8080
netstat -tulpn | grep :8080
# Permission denied
docker run --user root myapp
docker exec -it --user root myapp bash
# Network connectivity issues
docker network ls
docker network inspect bridge
# Volume mount issues
docker volume ls
docker volume inspect myvolume
# Image pull failures
docker login
docker pull nginx:latest
# Build failures
docker build --no-cache -t myapp .
docker build --progress=plain -t myapp .
Docker Scripts and Automation
Useful Scripts
Automation Scripts
#!/bin/bash
# docker-cleanup.sh - Clean up Docker resources
echo "Cleaning up Docker resources..."
# Stop all running containers
docker stop $(docker ps -q) 2>/dev/null || true
# Remove all containers
docker rm $(docker ps -aq) 2>/dev/null || true
# Remove all images
docker rmi $(docker images -q) 2>/dev/null || true
# Remove all volumes
docker volume rm $(docker volume ls -q) 2>/dev/null || true
# Remove all networks
docker network rm $(docker network ls -q) 2>/dev/null || true
# System cleanup
docker system prune -a -f
echo "Docker cleanup completed!"
#!/bin/bash
# docker-backup.sh - Backup Docker volumes
VOLUME_NAME="myvolume"
BACKUP_FILE="backup-$(date +%Y%m%d-%H%M%S).tar"
echo "Creating backup of volume: $VOLUME_NAME"
docker run --rm -v $VOLUME_NAME:/data -v $(pwd):/backup alpine tar czf /backup/$BACKUP_FILE -C /data .
echo "Backup created: $BACKUP_FILE"
Summary
Master Docker command line with these essential tips:
- Learn basic commands: run, ps, logs, exec, build, push
- Use Docker Compose: Manage multi-container applications
- Optimize images: Multi-stage builds, .dockerignore, specific tags
- Manage resources: Memory limits, CPU limits, restart policies
- Use aliases: Create shortcuts for common commands
- Monitor and debug: stats, logs, inspect, events
- Follow security practices: Non-root users, read-only filesystems
Need More Help?
Struggling with Docker command line or need help optimizing your container workflows? Our Docker experts can help you master container management and deployment.
Get Docker Help