Mục tiêu:
- Giảm kích thước Docker image bằng cách loại bỏ file không cần thiết khi build image.
Cách tạo .dockerignore
1. Di chuyển vào thư mục chứa Dockerfile:
cd docker_images/dockerignore/
2. Tạo file .dockerignore:
vi .dockerignore
3. Nội dung mẫu .dockerignore:
## Ignore markdown files
**/*.md
## Ignore all .git directories
**/.git
## Ignore docs directory
src/docs/
## Ignore test directories
**/tests/
## Ignore README file
**/README
**/ là wildcard để tìm trong mọi thư mục con.
Build Image với .dockerignore
1. Tạo Dockerfile như thường lệ.
2. Build image:
docker image build -t weather-app:v5 .
Kiểm tra kết quả .dockerignore hoạt động
Chạy container và kiểm tra các file bị loại bỏ:
docker container run -d --name weather-ignore weather-app:v5
docker container exec weather-ignore ls -la /var/node
Nếu đúng: Không thấy README, .git/, docs/, tests/.
Tại sao .dockerignore quan trọng?
- Giảm dung lượng image
- Tăng tốc độ build
- Tránh rò rỉ file nội bộ (ex: tài liệu, test, repo)
Kết luận
- Luôn sử dụng
.dockerignoretrong dự án thực tế. - Loại bỏ những file không cần thiết như:
README.md,docs/,tests/.git/,.vscode/,.log, etc.
- Tương tự
.gitignorenhưng dành cho Docker build context.