About us Guides Projects Contacts
Админка
please wait

Docker has revolutionized how we build, ship, and run applications. Understanding Docker deeply—beyond basic commands—separates efficient DevOps workflows from painful debugging sessions. This guide covers essential Docker commands and production best practices from a senior developer's perspective.

Why Docker Mastery Matters

Deep Docker knowledge enables:

  1. Efficient Development: Fast iteration with containers
  2. Consistent Environments: Same container everywhere
  3. Resource Optimization: Smaller images, faster deployments
  4. Debugging Skills: Quick issue identification
  5. Production Readiness: Security and performance tuning

Essential Commands

Container Lifecycle

# Run a container in the background
docker run -d --name my-app nginx:latest
# Run with port mapping
docker run -d -p 8080:80 nginx:latest
# Run with multiple port mappings
docker run -d -p 8080:80 -p 3000:3000 my-app
# Run with environment variables
docker run -d -e NODE_ENV=production -e API_KEY=secret my-app
# Run with resource limits
docker run -d --cpus=0.5 --memory=256m my-app
# Run interactively
docker run -it ubuntu:latest bash
# Run and remove on exit
docker run --rm -it python:3.11 python

Container Management

# List running containers
docker ps
# List all containers (including stopped)
docker ps -a
# Custom output format
docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}"
# Stop container
docker stop my-app
# Start stopped container
docker start my-app
# Restart container
docker restart my-app
# Remove container
docker rm my-app
# Force-remove a running container
docker rm -f my-app
# Remove all stopped containers
docker rm $(docker ps -aq -f status=exited)

Executing Commands in Containers

# Execute a command in a running container
docker exec my-app ls -la
# Interactive shell
docker exec -it my-app bash
docker exec -it my-app sh # For Alpine-based images
# Execute as a specific user
docker exec -u root -it my-app bash
# Execute with an environment variable
docker exec -e DEBUG=true my-app npm test
# Get a container by name pattern
docker exec -it $(docker ps -aqf "name=my-app") bash

Logs and Monitoring

# View logs
docker logs my-app
# Follow logs (streaming)
docker logs -f my-app
# Show the last N lines
docker logs --tail 100 my-app
# Show logs with timestamps
docker logs -t my-app
# Show logs since timestamp
docker logs --since 2024-01-01T00:00:00 my-app
# Container resource usage
docker stats
# Specific container stats
docker stats my-app --no-stream
# Inspect container details
docker inspect my-app
# Get a specific field
docker inspect --format '{{.NetworkSettings.IPAddress}}' my-app

Image Management

Building Images

# Build from a Dockerfile in the current directory
docker build -t my-app .
# Build with a specific Dockerfile
docker build -f Dockerfile.prod -t my-app:prod .
# Build with build arguments
docker build --build-arg NODE_VERSION=18 -t my-app .
# Build without cache
docker build --no-cache -t my-app .
# Build with target stage (multi-stage)
docker build --target builder -t my-app:builder .
# Tag image
docker tag my-app:latest my-registry.com/my-app:v1.0.0

Managing Images

# List images
docker images
# List with size
docker images --format "{{.Repository}}:{{.Tag}} - {{.Size}}"
# Remove image
docker rmi my-app:latest
# Remove unused images
docker image prune
# Remove all unused images (not just dangling)
docker image prune -a
# Pull image
docker pull nginx:alpine
# Push image
docker push my-registry.com/my-app:v1.0.0

Volumes and Storage

Volume Management

# Create a named volume
docker volume create my-data
# List volumes
docker volume ls
# Inspect volume
docker volume inspect my-data
# Remove volume
docker volume rm my-data
# Remove unused volumes
docker volume prune

Mounting Volumes

# Named volume
docker run -v my-data:/app/data my-app
# Bind mount (host path)
docker run -v /host/path:/container/path my-app
# Bind mount current directory
docker run -v $(pwd):/app my-app
# Read-only mount
docker run -v /host/path:/container/path:ro my-app
# Volumes from another container
docker run --volumes-from data-container my-app

Networking

Network Management

# List networks
docker network ls
# Create network
docker network create my-network
# Create a bridge network with subnet
docker network create --driver bridge --subnet 172.20.0.0/16 my-network
# Connect container to network
docker network connect my-network my-app
# Disconnect from network
docker network disconnect my-network my-app
# Inspect network
docker network inspect my-network

Container Networking

# Run on a specific network
docker run --network my-network my-app
# Run on host network (no isolation)
docker run --network host my-app
# Link containers (legacy; use networks instead)
docker run --link db:database my-app

Dockerfile Best Practices

Optimized Dockerfile

# Use specific version tags
FROM node:20-alpine AS builder
# Set working directory
WORKDIR /app
# Copy dependency files first (layer caching)
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy source code
COPY . .
# Build application
RUN npm run build
# Production stage
FROM node:20-alpine AS production
# Create a non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nextjs -u 1001
WORKDIR /app
# Copy only necessary files from builder
COPY --from=builder --chown=nextjs:nodejs /app/dist ./dist
COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nextjs:nodejs /app/package.json ./
# Switch to a non-root user
USER nextjs
# Expose port
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
# Start application
CMD ["node", "dist/index.js"]

Layer Optimization

# BAD: Creates many layers
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y git
RUN rm -rf /var/lib/apt/lists/*
# GOOD: Single layer; cleanup included
RUN apt-get update && \
apt-get install -y --no-install-recommends \
curl \
git && \
rm -rf /var/lib/apt/lists/*

Multi-stage for Smaller Images

# Build stage with all dev dependencies
FROM golang:1.21 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o main .
# Minimal production image
FROM alpine:3.18
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/main .
CMD ["./main"]

System Maintenance

Cleanup Commands

# Remove all stopped containers
docker container prune
# Remove unused images
docker image prune
# Remove unused volumes
docker volume prune
# Remove unused networks
docker network prune
# Nuclear option: remove everything unused
docker system prune
# Include volumes and all images
docker system prune -a --volumes
# Show disk usage
docker system df
# Detailed disk usage
docker system df -v

Database Operations

MySQL/PostgreSQL Backup

# MySQL backup from container
docker exec my-mysql mysqldump -u root -ppassword dbname > backup.sql
# MySQL restore to container
cat backup.sql | docker exec -i my-mysql mysql -u root -ppassword dbname
# PostgreSQL backup
docker exec my-postgres pg_dump -U postgres dbname > backup.sql
# PostgreSQL restore
cat backup.sql | docker exec -i my-postgres psql -U postgres dbname

Production Deployment

Docker Compose for Production

version: '3.8'
services:
app:
image: my-app:${VERSION:-latest}
deploy:
replicas: 3
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.25'
memory: 256M
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"

Security Best Practices

# Don't run as root
USER 1001
# Use COPY instead of ADD (more predictable)
COPY requirements.txt .
# Don't store secrets in images
# Use --secret or environment variables at runtime
# Scan for vulnerabilities
# docker scan my-app:latest

Key Takeaways

  1. Use specific tags: Never use latest in production
  2. Optimize layers: Combine RUN commands; order by change frequency
  3. Multi-stage builds: Separate build and runtime environments
  4. Non-root users: Security best practice
  5. Health checks: Enable orchestrator self-healing
  6. Clean up regularly: Prevent disk space issues

Docker mastery comes from understanding both the commands and the underlying concepts—practice these patterns until they become second nature.

 
 
 
Языки
Темы
Copyright © 1999 — 2026
ZK Interactive