Viết Dockerfile chuẩn: 7 best practices
VietDevOps
0:00 / 0:00
Viết Dockerfile chuẩn: 7 best practices
6 просмотров · 7 дней назад
VietDevOps
1 подписчик
6 просмотров · 7 дней назад
Viết được Dockerfile và viết Dockerfile chuẩn là hai chuyện hoàn toàn khác nhau. Video này hướng dẫn 7 best practices giúp image nhẹ hơn, build nhanh hơn và an toàn hơn: ghim version base image, chọn image tối giản, tận dụng layer caching, gộp RUN, multi-stage build, chạy non-root, .dockerignore và HEALTHCHECK.
Trong video: so sánh image 1.24GB vs 87MB, vì sao không dùng latest, alpine vs slim, thứ tự COPY để cache trúng, multi-stage build tách builder/runtime, tạo user non-root, file .dockerignore mẫu, HEALTHCHECK với start-period, và 3 sai lầm người mới hay mắc (CMD shell-form, quên WORKDIR, COPY ngoài build context).
⏱ Mục lục:
00:00 – Mở đầu: vì sao Dockerfile cẩu thả gây họa
01:31 – Ghim version + image tối giản (quy tắc 1+2)
03:18 – Layer caching + gộp RUN (quy tắc 3+4)
05:06 – Multi-stage build (quy tắc 5)
06:36 – Chạy dưới non-root user (quy tắc 6)
08:08 – .dockerignore + HEALTHCHECK (quy tắc 7)
10:08 – Tóm tắt checklist + video tiếp theo
💻 Lệnh trong video (copy dùng ngay):
-- Kiểm tra image sau build:
docker images
-- Quy tắc 1+2: ghim version + image tối giản (Dockerfile):
FROM node:20.11.1-alpine3.19
FROM python:3.12-slim-bookworm
-- Quy tắc 3: thứ tự COPY tận dụng cache (Dockerfile):
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . ./
-- Quy tắc 4: gộp RUN + dọn rác trong cùng layer (Dockerfile):
RUN apt-get update && apt-get install -y curl \
&& rm -rf /var/lib/apt/lists
-- Quy tắc 5: multi-stage build (Dockerfile):
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
RUN npm run build
FROM node:20-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/index.js"]
-- Build chỉ tới stage builder để chạy test trong CI:
docker build --target builder -t my-app:test .
-- Quy tắc 6: chạy dưới non-root user (Dockerfile):
RUN addgroup -S app && adduser -S app -G app
COPY --chown=app:app . .
USER app
CMD ["node", "dist/index.js"]
-- Kiểm tra user trong container:
docker exec web whoami
-- Quy tắc 7a: file .dockerignore mẫu:
node_modules
npm-debug.log
.git
.env
Dockerfile
.dockerignore
-- Quy tắc 7b: HEALTHCHECK (Dockerfile):
HEALTHCHECK --interval=30s --timeout=3s \
--start-period=60s \
CMD wget qO http://localhost:3000/health || exit 1
-- Kiểm tra sức khỏe container:
docker inspect web
-- Build image cuối cùng:
docker build -t my-app:1.0 .
📌 Video tiếp theo: Docker Compose — chạy cả stack app + database bằng 1 lệnh. Đăng ký kênh VietDevOps để không bỏ lỡ series Docker từ con số 0!
Kênh VietDevOps — DevOps • Cloud • AI, song ngữ Việt–Anh. Video nói tiếng Việt, có phụ đề tiếng Việt & tiếng Anh.
#docker #dockerfile #devops #vietdevops #hocdocker #multistagebuild #cloud