接手项目发现Dockerfile含RUN true命令,其作用是什么?
Dockerfile中
RUN true的作用解析 我接手项目时,发现Dockerfile里存在单独的RUN true命令,示例如下:
FROM xxx RUN xxx RUN true RUN xxx
我感觉这个命令似乎没什么意义,但不确定是否存在其他用途。
在容器构建最佳实践文档里,也有包含RUN true的示例:
RUN true \ && dnf install -y --setopt=tsflags=nodocs \ httpd vim \ && systemctl enable httpd \ && dnf clean all \ && true
测试验证
我针对缓存复用的疑问做了测试:
测试1:构建失败场景
Dockerfile内容:
FROM centos:7.9.2009 RUN yum install tmux -y RUN yum install not_exists -y
构建日志片段:
Sending build context to Docker daemon 2.048kB Step 1/3 : FROM centos:7.9.2009 ---> eeb6ee3f44bd Step 2/3 : RUN yum install tmux -y ---> Running in 6c6e29ea9f2c ...omit... Complete! Removing intermediate container 6c6e29ea9f2c ---> 7c796c2b5260 Step 3/3 : RUN yum install not_exists -y ---> Running in e4b7096cc42b ...omit... No package not_exists available. Error: Nothing to do The command '/bin/sh -c yum install not_exists -y' returned a non-zero code: 1
测试2:构建成功场景
修改后的Dockerfile:
FROM centos:7.9.2009 RUN yum install tmux -y RUN yum install tree -y
构建日志片段:
Sending build context to Docker daemon 2.048kB Step 1/3 : FROM centos:7.9.2009 ---> eeb6ee3f44bd Step 2/3 : RUN yum install tmux -y ---> Using cache ---> 7c796c2b5260 Step 3/3 : RUN yum install tree -y ---> Running in 180b32cb44f3 ...omit... Installed: tree.x86_64 0:1.6.0-10.el7 Complete! Removing intermediate container 180b32cb44f3 ---> 4e905ed25cc2 Successfully built 4e905ed25cc2 Successfully tagged test:v0
从日志可以看到,即使没有RUN true,第一个RUN层的缓存依然能被正常复用,说明单独的RUN true对缓存逻辑没有影响。
实际用途分析
- 链式命令中的
RUN true:文档示例里开头的RUN true是为了方便后续扩展命令——如果要新增步骤,直接在后面加&& 新命令即可,不用修改前面的命令行;结尾的&& true则是强制让整个RUN命令的退出码为0,避免某些命令(如清理缓存的命令)意外返回非0值导致构建失败。不过这种用法并不推荐,更稳妥的方式是确保每个命令本身能正确返回0。 - 单独的
RUN true:确实没有实际功能,既不会修改镜像内容,也不影响构建流程或缓存,大概率是调试遗留的冗余代码,或者误操作添加的,可以安全删除。
内容的提问来源于stack exchange,提问作者reflux
相关产品推荐
相关产品推荐

