Dockerfile 优秀实践
1. 善用.dockerignore文件
Docker 是CS架构,这就意味着 Client 和 Server 可以在不同的主机上。在构建镜像的时候,Client 会把所有需要的文件打包发送给 Server,这些发送的文件叫做 build context
默认情况下,构建上下文中所有的文件都会被打包发送给 Docker deamon,但是我们可以使用 .dockerignore 来忽略 build context 中的某些路径和文件,从而避免发送不必要的数据内容,从而加快镜像的创建过程,特别是远程构建的时候
When you run a build command, the build client looks for a file named .dockerignore
in the root directory of the context. If this file exists, the files and directories that match patterns in the files are removed from the build context before it’s sent to the builder.
如果你有多个 Dockerfile,你可以为每一个 Dockerfile 指定一个 ignore 文件。为了达到这样的目的,我们需要遵循特定的命名规范:" Place your ignore-file in the same directory as the Dockerfile, and prefix the ignore-file with the name of the Dockerfile":
.dockerignore 的忽略规则如下
- .dockerignore 中的每一行表示一条忽略规则
- # 开头的行会被视为注释,不会被处理
- “the root of the context is considered to be both the working and the root directory” 因此 .dockerignore 中
/foo/bar
andfoo/bar
是等效的,都是以构建上下文的根路径开始 - 你可以使用
!
来排除某些文件,即使他们匹配 .dockerignore 文件中的规则。 *
:匹配任意数量的字符(包括零个)。?
:匹配单个字符。**
:匹配任意数量的目录(包括零个)。**/*.go
会排除 build context 中所有 .go 结尾的文件!
:用于排除特定文件或目录,即使它们被之前的模式匹配。