本文介绍了有没有办法对 Dockerfile 进行 lint?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个 Dockerfile 写有错误例如:

If a Dockerfile is written with mistakes for example:

CMD ["service", "--config", "/etc/service.conf](缺少引号)

有没有办法在构建之前对其进行 lint 检测以检测此类错误?

Is there a way to lint it to detect such mistake before building?

推荐答案

试试:

  • Either the Haskell Dockerfile Linter ("hadolint"), also available online. hadolint parses the Dockerfile into an AST and performs checking and validation based on best practice Docker images rules. It also uses Shellcheck to lint the Bash code on RUN commands.
  • Or dockerlinter (node.js-based).

我使用 RUNADDENVCMD.dockerlinter 很聪明地将相同的违规行为分组在一起,但它无法像 hadolinter 那样彻底检查,这可能是由于缺少 Shellcheck静态分析 Bash 代码.

I've performed a simple test against of a simple Docker file with RUN, ADD, ENV and CMD. dockerlinter was smart about grouping the same violation of rules together but it was not able to inspect as thorough as hadolinter possibly due to the lack of Shellcheck to statically analyze the Bash code.

虽然 dockerlinter 在它可以 lint 的范围内不足,但它似乎确实更容易安装.npm install -g dockerlinter 可以,而编译 hadolinter 需要一个 Haskell 编译器和构建环境,需要永远编译.

Although dockerlinter falls short in the scope it can lint, it does seem to be much easier to install. npm install -g dockerlinter will do, while compiling hadolinter requires a Haskell compiler and build environment that takes forever to compile.

$ hadolint ./api/Dockerfile
L9 SC2046 Quote this to prevent word splitting.
L11 SC2046 Quote this to prevent word splitting.
L8 DL3020 Use COPY instead of ADD for files and folders
L10 DL3020 Use COPY instead of ADD for files and folders
L13 DL3020 Use COPY instead of ADD for files and folders
L18 DL3020 Use COPY instead of ADD for files and folders
L21 DL3020 Use COPY instead of ADD for files and folders
L6 DL3008 Pin versions in apt get install. Instead of `apt-get install <package>` use `apt-get install <package>=<version>`
L6 DL3009 Delete the apt-get lists after installing something
L6 DL3015 Avoid additional packages by specifying `--no-install-recommends`

$ dockerlint ./api/Dockerfile
WARN:  ADD instruction used instead of COPY on line 8, 10, 13, 18, 21
ERROR: ./api/Dockerfile failed.

2018 年更新.由于 hadolint 现在有官方的 Docker 仓库,你可以快速获取可执行文件:

Update in 2018. Since hadolint has the official Docker repository now, you can get the executable quickly:

id=$(docker create hadolint/hadolint:latest)
docker cp "$id":/bin/hadolint .
docker rm "$id"

这是一个静态编译的可执行文件(根据 ldd hadolint),因此无论安装的库如何,它都应该运行.关于如何构建可执行文件的参考:https://github.com/hadolint/hadolint/blob/master/docker/Dockerfile.

This is a statically compiled executable (according to ldd hadolint), so it should run regardless of installed libraries. A reference on how the executable is built: https://github.com/hadolint/hadolint/blob/master/docker/Dockerfile.

这篇关于有没有办法对 Dockerfile 进行 lint?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 16:43