How to Fix Hadolint Dockerfile Lint Error
In this tutorial, you'll learn about How to Fix Hadolint Dockerfile Lint Error. We cover key concepts, practical examples, and best practices.
Hadolint returns multiple lint errors when analyzing a Dockerfile, such as DL3008: Pin versions in apt-get install or DL3018: Pin package versions in apk add — the Dockerfile violates best practice rules for building container images.
The Problem
$ hadolint Dockerfile
Dockerfile:5 DL3008 error: Pin versions in apt-get install
Dockerfile:7 DL3018 error: Pin versions in apk add
Dockerfile:12 DL4006 warning: Use COPY instead of ADD
Step-by-Step Fix
Step 1: Pin package versions
# Bad
RUN apt-get update && apt-get install -y curl
# Good
RUN apt-get update && apt-get install -y curl=7.88.1-10+deb12u1
Step 2: Use COPY instead of ADD
# Bad
ADD ./app /app
# Good
COPY ./app /app
Step 3: Avoid sudo in RUN commands
# Bad
RUN sudo apt-get install -y curl
# Good
RUN apt-get install -y curl
Step 4: Remove apt-get cache
# Bad
RUN apt-get update && apt-get install -y curl
# Good
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
Step 5: Use WORKDIR instead of cd
# Bad
RUN cd /app && npm install
# Good
WORKDIR /app
RUN npm install
Step 6: Configure hadolint
# .hadolint.yaml
failure-threshold: warning
override:
- image: node:20-alpine
rules:
- DL3008 = false # Skip version pinning for base image
Step 7: Run with ignore
hadolint --ignore DL3008 Dockerfile
Prevention Tips
- Install hadolint as a pre-commit hook
- Pin all package versions in package managers
- Always use
COPYinstead ofADDfor local files - Run
hadolint Dockerfilein CI/CD pipelines
Common Mistakes with dockerfile
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world HADOLINT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro