Saltar al contenido

Hadolint: Mejores prácticas para tus Dockerfiles en 3 modelos diferentes

Introducción

Hadolint es una herramienta de código abierto que te ayudará a asegurar que todos los Dockerfiles que crees sigan todas las mejores prácticas de Dockerfile disponibles de manera automatizada. Hadolint, como el número ya sugiere, es una herramienta linter y, debido a eso, también puede ayudarte a enseñarte todas estas mejores prácticas al crear Dockerfiles por ti mismo. Ya hablamos sobre la optimización del tamaño de la imagen del contenedor, pero hoy vamos a intentar cubrirlo más a fondo.

Hadolint es una herramienta más pequeña escrita en Haskell que analiza el Dockerfile en un AST y realiza reglas sobre el AST. Se apoya en ShellCheck para analizar el código Bash dentro de las instrucciones RUN, como se muestra en la imagen a continuación:

Hay varias maneras de ejecutar la herramienta, dependiendo de lo que intentes lograr, y hablaremos un poco sobre las diferentes opciones.

Ejecutándolo como una herramienta independiente

Esta es la primera forma en que podemos ejecutarlo como una herramienta independiente completa que puedes descargar desde aquí, y necesitará hacer el siguiente comando.

 hadolint <Dockerfile path>

Se ejecutará contra él y mostrará cualquier problema que se encuentre, como puedes ver en la imagen a continuación:

Ejecución de Hadolint

Para cada uno de los problemas encontrados, mostrará la línea donde se detecta el problema, el código de la verificación de mejores prácticas de Dockerfile que se está realizando (DL3020), la severidad de la verificación (error, advertencia, información, etc.), y la descripción del problema.

Para ver todas las reglas que se están ejecutando, puedes revisarlas en el Wiki de GitHub, y todas ellas están basadas en las mejores prácticas de Dockerfile publicadas directamente por Docker en su página web oficial aquí.

Para cada una de ellas, encontrarás una página wiki específica con toda la información que necesitas sobre el problema y por qué esto es algo que debería cambiarse, y cómo debería cambiarse, como puedes ver en la imagen a continuación:

Página del Wiki de Hadolint en GitHub

Capacidad de Ignorar Reglas

Puedes ignorar algunas reglas si no quieres que se apliquen porque hay algunos falsos positivos o simplemente porque las verificaciones no están alineadas con las mejores prácticas de Dockerfile utilizadas en tu organización. Para hacer eso, puedes incluir un parámetro —ignore con la regla a aplicar:

 hadolint --ignore DL3003 --ignore DL3006 <Dockerfile>

Ejecutándolo como Contenedor Docker

Además, la herramienta está disponible como un contenedor Docker en los siguientes repositorios:

docker pull hadolint/hadolint
# O
docker pull ghcr.io/hadolint/hadolint

Y esto te ayudará a introducirlo en tu Integración Continua y Despliegue Continuo o simplemente para ser usado en tu entorno local si prefieres no instalar software localmente.

Ejecutándolo dentro de VS Code

Como muchos linters, es esencial tenerlo cerca de tu entorno de desarrollo; esta vez no es diferente. Nos gustaría tener las mejores prácticas de Dockerfile relativas al editor mientras estamos escribiendo por dos razones principales:

  • Tan pronto como obtengas el problema, lo solucionarás más rápido para que el código siempre tenga mejor calidad
  • Tan pronto como sepas del problema, no lo volverás a cometer en desarrollos nuevos.

Tendrás Hadolint como parte de las Extensiones: Marketplace, y puedes instalarlo:

Extensión de Hadolint para VS Code


Una vez que hayas hecho eso, cada vez que abras un Dockerfile, validarás contra todas estas mejores prácticas de Dockerfile, y mostrará los problemas detectados en la vista de Problemas, como puedes ver en la imagen a continuación:

Ejecución de la Extensión de Hadolint para VS Code

Y esos problemas serán reevaluados tan pronto como modifiques y guardes el Dockerfile nuevamente, por lo que siempre verás la versión en vivo del problema detectado contra las mejores prácticas de Dockerfile.

Hadolint: Best Practices for your Dockerfiles In 3 Different Models

Introduction

Hadolint is an open-source tool that will help you ensure that all the Dockerfiles you create follow all the Dockerfile best practices available in an automated way. Hadolint, as the number already suggested, is a linter tool and, because of that, can also help you to teach you all these best practices when creating Dockerfiles yourself. We already talked about it the optimization of container image size, but today we are going to try to cover it more in-depth.

Hadolint is a smaller tool written in Haskell that parses the Dockerfile into an AST and performs rules on top of the AST. It stands on the shoulders of ShellCheck to lint the Bash code inside RUN instructions, as shown in the picture below:

There are several ways to run the tool, depending on what you try to achieve, and we will talk a little bit about the different options.

Running it as a standalone tool

This is the first way we can run it as a complete standalone tool that you can download from here , and it will need to do the following command.

 hadolint <Dockerfile path>

It will run against it and show any issue that is found, as you can see in the picture below:

Hadolint execution

For each of the issues found, it will show the line where the problem is detected, the code of the Dockerfile best practice check that is being performed (DL3020), the severity of the check (error, warn, info, and so on), and the description of the issue.

To see all the rules that are being executed, you can check them in the GitHub Wiki , and all of them are based on the Dockerfile best practices published directly from Docker on its official web page here.

For each of them, you will find a specific wiki page with all the information you need about the issue and why this is something that should be changed, and how it should be changed, as you can see in the picture below:

Hadolint GitHub Wiki page

Ignore Rules Capability

You can ignore some rules if you don’t want them to be applied because there are some false-positive or just because the checks are not aligned with the Dockerfile best practices used in your organization. To do that, you can include an —ignore parameter with the rule to be applied:

 hadolint --ignore DL3003 --ignore DL3006 <Dockerfile>

Running it as Docker Container

Also, the tool is available as a Docker container in the following repos:

docker pull hadolint/hadolint
# OR
docker pull ghcr.io/hadolint/hadolint

And this will help you to be introduced to your Continuous Integration and Continuous Deployment or just to be used in your local environment if you prefer not to install software locally.

 Running it inside VS Code

Like many linters, it is essential to have it close to your development environment; this time is nothing different. We would like to have the Dockerfile best practice relative to the editor while we are typing for two main reasons:

  • As soon as you get the issue, you will fix it faster so the code always will have better quality
  • As soon as you know of the issue, you will not make it again in newer developments.

You will have a Hadolint as part of the Extensions: Marketplace, and you can install it:

Hadolint VS Code Extension


Once you have that done, each time you open a Dockerfile, you will validate against all these Dockerfile best practices, and it will show the issues detected in the Problems view, as you can see in the picture below:

Hadolint: VS Code Extension Execution

And those issues will be re-evaluated as soon as you modify and save the Dockerfile again, so you will always see the live version of the problem detected against the Dockerfile best practices.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *