Docker best practices: linter for Dockerfile

Published 26 Oct 2020 - 3 min read

In software development, best practices are the way to go. You must do the same while developing the infrastructure code! In this post, we’ll go through how a linter can increase your productivity, how to use it with a Dockerfile, and how to implement it in a CI pipeline.

What is a linter? Why we need it?

According to Wikipedia, a linter is a static code analysis tool used to flag programming errors, bugs, stylistic errors, and suspicious constructs. As a static code analysis tool, linters can’t be used to detect compiling time errors but are very useful in finding typos and syntax errors. Using a linter will allow you to detect errors early, fixing them faster, and reduce bugs before execution.



The tool we will use is called Hadolint and as you can recall from the name is a linter. It’s built to help you follow the docker best practices, and it also uses ShellCheck to inspect your RUN instructions.

How to set it up

It very easy to use both in a local environment and CI, you can find the integration docs here.

If you are a VS Code user, there is the Hadolint extension. If you want to use it directly in Github, there is theHadolint Github action.

Define custom rules

If you don’t want to follow all the rules defined by Hadolint, you can easily deactivate some of them. You only need to create a file called ~/.config/hadolint.yaml, a full list of rules here. An example of a custom rule file is:

  - DL3000
  - SC1010

How to run it in CI

To enforce this best practice, you can add a test in your Docker deployment pipeline. We can implement it in the Ansible pipelinewe used to execute unit tests for Docker.

Let’s add a new role called “Run hadolint on Dockerfile”:

- name: Run hadolint on Dockerfile
  shell: |
    docker run --rm -i \
      -v "{{ role_path }}/files/hadolint.yaml":/root/.config/hadolint.yaml hadolint/hadolint \
      < {{ dockerfile_name }}

In this example we directly run the official hadolint docker image against the Dockerfile. I’m mounting the hadolint.yaml file to use my custom rules configuration.

This is it!

Now you should know all you need to use Hadolint for your Dockerfile.

Reach me on Twitter @gasparevitta and let me know your thoughts!

You can find the code snippets on Github.

Get emails about new articles!

I write about Continuous Integration, Continuous Deployment, testing, and other cool stuff.
Gaspare Vitta on Twitter