This skill generates optimized Dockerfiles.
Overview
Automatically generates secure and efficient Dockerfiles according to the project type.
Key Features
- Multi-stage builds: Image size reduction
- Security: Non-root user, least privilege
- Cache optimization: Reduced build time
- Best practices: Docker recommended settings
- Multi-language support: Node.js, Python, Go, Java, etc.
Generation Examples
Node.js (Express)
# マルチステージビルド
FROM node:18-alpine AS builder
WORKDIR /app
# 依存関係のみ先にコピー(キャッシュ最適化)
COPY package*.json ./
RUN npm ci --only=production
# ソースコードコピー
COPY . .
# 本番イメージ
FROM node:18-alpine
# 非rootユーザー作成
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
WORKDIR /app
# ビルド成果物をコピー
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --chown=nodejs:nodejs . .
USER nodejs
EXPOSE 3000
CMD ["node", "server.js"]
Python (FastAPI)
FROM python:3.11-slim AS builder
WORKDIR /app
# システム依存関係
RUN apt-get update && \
apt-get install -y --no-install-recommends gcc && \
rm -rf /var/lib/apt/lists/*
# Python依存関係
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
# 本番イメージ
FROM python:3.11-slim
RUN adduser --disabled-password --gecos '' appuser
WORKDIR /app
# ビルドしたパッケージをコピー
COPY --from=builder /root/.local /home/appuser/.local
COPY --chown=appuser:appuser . .
USER appuser
ENV PATH=/home/appuser/.local/bin:$PATH
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Go
# ビルドステージ
FROM golang:1.21-alpine AS builder
WORKDIR /app
# 依存関係
COPY go.mod go.sum ./
RUN go mod download
# ビルド
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
# 最小イメージ
FROM scratch
COPY --from=builder /app/main /main
EXPOSE 8080
ENTRYPOINT ["/main"]
React (static site)
# ビルドステージ
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Nginxで配信
FROM nginx:alpine
COPY --from=builder /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
.dockerignore
node_modules
npm-debug.log
.git
.gitignore
README.md
.env
.DS_Store
*.log
dist
build
coverage
docker-compose.yml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
environment:
- NODE_ENV=production
volumes:
- ./data:/app/data
restart: unless-stopped
database:
image: postgres:15-alpine
environment:
POSTGRES_DB: myapp
POSTGRES_USER: user
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
volumes:
postgres_data:
Best practices
- Multi-stage builds: Image size reduction
- Layer caching: From files that change least frequently
- Non-root user: Improved security
- .dockerignore: Exclude unnecessary files
- Health check: Container monitoring
Version Information
- Skill version: 1.0.0