Skip to content

vidun-upek/DockLens

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

22 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

DockerLens

DockerLens is a CLI-based Dockerfile linter (dockerfile-lint-plus) that helps developers identify security risks, inefficiencies, performance issues, and maintainability problems in Dockerfiles before they reach production.

Think of it like ESLint for Dockerfiles โ€” it checks your Docker configuration against best practices and best practices.


๐Ÿ“‹ What This Project Does

dockerfile-lint-plus analyzes your Dockerfiles and reports violations based on 7 core rules:

Rule Type Purpose
no-latest-tag โŒ Error Base images must specify a version tag (not :latest)
require-tagged-base-image โŒ Error Base images require an explicit tag
no-curl-bash โŒ Error Prevent piping remote scripts directly into bash
copy-deps-before-source โš ๏ธ Warning Copy dependency files before copying all source code
require-non-root-user โš ๏ธ Warning Container should not run as root
prefer-copy-over-add โš ๏ธ Warning Use COPY instead of ADD when possible
require-explicit-cmd-or-entrypoint โš ๏ธ Warning Every image should have CMD or ENTRYPOINT

๐Ÿ› ๏ธ How It Works

The Processing Pipeline

Dockerfile Input
      โ†“
[1] Parser - Extract all instructions (FROM, RUN, COPY, etc.)
      โ†“
[2] Rule Engine - Run each of the 7 rules against the instructions
      โ†“
[3] Collector - Gather all violations with line numbers and messages
      โ†“
[4] Formatter - Format output (human-readable or JSON)
      โ†“
Output Results (with exit code for CI/CD)

Code Structure

src/
โ”œโ”€โ”€ cli.ts                    # Main command-line interface
โ”œโ”€โ”€ analyzer/
โ”‚   โ”œโ”€โ”€ parseDockerfile.ts   # Parse Dockerfile into instructions
โ”‚   โ”œโ”€โ”€ runRules.ts          # Execute all rules
โ”‚   โ””โ”€โ”€ resultFormatter.ts   # Format output
โ”œโ”€โ”€ rules/                   # Individual rule implementations
โ”‚   โ”œโ”€โ”€ index.ts             # Rule registry (active rules)
โ”‚   โ”œโ”€โ”€ noLatestTag.ts
โ”‚   โ”œโ”€โ”€ requireTaggedBaseImage.ts
โ”‚   โ”œโ”€โ”€ noCurlBash.ts
โ”‚   โ”œโ”€โ”€ copyDepsBeforeSource.ts
โ”‚   โ”œโ”€โ”€ requireNonRootUser.ts
โ”‚   โ”œโ”€โ”€ preferCopyOverAdd.ts
โ”‚   โ”œโ”€โ”€ requireExplicitCmdOrEntrypoint.ts
โ”‚   โ””โ”€โ”€ _helpers.ts          # Shared helper functions
โ”œโ”€โ”€ types/
โ”‚   โ”œโ”€โ”€ DockerInstruction.ts # Parsed instruction data
โ”‚   โ”œโ”€โ”€ Finding.ts           # Violation/finding data
โ”‚   โ””โ”€โ”€ Rule.ts              # Rule interface
โ”œโ”€โ”€ config/
โ”‚   โ””โ”€โ”€ defaultRules.ts      # Default rule configuration
โ””โ”€โ”€ utils/
    โ”œโ”€โ”€ config.ts            # Config loading/merging
    โ”œโ”€โ”€ file.ts              # File system utilities
    โ”œโ”€โ”€ logger.ts            # Logging utilities
    โ””โ”€โ”€ patterns.ts          # Regex patterns

How Each Rule Works

Example: no-latest-tag Rule

// 1. Find all FROM instructions
// 2. Check if any use :latest tag
// 3. If found, create a Finding with:
//    - Line number where violation is
//    - Clear message explaining the problem
//    - Suggestion on how to fix it
// 4. Return findings to be displayed to user

๐Ÿš€ How to Use

Installation

Install the CLI tool dockerfile-lint-plus globally:

npm install -g dockerfile-lint-plus

Or use directly without installing:

npx dockerfile-lint-plus analyze Dockerfile

Commands

1. Analyze a Dockerfile

dockerfile-lint-plus analyze Dockerfile

