如何在 Dockerfile 中添加所有 files/directories 除了像 .git 这样的隐藏目录

How to ADD all files/directories except a hidden directory like .git in Dockerfile

我们经常做的一件事是在构建 Docker 图像时将所有源代码打包在 Dockerfile 中。

ADD . /app

我们如何才能简单地避免包含 .git 目录?

我尝试了使用 ADD [^.]* /app/

的 Unix 处理方式

完整示例:

docker@boot2docker:/mnt/sda1/tmp/abc$ 找到 .
.
。/C
./.git
./Docker文件
。/好的
./good/a1
docker@boot2docker:/mnt/sda1/tmp/abc$ cat Docker文件
来自 ubuntu

添加 [^.]* /app/
docker@boot2docker:/mnt/sda1/tmp/abc$ docker build -t abc 。
将构建上下文发送到 Docker 守护进程 4.096 kB
将构建上下文发送到 Docker 守护程序
第 0 步:来自 ubuntu
 ---> 04c5d3b7b065
第 1 步:添加 [^.]* /app/
d ---> 5d67603f108b
移除中间容器 60159dee6ac8
成功构建5d67603f108b
docker@boot2docker:/mnt/sda1/tmp/abc$ docker 运行 -it abc
root@1b1705dd66a2:/# ls -l 应用程序
共 4 个
-rw-r--r-- 1 1000 名员工 22 年 1 月 30 日 01:18 Docker 文件
-rw-r--r-- 1 root root 0 Jan 22 01:03 a1
-rw-r--r-- 1 root root 0 Jan 22 00:10 c

其次,它会丢失目录结构,因为 good\a1 被更改为 a1

Docker中的相关源码是https://github.com/docker/docker/blob/eaecf741f0e00a09782d5bcf16159cc8ea258b67/builder/internals.go#L115

您可以在 .dockerignore file

的帮助下排除不需要的文件

How can we avoid including the .git directory in simple way ?

只需在根上下文文件夹中创建一个名为 .dockerignore 的文件,其中包含以下行

**/.git
**/node_modules

这样的行 Docker 将从包括根目录在内的任何子目录中排除目录 .gitnode_modules。 Docker 还支持一个特殊的通配符字符串 ** 匹配任意数量的目录(包括零个)。

And secondly, it will lose the directory structure, since good\a1 gets changed to a1

使用 .dockerignore 不会

$ docker run -it --rm sample tree /opt/
/opt/
├── Dockerfile
├── c
│   └── no_sslv2.patch
└── good
    └── a1
        └── README

3 directories, 3 files

参考官方文档:.dockerignore

在您的根目录中添加 .dockerignore 文件(语法类似于 .gitignore 文件)