Docker Layer Caching / แคช Layer ของ Docker
Prerequisites / สิ่งที่ต้องเตรียม
- Docker Engine 20.10+ - รองรับ BuildKit สำหรับ caching ที่ดีขึ้น
- Dockerfile Knowledge - ความเข้าใจเกี่ยวกับ Docker commands และ layer structure
- Container Registry - Docker Hub, GitHub Container Registry หรือ private registry
บทนำ (Introduction)
Docker ใช้ layer-based filesystem แต่ละ command ใน Dockerfile จะสร้าง layer ใหม่ หากเนื้อหาของ layer ไม่เปลี่ยนแปลง Docker จะใช้ cache ที่มีอยู่แล้ว ทำให้ build เร็วขึ้นอย่างมาก
Key Concept
Docker cache ทำงานโดยเปรียบเทียบ hash ของแต่ละ layer หากเหมือนเดิมจะใช้ cache เลย
Writing Optimized Dockerfiles / เขียน Dockerfile ให้ Optimize
Best Practices:
1. เรียงลำดับ commands ให้ถูกต้อง
วาง commands ที่มีการเปลี่ยนแปลงน้อยไว้ท้ายสุด
2. ใช้ .dockerignore
ลบ files ที่ไม่จำเป็นออกจาก context build
3. รวม RUN commands
ใช้ && เพื่อรวมหลาย commands เป็น layer เดียว
4. กำหนด dependencies ก่อน
COPY package.json ก่อน COPY . เพื่อ cache node_modules
Example Dockerfile:
# Multi-stage Dockerfile with caching
FROM node:20-alpine AS builder
WORKDIR /app
# Copy dependency files first (for caching)
COPY package*.json ./
# Install dependencies (cached if package.json unchanged)
RUN npm ci --only=production
# Copy source code
COPY . .
# Build application
RUN npm run build
# Production stage
FROM node:20-alpine AS production
WORKDIR /app
# Copy from builder stage
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
EXPOSE 3000
CMD ["node", "dist/index.js"]
BuildKit Cache / Cache ของ BuildKit
BuildKit เป็น backend build ของ Docker ที่รองรับ advanced caching features เช่น registry caching และ inline caching
# Enable BuildKit (Docker 23.04+)
export DOCKER_BUILDKIT=1
# Build with BuildKit
docker build --build-arg BUILDKIT_INLINE_CACHE=1 -t myapp .
# Build with registry cache
docker build \
--cache-from type=registry,ref=myregistry.com/myapp:cache \
--cache-to type=registry,ref=myregistry.com/myapp:cache,mode=max \
-t myapp .
Registry Cache
เก็บ cache ไว้ที่ container registry สำหรับแชร์ระหว่าง builds
Local Cache
เก็บ cache ใน local machine สำหรับ builds ถัดไป
Multi-Stage Builds / Builds หลาย Stage
Multi-stage builds ช่วยลดขนาด final image โดยใช้หลาย FROM statements และ COPY --from
ข้อดี: ลดขนาด image 50-80% และไม่รวม build tools ใน final image