.dockerignore 配置
.dockerignore 用于排除构建上下文中不需要的文件,下面介绍配置方法。
基本用法
在项目根目录创建 .dockerignore 文件:
Bash
# 版本控制
.git/
.gitignore
.svn/
# 依赖目录
node_modules/
vendor/
.venv/
# 日志文件
*.log
logs/
# 环境变量
.env
.env.*
*.env
# IDE 配置
.vscode/
.idea/
*.swp
*.swo
# Docker 文件
Dockerfile*
docker-compose*
.dockerignore
# 测试与文档
test/
tests/
*.md
docs/
语法说明
Bash
# 注释以 # 开头
# 每行一个模式
node_modules/ # 排除目录
*.log # 排除所有 .log 文件
temp?.txt # 通配符(? 匹配单个字符)
!important.log # ! 取反(不排除该文件)
模式匹配
| 模式 | 说明 | 示例 |
|---|---|---|
* | 匹配任意字符 | *.log |
? | 匹配单个字符 | temp?.txt |
** | 匹配任意目录 | **/*.log |
! | 取反 | !important.log |
示例
text
# 排除所有 .md 文件
*.md
# 但不排除 README.md
!README.md
常见场景
Go 项目
text
.git/
vendor/
*.md
test/
Dockerfile*
docker-compose*
*.exe
*.exe~
*.dll
Node.js 项目
text
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.npm
.eslintcache
coverage/
.env*
Python 项目
text
__pycache__/
*.pyc
.venv/
.env
.pytest_cache/
.mypy_cache/
*.egg-info/
与 .gitignore 对比
text
# 可复用 .gitignore
cp .gitignore .dockerignore
# 但通常 .dockerignore 更严格
# 因为构建上下文不需要测试、文档等文件
| 对比项 | .gitignore | .dockerignore |
|---|---|---|
| 用途 | 排除 Git 追踪 | 排除构建上下文 |
| 范围 | 代码仓库 | Docker 构建 |
| 严格度 | 宽松 | 严格 |
影响
text
# 不使用 .dockerignore
docker build -t my-app .
# 构建上下文:500MB(包含 node_modules)
# 使用 .dockerignore
docker build -t my-app .
# 构建上下文:5MB(仅包含必要文件)
构建上下文大小直接影响构建速度,特别是远程 Docker Daemon。
要点总结
- .dockerignore 排除构建上下文中不需要的文件,减小构建上下文
- 语法类似 .gitignore,支持
*、?、**通配符和!取反 - 排除 node_modules、.git、日志、测试、文档等无关文件
- 构建上下文大小影响构建速度,强烈建议配置
- 可复用 .gitignore 并根据 Docker 需求调整
📝 发现内容有误?点击此处直接编辑