2 min to read
Dockerfile Security Best Practices and Hadolint Usage Guide
Implementing security best practices in your Dockerfiles

Overview
Today, we’ll explore Dockerfile security best practices and learn how to use Hadolint for identifying potential security issues.
Dockerfile Security Best Practices
Let’s start with a basic Dockerfile:
Key Security Practices:
- Ensure stability and security
- Avoid using unofficial or custom base images
2. Minimize Image Layers
- Reduce image size and build time
- Avoid unnecessary layers
3. Remove Unnecessary Packages
- Reduce attack surface
- Avoid vulnerabilities
7. Pin Software Versions
- Ensure reproducibility
- Avoid breaking changes
8. Implement Resource Limits
- Prevent resource abuse
- Avoid DoS attacks
9. Use Image Signing
- Ensure image authenticity
- Avoid tampering
10. Implement Health Checks
- Prevent resource abuse
- Avoid DoS attacks
Secure Version:
Hadolint Introduction
Hadolint is a Dockerfile linter that helps build better Docker images by following best practices and avoiding common mistakes.
How Hadolint Works
- Hadolint reads Dockerfile.
- We parse Dockerfile as an abstract syntax tree (AST) to identify each instruction and argument associated with it.
- Each command is then checked against a predefined set of rules covering security, efficiency, and code quality. The rules are part of the Hadolint source code. You can check the list of rules here.
- All rule violations are marked by Hadolint and generate feedback on all detected problems.
Installation:
# Linux and macOS
wget -O /usr/local/bin/hadolint https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64
chmod +x /usr/local/bin/hadolint
# macOS with Homebrew
brew install hadolint
# Windows (PowerShell)
Invoke-WebRequest -Uri https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Windows-x86_64.exe -OutFile 'hadolint.exe'
Common Issues and Fixes:
# Dockerfile
# Bad
FROM ubuntu:latest# Dockerfile
# Good
FROM ubuntu:20.04
# Dockerfile
# Bad
MAINTAINER somaz@gmail.com# Dockerfile
# Good
LABEL maintainer="somaz@gmail.com"
# Dockerfile
# Bad
RUN apt-get update && apt-get install nginx# Dockerfile
# Good
RUN apt-get update && apt-get install nginx && rm -rf /var/lib/apt/lists/*
Practical Example
Let’s analyze a Node.js application Dockerfile:
Key Improvements:
- Pinned package versions
- Consolidated RUN instructions
- Used
--no-install-recommends
- Cleaned up package lists
- Multi-stage build for smaller final image
Comments