Docker commands, Dockerfile syntax, Docker Compose, and container management essentials
Basic Commands
Container Lifecycle
Manage container lifecycle
# Run a container
docker run -d --name myapp nginx
# List running containers
docker ps
# List all containers
docker ps -a
# Stop a container
docker stop myapp
# Start a stopped container
docker start myapp
# Remove a container
docker rm myapp
# Remove all stopped containers
docker container prune Image Management
Work with Docker images
# Pull an image
docker pull nginx:latest
# List images
docker images
# Remove an image
docker rmi nginx:latest
# Remove unused images
docker image prune -a
# Build an image
docker build -t myapp:v1 .
# Tag an image
docker tag myapp:v1 myapp:latest Logs and Debugging
Debug and monitor containers
# View logs
docker logs myapp
# Follow logs (like tail -f)
docker logs -f myapp
# Execute command in running container
docker exec -it myapp bash
# Inspect container
docker inspect myapp
# View container stats
docker stats myapp Dockerfile
Basic Dockerfile
Simple Node.js application Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"] Multi-Stage Build
Optimize image size with multi-stage builds
# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/index.js"] Common Instructions
Important Dockerfile instructions
# Set environment variables
ENV NODE_ENV=production
# Create user (security best practice)
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001
USER nodejs
# Health check
HEALTHCHECK --interval=30s --timeout=3s \
CMD node healthcheck.js
# Volume for persistent data
VOLUME /app/data Docker Compose
Basic docker-compose.yml
Multi-container application definition
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
depends_on:
- db
db:
image: postgres:15
environment:
POSTGRES_PASSWORD: secret
volumes:
- db-data:/var/lib/postgresql/data
volumes:
db-data: Compose Commands
Common docker-compose commands
# Start services
docker-compose up -d
# Stop services
docker-compose down
# View logs
docker-compose logs -f web
# Execute command in service
docker-compose exec web bash
# Rebuild services
docker-compose up -d --build Networking
Network Commands
Manage Docker networks
# Create network
docker network create mynetwork
# List networks
docker network ls
# Run container on network
docker run -d --network mynetwork --name app nginx
# Connect container to network
docker network connect mynetwork myapp
# Inspect network
docker network inspect mynetwork Find this helpful?
Check out more cheatsheets and learning resources, or get in touch for personalized training.