Docker 忽略 .dockerignore 中的模式

Docker ignores patterns in .dockerignore

我打算从 docker 图像中排除 python 生成的文件。所以我在上下文目录的根目录下添加了 .dockerignore

# Ignore generated files
*.pyc

哎呀docker build 忽略了这一点并复制了如下所示的整个目录树:

/contextdir/
|-- Dockerfile
\-- src/
    |-- a.py   # this is copies - all right
    \-- a.pyc  # this should be ignored, but is copied too. Why?

我终于明白是怎么回事了。出于某种原因,我找不到任何关于此的提及,也没有找到任何具有此类构造的示例 Dockerfile,因此在此处进行记录。这对其他人来说微不足道吗?

How to create a dockerignore file 处的引用不够清楚,像 *.pyc 这样的模式只在路径的开头匹配,或者对于上下文目录正下方的文件,但不是递归的。要使其递归工作,必须使用 **/ 语法:

# Ignore generated files
**/*.pyc

docs for .dockerignore state that the pattern matching use's Go's filepath matching logic。文档还介绍了递归模式:

Beyond Go’s filepath.Match rules, Docker also supports a special wildcard string ** that matches any number of directories (including zero). For example, **/*.go will exclude all files that end with .go that are found in all directories, including the root of the build context.