Dockerfile định nghĩa image theo từng layer — đặt COPY package.json + RUN npm install trước COPY source để tận dụng cache; dùng non-root USER và .dockerignore cho security và performance.
- Dockerfile là script định nghĩa cách build Docker image.
- Layer caching optimization: Docker cache mỗi instruction layer — nếu layer không thay đổi, dùng cache từ previous build.
- Đặt instructions ít thay đổi trước: FROM → COPY package*.json → RUN npm install → COPY . . — nếu source code thay đổi nhưng package.json không, Docker reuse cached npm install layer (tiết kiệm 1-2 phút). .dockerignore: exclude node_modules, .git, .env, build artifacts — tránh copy không cần thiết vào build context, giảm build time.
- Security — non-root user: mặc định container chạy root (risk nếu có vulnerability); thêm RUN addgroup -S appgroup && adduser -S appuser -G appgroup; USER appuser trước CMD — principle of least privilege.
- Health checks: HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://localhost:3000/health || exit 1 — Docker/K8s biết container có healthy không để route traffic.
- CMD vs ENTRYPOINT: ENTRYPOINT định nghĩa executable không thể override (docker run image args — args được pass vào ENTRYPOINT); CMD là default args có thể override; dùng kết hợp ENTRYPOINT ['node'] CMD ['server.js'] — có thể đổi file chạy nhưng không đổi runtime.
- Multi-line RUN với && và cleanup: RUN apt-get update && apt-get install -y ... && rm -rf /var/lib/apt/lists/* — clean trong cùng layer tránh layer to.