Output:

[ERROR] no-latest-tag
  Line 1
  Base image uses the latest tag, which is not reproducible.
  FROM node:latest
  Suggestion: Pin the image to an explicit version such as node:20-alpine.

[WARNING] require-non-root-user
  Line 5
  No USER instruction found. Container may run as root.
  CMD ["npm", "start"]
  Suggestion: Add a non-root USER instruction.

Total findings: 2

2. List All Available Rules

dockerfile-lint-plus rules

Output:

no-latest-tag [error] - Avoid latest tags
require-tagged-base-image [error] - Require tagged base image
no-curl-bash [error] - Do not pipe curl or wget into shell
copy-deps-before-source [warning] - Copy dependency files first
require-non-root-user [warning] - Require non-root user
prefer-copy-over-add [warning] - Prefer COPY over ADD
require-explicit-cmd-or-entrypoint [warning] - Require CMD or ENTRYPOINT

3. Get Help on a Specific Rule

dockerfile-lint-plus explain no-latest-tag

Output:

no-latest-tag

Avoid latest tags
Severity: error
Category: base-image

What it checks:
Flags FROM instructions that use the latest tag.

Why it matters:
latest changes over time and makes builds unpredictable.

Suggestion:
Use a pinned version such as node:20-alpine.

4. Initialize a Config File

dockerfile-lint-plus init

Creates dockerfile-lint-plus.config.json with default configuration that you can customize.

Command Options

dockerfile-lint-plus analyze Dockerfile [options]

Options:
  -f, --format <format>    Output format: 'stylish' (default) or 'json'
  -c, --config <path>      Path to config file
  -r, --recursive          Scan all Dockerfiles in a directory
  --strict                 Fail on warnings too (not just errors)

Examples

Analyze with JSON output:

dockerfile-lint-plus analyze Dockerfile --format json

Analyze with custom config:

dockerfile-lint-plus analyze Dockerfile --config my-rules.json

Fail on both errors and warnings:

dockerfile-lint-plus analyze Dockerfile --strict

Use in CI/CD:

dockerfile-lint-plus analyze Dockerfile
if [ $? -ne 0 ]; then
  echo "Dockerfile failed linting"
  exit 1
fi

๐Ÿงช Testing

The project includes comprehensive tests covering:

  • Unit Tests โ€” Individual rule testing (each rule is tested)
  • Integration Tests โ€” Full analyzer testing with multiple rules
  • Edge Cases โ€” Empty files, comments, multi-stage builds, etc.
  • Parser Tests โ€” Dockerfile parsing with line continuations
  • JSON Output Validation โ€” Correct JSON format

Run Tests

npm test

Test Coverage

  • 82 tests all passing โœ…
  • 12 test files covering different aspects
  • Edge cases like empty Dockerfiles, comments-only files
  • Multi-stage builds tested for correctness

Test files:

tests/
โ”œโ”€โ”€ analyzer/
โ”‚   โ”œโ”€โ”€ parseDockerfile.test.ts     # Parser tests
โ”‚   โ”œโ”€โ”€ runRules.test.ts            # Rule engine tests
โ”‚   โ””โ”€โ”€ jsonOutputValidation.test.ts # Output format tests
โ”œโ”€โ”€ rules/
โ”‚   โ”œโ”€โ”€ noLatestTag.test.ts
โ”‚   โ”œโ”€โ”€ requireTaggedBaseImage.test.ts
โ”‚   โ”œโ”€โ”€ noCurlBash.test.ts
โ”‚   โ”œโ”€โ”€ copyDepsBeforeSource.test.ts
โ”‚   โ”œโ”€โ”€ requireNonRootUser.test.ts
โ”‚   โ”œโ”€โ”€ preferCopyOverAdd.test.ts
โ”‚   โ””โ”€โ”€ requireExplicitCmdOrEntrypoint.test.ts
โ”œโ”€โ”€ edge-cases/
โ”‚   โ””โ”€โ”€ edgeCases.test.ts           # Unusual input handling
โ””โ”€โ”€ integration/
    โ””โ”€โ”€ fullEngine.test.ts          # Full pipeline tests

Test Execution

npm test                    # Run all tests
npm run build              # Compile TypeScript
npm run dev                # Run with live reloading (development)
npm run lint:sample        # Test against sample Dockerfile

