If this project helps you build better Docker images, consider sponsoring me on GitHub:
Your support helps me maintain and improve this project. Every contribution counts! π
A CLI tool that analyzes Dockerfiles to identify inefficiencies in layer structure, caching, and image size. Helps you build smaller, faster Docker images with better cache utilization.
- π Dockerfile Parser - Parses Dockerfiles with multi-stage build detection
- π Layer Size Analysis - Analyzes layer sizes from
docker historyor estimates from Dockerfile - β‘ Cache Optimization Rules - Applies best practices to identify caching opportunities
- π― Smart Recommendations - Actionable suggestions with severity levels
- π CLI with Diff Output - Easy-to-use command-line interface
- π§ͺ Test Coverage - Comprehensive test suite
npm install -g docker-layer-optimizernpm install docker-layer-optimizer
npx docker-layer-opt analyze Dockerfiledocker-layer-opt analyze Dockerfiledocker-layer-opt analyze Dockerfile --estimatedocker-layer-opt analyze Dockerfile --format json# Returns exit code 2 if high-severity issues are found
docker-layer-opt analyze Dockerfileπ³ Docker Layer Optimization Report
File: /path/to/Dockerfile
π Summary:
Instructions: 8
Stages: 1
Multi-stage: No
Issues: 2 high, 1 medium, 1 low
β οΈ Issues Found (4):
π΄ [HIGH] Combine package installations
Package installation commands should be combined into a single RUN layer
π‘ Combine all apt-get/yum/apk add commands into one RUN instruction
Lines affected:
- Line 3: RUN apt-get install -y curl
- Line 4: RUN apt-get install -y git
π΄ [HIGH] Order COPY by change frequency
Copy files that change less frequently before files that change often
π‘ Move package.json COPY before source file COPY to leverage layer caching
Lines affected:
- Line 5: COPY . .
π‘ [MEDIUM] Clean up package caches
Package managers leave cache files that increase image size
π‘ Add cleanup commands after installations (e.g., apt-get clean)
Lines affected:
- Line 3: RUN apt-get install -y curl
π΅ [LOW] Prefer COPY over ADD
ADD has automatic features that can be surprising
π‘ Use COPY for local files. Only use ADD for URL downloads
Lines affected:
- Line 6: ADD dist /app
The tool analyzes your Dockerfile against these best practices:
- Package Installation Combined - Multiple package install commands should be combined
- Copy Order - Less frequently changed files (package.json) should be copied before source code
- Cleanup Package Caches - Remove package manager caches after installation
- Multi-Stage Builds - Use multi-stage builds to exclude build tools from final image
- Layer Order - Combine update and install commands to prevent stale caches
- Update/Install Mismatch - Keep package updates paired with installations
- COPY vs ADD - Prefer explicit COPY over feature-heavy ADD
- NPM Cache Mounts - Consider BuildKit cache mounts for npm installs
- Wildcard Copies - Avoid wildcard patterns in COPY commands
- Dockerignore - Use .dockerignore to exclude unnecessary files
const { Analyzer } = require('docker-layer-optimizer');
async function analyze() {
const analyzer = new Analyzer('./Dockerfile');
await analyzer.load();
const results = analyzer.analyze({ estimateSizes: true });
console.log(`Found ${results.cacheIssues.length} issues`);
console.log(`Total layers: ${results.summary.totalInstructions}`);
const suggestions = analyzer.generateSuggestions();
for (const suggestion of suggestions) {
console.log(`[${suggestion.severity}] ${suggestion.title}`);
}
}
analyze();0- Success, no issues found1- Error occurred2- High-severity issues found (useful for CI)
name: Dockerfile Analysis
on: [push, pull_request]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npx docker-layer-opt analyze Dockerfiledockerfile-analysis:
stage: test
script:
- npx docker-layer-opt analyze Dockerfile
allow_failure: trueFor actual layer size analysis, you can combine with docker history:
# Build image first
docker build -t myapp:latest .
# Export history
docker history --no-trunc --format "{{.ID}}|{{.Size}}|{{.CreatedBy}}" myapp:latest > history.txt
# Analyze (programmatic)
const { Analyzer } = require('docker-layer-optimizer');
const analyzer = new Analyzer('./Dockerfile');
analyzer.load();
const layerAnalysis = analyzer.analyzeFromHistory(historyContent);
console.log(`Total size: ${layerAnalysis.formattedTotalSize}`);- Parse - Reads and parses your Dockerfile, detecting stages and instructions
- Analyze - Applies optimization rules to identify issues
- Estimate - Heuristically estimates layer sizes (optional)
- Report - Provides actionable recommendations with severity levels
Contributions are welcome! Please feel free to submit issues or pull requests.
MIT License - see LICENSE file for details
Built with β€οΈ to help the DevOps community build better Docker images.