Dockerfile Security Best Practices and Hadolint Usage Guide

Implementing security best practices in your Dockerfiles

Featured image



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:

1. Use Official Base Images
  • 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-work

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:

1. **DL3007**: Using 'latest' tag
  • # Dockerfile
    # Bad
    FROM ubuntu:latest
  • # Dockerfile
    # Good
    FROM ubuntu:20.04
2. **DL4000**: Deprecated MAINTAINER
  • # Dockerfile
    # Bad
    MAINTAINER somaz@gmail.com
  • # Dockerfile
    # Good
    LABEL maintainer="somaz@gmail.com"
3. **DL3009**: Delete apt-get lists
  • # 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:



References