DEV Community

Cover image for 10 Docker & Kubernetes Commands That Every DevOps Engineer Uses Daily
MaxxMini
MaxxMini

Posted on

10 Docker & Kubernetes Commands That Every DevOps Engineer Uses Daily

I've been working with Docker and Kubernetes in production for years. Out of the 70+ commands I use regularly, these 10 come up every single day.

Here's each one with real examples, when to use them, and pro tips that took me way too long to figure out.


🐳 Docker Commands

1. docker build --target — Multi-Stage Builds

What it does: Builds only a specific stage from a multi-stage Dockerfile, so your production image stays tiny.

# Dockerfile
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:20-alpine AS production
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/index.js"]
Enter fullscreen mode Exit fullscreen mode
# Build only the production stage
docker build --target production -t myapp:latest .

# Build only the builder stage (for testing)
docker build --target builder -t myapp:test .
Enter fullscreen mode Exit fullscreen mode

When to use: Every production build. Your images go from 1GB+ to under 200MB.

💡 Pro tip: Use --target builder in CI to run tests without building the final image. Saves minutes per pipeline.


2. docker compose watch — Dev Hot Reload

What it does: Watches your source files and automatically syncs changes into running containers — no rebuild needed.

# docker-compose.yml
services:
  web:
    build: .
    develop:
      watch:
        - action: sync
          path: ./src
          target: /app/src
        - action: rebuild
          path: package.json
Enter fullscreen mode Exit fullscreen mode
docker compose watch
Enter fullscreen mode Exit fullscreen mode

When to use: Local development. Edit code, see changes instantly in your containerized app.

💡 Pro tip: Use action: rebuild for dependency files (package.json, requirements.txt) and action: sync for source code. This gives you the best of both worlds.


3. docker system prune -a — Disk Cleanup

What it does: Removes ALL unused images, containers, networks, and build cache. Reclaim gigabytes instantly.

# See what's eating your disk first
docker system df

# Nuclear option — remove everything unused
docker system prune -a --volumes

# Less aggressive — only dangling images
docker system prune
Enter fullscreen mode Exit fullscreen mode

When to use: When docker system df shows 20GB+ of reclaimable space (happens faster than you think).

💡 Pro tip: Run docker system prune -a --filter "until=168h" to only remove things older than 7 days. Keeps your recent work intact.


4. docker exec -it — Container Debugging

What it does: Opens an interactive shell inside a running container. Your #1 debugging tool.

# Open a bash shell
docker exec -it my-container bash

# If bash isn't available (alpine images)
docker exec -it my-container sh

# Run a one-off command
docker exec my-container cat /etc/nginx/nginx.conf

# Check environment variables
docker exec my-container env | grep DATABASE
Enter fullscreen mode Exit fullscreen mode

When to use: When something's wrong inside the container — check configs, test connectivity, inspect logs.

💡 Pro tip: If the container keeps crashing, use docker run --entrypoint sh -it myimage instead. You can't exec into a stopped container.


5. docker stats — Resource Monitoring

What it does: Real-time CPU, memory, network, and disk I/O for all running containers.

# All containers, live updating
docker stats

# Specific container, formatted output
docker stats my-container --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"

# One-shot (no streaming)
docker stats --no-stream
Enter fullscreen mode Exit fullscreen mode

When to use: When your app is slow or your machine is grinding. Find out which container is the culprit.

💡 Pro tip: Combine with --no-stream in monitoring scripts. Pipe to awk or jq for alerting when memory exceeds thresholds.


☸️ Kubernetes Commands

6. kubectl apply -f — Declarative Deployments

What it does: Creates or updates resources from YAML files. The foundation of GitOps.

# Apply a single file
kubectl apply -f deployment.yaml

# Apply an entire directory
kubectl apply -f ./k8s/

# Apply from URL (useful for installing tools)
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.7.0/aio/deploy/recommended.yaml

# Dry run — see what would change
kubectl apply -f deployment.yaml --dry-run=client -o yaml
Enter fullscreen mode Exit fullscreen mode

When to use: Every. Single. Deployment. Never use kubectl create in production.

💡 Pro tip: Always use --dry-run=server (not client) for accurate validation. Server-side dry run checks against admission webhooks and CRDs.


