Docker▶ EP 008⏱️ ~2 min read

.dockerignore Best Practices: Controlling Build Context & Protecting Secrets

Prevent large build contexts, protect .env and .git directories from leaking into production container images.

Curated by Vibe DevOps · Published:

Dùng .dockerignore để loại node_modules, file không cần thiết và dữ liệu nhạy cảm khỏi build context. Giải thích tác động tới tốc độ build và rủi ro lộ secret.


1. Build Context là gì?

Khi bạn gõ lệnh:

docker build -t myapp .

Dấu chấm . đại diện cho thư mục hiện tại. Trước khi thực hiện bất kỳ lệnh nào trong Dockerfile, Docker CLI sẽ nén toàn bộ thư mục đó và gửi sang Docker Daemon qua socket.

Nếu thư mục của bạn có:
- Thư mục node_modules (500MB)
- Thư mục .git (lưu toàn bộ lịch sử commit, có thể nặng hàng GB)
- File .env chứa mật khẩu production database

Toàn bộ dữ liệu này sẽ bị gửi sang daemon một cách vô ích, làm tốn băng thông và tiềm ẩn nguy cơ bảo mật nghiêm trọng.


2. Mẫu .dockerignore để điều chỉnh theo dự án

Hãy tạo ngay file .dockerignore tại thư mục gốc của repository với nội dung sau:

# Git metadata
.git
.gitignore
.github

# Local dependencies & caches (Bắt buộc phải build lại trong container)
node_modules
npm-debug.log
vendor/
__pycache__/
*.pyc
.venv/
target/

# Sensitive & Secrets (Tuyệt đối không để lọt vào image)
.env
.env.*
*.pem
*.key
id_rsa
credentials.json

# Build artifacts & temp files
dist/
build/
coverage/
.idea/
.vscode/
*.swp
*.log
Dockerfile
.dockerignore

3. Tác động cần kiểm tra sau khi cấu hình

  1. Build context nhỏ hơn: Đo dung lượng context và thời gian build trước/sau; mức cải thiện phụ thuộc project và builder.
  2. Layer Caching hoạt động chính xác: Tránh việc chỉnh sửa file README hay file .git làm hỏng cache của lệnh COPY . ..
  3. Giảm rủi ro lộ secret: Các pattern chỉ loại file khớp khỏi context; vẫn cần secret scanning và kiểm tra image. Không dùng .dockerignore thay cơ chế build secrets.
TOPIC EXPLAINER VIDEO

Visual Breakdown: .dockerignore Best Practices: Controlling Build Context & Protecting Secrets

Watch this visual explainer to recap architectural trade-offs. Test and verify against your exact version before deploying.