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!)
Dockerfile
# Use specific version, not 'latest'
FROM node:20-alpine
# Set working directory
WORKDIR /app
# Copy package files first (better caching)
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy source code
COPY . .
# Use non-root user
USER node
# Expose port
EXPOSE 3000
# Start command
CMD ["npm", "start"]