上一节学习了一些实际工作中编写Dockerfile的实践经验,本节给大家推荐一款Dockerfile的代码规范检查工具hadolint。 hadolint的项目地址是https://github.com/hadolint/hadolint,它是一个智能的Dockerfile linter,帮助检查Dockerfile的编写是否满足最佳实践的规范。hadolint将Dockerfile解析为一个AST抽象语法树,并在AST之上执行规则。它是基于ShellCheck检查RUN指令中的Bash代码的。

hadolint

hadolint在各个平台的可执行文件可以在https://github.com/hadolint/hadolint/releases下载到。在MacOS上可以使用brew直接安装:

1brew install hadolint

hadolint的使用也十分简单,直接在本地运行检查Dockerfile即可:

1hadolint Dockerfile

下面是对https://github.com/docker-library/redis/blob/a73df6df17be8294a63e6914fca028984772179a/6.0/alpine/Dockerfile进行检查的结果:

1hadolint Dockerfile
2Dockerfile:7 DL3018 warning: Pin versions in apk add. Instead of `apk add <package>` use `apk add <package>=<version>`
3Dockerfile:17 DL3018 warning: Pin versions in apk add. Instead of `apk add <package>` use `apk add <package>=<version>`
4Dockerfile:17 DL4006 warning: Set the SHELL option -o pipefail before RUN with a pipe in it. If you are using /bin/sh in an alpine image or if your shell is symlinked to busybox then consider explicitly setting your SHELL to /bin/ash, or disable this check
5Dockerfile:17 DL3019 info: Use the `--no-cache` switch to avoid the need to use `--update` and remove `/var/cache/apk/*` when done installing packages
6Dockerfile:17 SC2086 info: Double quote to prevent globbing and word splitting.
7Dockerfile:17 DL3047 info: Avoid use of wget without progress bar. Use `wget --progress=dot:giga <url>`.Or consider using `-q` or `-nv` (shorthands for `--quiet` or `--no-verbose`).
8Dockerfile:94 DL3059 info: Multiple consecutive `RUN` instructions. Consider consolidation.

可以看到它按行号和违反的规则号给出了具体的信息。hadolint的文档https://github.com/hadolint/hadolint中有它当前支持的各个检查规则的详细信息,以及如何配置忽略规则等更多用法。

另外在VSCode上也有hadolint的扩展,本机安装完hadolint的可执行文件后,vscode里装上这个扩展就可以直接使用。

hadolint-vscode.png

可以借助hadolint来让一个团队内部编写的Dockerfile更加一致和规范。

参考