7. kubectl logs -f --previous — Crash Debugging

What it does: Shows logs from the previous container instance — critical when pods crash and restart.

# Follow current logs
kubectl logs -f pod-name

# Logs from crashed container
kubectl logs pod-name --previous

# Specific container in multi-container pod
kubectl logs pod-name -c sidecar --previous

# Last 100 lines with timestamps
kubectl logs pod-name --tail=100 --timestamps
Enter fullscreen mode Exit fullscreen mode

When to use: Pod in CrashLoopBackOff? --previous shows you why it crashed before the restart wiped the logs.

💡 Pro tip: Use kubectl logs -l app=myapp --all-containers to tail logs from ALL pods with a label. Essential for debugging distributed issues.


8. kubectl port-forward — Local Access to Pods

What it does: Tunnels a port from a pod or service to your local machine. Access internal services without exposing them.

# Forward pod port to localhost
kubectl port-forward pod/my-pod 8080:80

# Forward service (load-balanced across pods)
kubectl port-forward svc/my-service 8080:80

# Forward to a different local port
kubectl port-forward svc/postgres 5433:5432

# Listen on all interfaces (share with team)
kubectl port-forward --address 0.0.0.0 svc/my-service 8080:80
Enter fullscreen mode Exit fullscreen mode

When to use: Debugging internal services, accessing databases, testing APIs without creating an Ingress.

💡 Pro tip: Forward to a service (svc/) instead of a pod. If the pod restarts, service-based forwarding reconnects automatically.


9. kubectl rollout undo — Instant Rollback

What it does: Rolls back a deployment to the previous version in seconds. Your "oh no" button.

# Rollback to previous version
kubectl rollout undo deployment/my-app

# Rollback to a specific revision
kubectl rollout undo deployment/my-app --to-revision=3

# Check rollout history first
kubectl rollout history deployment/my-app

# Watch the rollback progress
kubectl rollout status deployment/my-app
Enter fullscreen mode Exit fullscreen mode

When to use: Bad deploy in production? This is faster than reverting commits, rebuilding, and redeploying.

💡 Pro tip: Always use --record flag (or kubernetes.io/change-cause annotation) with kubectl apply so rollout history shows meaningful revision descriptions.


10. kubectl top pods — Resource Usage

What it does: Shows real-time CPU and memory usage per pod. Requires metrics-server.

# All pods in current namespace
kubectl top pods

# Sort by CPU usage
kubectl top pods --sort-by=cpu

# Sort by memory
kubectl top pods --sort-by=memory

# Specific namespace
kubectl top pods -n production

# Node-level resources
kubectl top nodes
Enter fullscreen mode Exit fullscreen mode

When to use: Capacity planning, setting resource requests/limits, finding memory leaks.

💡 Pro tip: Compare kubectl top output with your resource requests and limits. If actual usage is 10x the request, your scheduler is making bad decisions.


These Are Just 10 Out of 70+

I use these daily, but my full workflow includes 60+ more commands for:

  • 🐳 Docker: Networking, volumes, multi-arch builds, BuildKit secrets, registry management
  • ☸️ Kubernetes: Secrets management, ConfigMaps, RBAC, HPA autoscaling, node affinity, taints & tolerations
  • 🔧 Debugging: Resource quotas, network policies, pod disruption budgets, init containers
  • 🚀 Production: Blue-green deployments, canary releases, cluster maintenance

I compiled all of them into a single cheat sheet:

More by MaxMini

🛠️ 27+ Free Developer Tools — JSON formatter, UUID generator, password analyzer, and more. All browser-based, no signup.

🎮 27 Browser Games — Built with vanilla JS. Play instantly, no install.

📚 Developer Resources on Gumroad — AI prompt packs, automation playbooks, and productivity guides.

💰 DonFlow — Free budget tracker. Plan vs reality, zero backend.

Every command with syntax, real examples, pro tips, and common gotchas. Print it, pin it, use it daily.


More Cheat Sheets for Engineers

If you found this useful, check out the rest of the series:


Like visualizing complex workflows? Check out DonFlow — a free interactive flowchart tool I built for engineering docs.


What's your most-used Docker or K8s command? Drop it in the comments 👇

Top comments (0)