干货总结!Dockerfile编写优秀实践

本文介绍了Dockerfile中的优秀实践,包括善用.dockerignore文件减小镜像体积,采用多阶段构建提高镜像效率,合理利用缓存加速构建,选择体积小的镜像,以及推荐使用execform以增强信号传递和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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":

image-20240206164700081

.dockerignore 的忽略规则如下

  • .dockerignore 中的每一行表示一条忽略规则
  • # 开头的行会被视为注释,不会被处理
  • “the root of the context is considered to be both the working and the root directory” 因此 .dockerignore 中 /foo/bar and foo/bar 是等效的,都是以构建上下文的根路径开始
  • 你可以使用 ! 来排除某些文件,即使他们匹配 .dockerignore 文件中的规则。
  • *:匹配任意数量的字符(包括零个)。
  • ?:匹配单个字符。
  • **:匹配任意数量的目录(包括零个)。 **/*.go 会排除 build context 中所有 .go 结尾的文件
  • !:用于排除特定文件或目录,即使它们被之前的模式匹配。

image-20240206190057649

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罅隙`

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值