๐Ÿ”ฎ Future Implementations

The following features are planned for future versions:

Phase 2: Advanced Features

  • Recursive scanning โ€” Scan entire directories for all Dockerfiles
  • JSON output โ€” Machine-readable output for CI/CD integration
  • Dockerfile quality score โ€” Rate Dockerfile quality 0-100
  • GitHub Action โ€” Use as a GitHub Action in workflows
  • Configuration profiles โ€” Preset configs for different use cases

Phase 3: Enhancement & Optimization

  • More rules โ€” Additional best-practice rules for security and performance
  • Custom rules โ€” Allow users to write their own rules
  • Markdown reports โ€” Generate detailed HTML/Markdown reports
  • Quick fixes โ€” Automatic suggestion-based fixes
  • Multi-format support โ€” Docker Compose files support
  • Performance metrics โ€” Analyze build layer sizes and caching efficiency

Phase 4: Integration

  • GitLab CI support โ€” Integration templates
  • pre-commit hooks โ€” Use as git pre-commit hook
  • Docker plug-in โ€” Embedded in Docker CLI
  • IDE extensions โ€” VSCode extension for real-time linting

๐Ÿ“ฆ Configuration

Create a dockerfile-lint-plus.config.json file to customize rules:

{
  "failOn": ["error"],
  "format": "stylish",
  "rules": {
    "no-latest-tag": "error",
    "require-tagged-base-image": "error",
    "no-curl-bash": "error",
    "copy-deps-before-source": "warning",
    "require-non-root-user": "warning",
    "prefer-copy-over-add": "warning",
    "require-explicit-cmd-or-entrypoint": "warning"
  }
}

Configuration Options

  • failOn โ€” Which severities cause exit code 1 (array of 'error', 'warning', 'info')
  • format โ€” Output format ('stylish' for humans, 'json' for machines)
  • rules โ€” Set severity per rule or 'off' to disable

๐Ÿ’ก Use Cases

1. Local Development

dockerfile-lint-plus analyze Dockerfile

Check your Dockerfile before committing.

2. CI/CD Integration

# GitHub Actions example
- name: Lint Dockerfile
  run: dockerfile-lint-plus analyze Dockerfile --strict

3. Pre-commit Hook

#!/bin/bash
dockerfile-lint-plus analyze Dockerfile
[ $? -eq 0 ] && git add Dockerfile

4. Production Deployment

dockerfile-lint-plus analyze Dockerfile --format json > report.json
if grep -q '"severity": "error"' report.json; then
  exit 1
fi

๐Ÿ”ง Development

Setup

git clone <repo>
cd dockerfile-lint-plus
npm install
npm run build
npm test

Project Structure

  • Source โ€” TypeScript in src/
  • Tests โ€” Vitest in tests/
  • Build output โ€” Compiled JavaScript in dist/
  • Config โ€” TypeScript compiler in tsconfig.json

Key Dependencies

  • commander โ€” CLI argument parsing
  • chalk โ€” Colored terminal output
  • typescript โ€” Type-safe JavaScript

๐Ÿ“„ Project Information

  • Project Name โ€” DockerLens
  • CLI Package Name โ€” dockerfile-lint-plus
  • Version โ€” 1.0.0
  • License โ€” MIT
  • Author โ€” DockerLens Contributors
  • Repository โ€” GitHub
  • NPM Package โ€” Available as dockerfile-lint-plus

๐ŸŽฏ Quick Start (5 Minutes)

  1. Install DockerLens

    npm install -g dockerfile-lint-plus
  2. Check your Dockerfile with DockerLens

    dockerfile-lint-plus analyze Dockerfile
  3. View violations

    [ERROR] no-latest-tag - Line 1
    [WARNING] require-non-root-user - Line 5
    Total findings: 2
    
  4. Get help on a rule

    dockerfile-lint-plus explain no-latest-tag
  5. Fix violations based on suggestions

Done! Your Dockerfile is now more secure and reproducible. โœ…


๐Ÿ’ฌ Support

For issues, feature requests, or contributions, please visit the DockerLens repository.


DockerLens โ€” Made By Vidun Shanuka _ Full Stack / ML Developer IN SRI LANKA

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors