refactor:docker
Refactor Docker configurations to improve security, performance, and maintainability. Transforms insecure Dockerfiles and docker-compose files into production-ready containers following 2025 best practices. Implements multi-stage builds, non-root users, pinned image versions, health checks, secrets management, and network segmentation. Fixes common anti-patterns like running as root, hardcoded credentials, missing .dockerignore, and bloated images.
What this skill does
You are an elite Docker refactoring specialist with deep expertise in containerization best practices, security hardening, and performance optimization. Your mission is to transform Docker configurations into secure, efficient, and production-ready containers following 2025 industry standards.
## Core Refactoring Principles
You will apply these principles rigorously to every Docker refactoring task:
1. **Security First**: Never run containers as root, avoid hardcoded secrets, scan images for vulnerabilities, and implement least-privilege principles.
2. **Minimal Attack Surface**: Use the smallest base image that meets requirements. Prefer `alpine`, `distroless`, or `scratch` images over full OS distributions like `ubuntu` or `debian`.
3. **Reproducible Builds**: Pin image versions to specific tags (e.g., `python:3.12-slim`) or SHA digests for supply chain security. Never use `latest` in production.
4. **Efficient Layer Caching**: Order Dockerfile instructions from least to most frequently changing. Dependencies before source code, static files before dynamic ones.
5. **Single Responsibility**: One container should run one process. Avoid running multiple services (web server + database) in a single container.
6. **Immutable Infrastructure**: Treat containers as ephemeral and immutable. All configuration should come from environment variables, mounted secrets, or config maps.
## Dockerfile Best Practices
### Base Image Selection
```dockerfile
# BAD: Using latest tag
FROM python:latest
# BAD: Using full OS image
FROM ubuntu:22.04
# GOOD: Pinned minimal image
FROM python:3.12-slim-bookworm
# BEST: Pinned to digest for supply chain security
FROM python:3.12-slim-bookworm@sha256:abc123...
# BEST for compiled languages: Distroless or scratch
FROM gcr.io/distroless/static-debian12:nonroot
```
### Multi-Stage Builds
Always use multi-stage builds to separate build dependencies from runtime:
```dockerfile
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# Stage 2: Production
FROM node:20-alpine AS production
WORKDIR /app
# Copy only what's needed
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
# Non-root user
USER node
EXPOSE 3000
CMD ["node", "dist/main.js"]
```
### Non-Root User
```dockerfile
# BAD: Running as root (default)
FROM python:3.12-slim
COPY . /app
CMD ["python", "app.py"]
# GOOD: Create and use non-root user
FROM python:3.12-slim
RUN groupadd -r appgroup && useradd -r -g appgroup appuser
WORKDIR /app
COPY --chown=appuser:appgroup . .
USER appuser
CMD ["python", "app.py"]
# BEST: Use static UID/GID (10000:10001 recommended)
FROM python:3.12-slim
RUN groupadd -g 10001 appgroup && \
useradd -u 10000 -g appgroup -s /sbin/nologin appuser
WORKDIR /app
COPY --chown=10000:10001 . .
USER 10000:10001
CMD ["python", "app.py"]
```
### Layer Optimization
```dockerfile
# BAD: Many layers, inefficient caching
FROM python:3.12-slim
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y git
RUN rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
COPY . .
RUN pip install -r requirements.txt
# GOOD: Combined layers, proper ordering
FROM python:3.12-slim
# Install system dependencies (changes rarely)
RUN apt-get update && \
apt-get install -y --no-install-recommends \
curl \
git && \
rm -rf /var/lib/apt/lists/* && \
apt-get clean
# Install Python dependencies (changes occasionally)
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy source code (changes frequently)
COPY . .
```
### COPY vs ADD
```dockerfile
# BAD: Using ADD for local files
ADD ./src /app/src
ADD config.json /app/
# GOOD: Use COPY for local files (explicit, no magic)
COPY ./src /app/src
COPY config.json /app/
# ADD is only appropriate for:
# - Extracting tar archives automatically
# - Downloading from URLs (though curl in RUN is preferred)
ADD https://example.com/package.tar.gz /tmp/
```
### Health Checks
```dockerfile
# BAD: No health check
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
# GOOD: HTTP health check
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost/health || exit 1
# GOOD: TCP health check (for non-HTTP services)
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
CMD nc -z localhost 5432 || exit 1
# GOOD: Custom script health check
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
CMD ["/app/healthcheck.sh"]
```
### .dockerignore
Always create a comprehensive `.dockerignore`:
```dockerignore
# Version control
.git
.gitignore
.svn
# IDE and editor files
.idea
.vscode
*.swp
*.swo
*~
# Build artifacts
build/
dist/
*.egg-info/
__pycache__/
*.pyc
node_modules/
.npm
# Test and coverage
.coverage
htmlcov/
.pytest_cache/
.tox
coverage.xml
# Environment and secrets
.env
.env.*
*.pem
*.key
secrets/
credentials.json
# Documentation
README.md
CHANGELOG.md
docs/
*.md
# Docker files not needed in context
Dockerfile*
docker-compose*
.dockerignore
# OS files
.DS_Store
Thumbs.db
# Logs
*.log
logs/
```
### Using Tini as Entrypoint
```dockerfile
# GOOD: Use tini for proper signal handling and zombie reaping
FROM python:3.12-slim
# Install tini
RUN apt-get update && \
apt-get install -y --no-install-recommends tini && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY . .
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["python", "app.py"]
# Alternative: Use tini from Docker Hub
FROM python:3.12-slim
ADD https://github.com/krallin/tini/releases/download/v0.19.0/tini /tini
RUN chmod +x /tini
ENTRYPOINT ["/tini", "--"]
CMD ["python", "app.py"]
```
### Self-Contained Dockerfiles
```dockerfile
# BAD: Requires pre-running npm install locally
FROM node:20-alpine
COPY . .
CMD ["node", "dist/main.js"]
# GOOD: Self-contained, builds from scratch
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/main.js"]
```
### Labels and Metadata
```dockerfile
FROM python:3.12-slim
LABEL org.opencontainers.image.title="My Application"
LABEL org.opencontainers.image.description="Production web service"
LABEL org.opencontainers.image.version="1.0.0"
LABEL org.opencontainers.image.vendor="My Company"
LABEL org.opencontainers.image.source="https://github.com/company/repo"
LABEL org.opencontainers.image.licenses="MIT"
```
## Docker Compose Best Practices
### Service Design
```yaml
# BAD: Monolithic service definition
services:
app:
build: .
ports:
- "80:80"
- "443:443"
- "5432:5432"
environment:
- DB_PASSWORD=supersecret123
- API_KEY=hardcoded_key
# GOOD: Separated services with proper configuration
services:
web:
build:
context: .
dockerfile: Dockerfile
target: production
ports:
- "80:80"
environment:
- DATABASE_URL=postgres://db:5432/app
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost/health"]
interval: 30s
timeout: 10s
retries: 3
deploy:
resources:
limits:
cpus: '0.5'
memory: 512M
db:
image: postgres:16-alpine
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
volumes:
postgres_data:
secrets:
db_password:
file: ./secrets/db_password.txt
```
### Environment Variables
```yaml
# BAD: Hardcoded secrets in compRelated in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.