使用 docker 复制但排除

COPY with docker but with exclusion

在一个Docker文件中,我有

COPY . .

我想排除整个目录,在我的例子中,node_modules 目录。

像这样:

   COPY [all but **/node_modules/**] .

Docker可以吗?

在您的 docker 构建上下文目录中创建文件 .dockerignore(因此在本例中,很可能是 node_modules 的父目录),其中一行:

**/node_modules

尽管您可能只想:

node_modules

关于docker忽略的信息:https://docs.docker.com/engine/reference/builder/#dockerignore-file

添加 .dockerignore 对我有用。 补充一点那些在Windows上尝试这个解决方案的人,windows不会让你创建.dockerignore文件(因为默认情况下不允许创建以 .)

开头的文件

创建以 .在 Windows 上也包含一个结束点,例如:.dockerignore. 并按回车键(前提是您已从文件夹选项中启用查看扩展选项)

对于那些不能使用 .dockerignore 文件的人(例如,如果您需要一个 COPY 而不是另一个 COPY 中的文件):

是的,但是您需要多个 COPY 指令。具体来说,您需要为要排除的文件名中的每个字母复制一份。

COPY [^n]*    # All files that don't start with 'n'
COPY n[^o]*   # All files that start with 'n', but not 'no'
COPY no[^d]*  # All files that start with 'no', but not 'nod'

继续,直到您获得完整的文件名,或者只有您确信不会有任何其他文件的前缀。

从当前目录

中排除 node_modules
node_modules

在任何直接子目录中排除 node_modules

*/node_modules

这是official docs

对于单线解决方案,在命令提示符终端中键入以下内容项目根目录。

echo node_modules >> .dockerignore

此命令在 .dockerignore 文件中附加“node_modules”。如果 .dockerignore 不存在,它将创建一个新的。将 node_modules 替换为您要排除的文件夹。

警告: 如果您是 Docker 生态系统 and/or 的新手,您的项目中已有 .dockerignore 文件,请在继续之前进行备份。

奖金:(正如 Joey Baruch 所指出的)

(To CREATE/OVERWRITE the .dockerignore file via PowerShell, which can be handled by Docker):
>> echo node_modules | Out-File -Encoding UTF8 .dockerignore

对于那些使用 gcloud build 的用户:

gcloud build 忽略 .dockerignore 并寻找 .gcloudignore

使用:

cp .dockerignore .gcloudignore

Source