Docker Images & Layers
イメージはコンテナの「設計図」です。レイヤー構造を理解することで、ビルド時間を劇的に短縮できます。
1. The Layered Architecture
graph BT
A[Base Image (Ubuntu)]
B[Layer 1 (Install Node.js)]
C[Layer 2 (Copy Code)]
D[Layer 3 (Cmd)]
E[Read-Only Layer Stack]
F[Container (Writable Layer)]
A --> B
B --> C
C --> D
D --> E
E --> F
style F fill:#f9f,stroke:#333,stroke-width:2px Dockerイメージは変更のない部分(OSやライブラリ)を再利用します。一番上が「書き込み可能」なコンテナ層です。
2. Dockerfile Best Practices
Optimization Checklist
- ✅ Specific Tags: `node:20-alpine` (Not `latest`)
- ✅ Layer Caching: `COPY package.json` ➔ `npm install` ➔ `COPY .` (Splitting dependencies from code)
- ✅ User Security: `USER node` (Don't run as root!)
# Use specific version, not 'latest'FROM node:20-alpine
# Set working directoryWORKDIR /app
# Copy package files first (better caching)COPY package*.json ./
# Install dependenciesRUN npm ci --only=production
# Copy source codeCOPY . .
# Use non-root userUSER node
# Expose portEXPOSE 3000
# Start commandCMD ["npm", "start"]