docker-optimize

docker-optimize is a command for Claude Code from georgekhananaev/claude-skills-vault. It costs 0 tokens per session (17,600 once invoked), scanned C, original, MIT.

A set of instructions for reviewing and improving Dockerfiles, which describe how to build software containers. It focuses on container image size, build speed, security, and runtime performance.

In plain words
What is it for?
Use it to review Dockerfiles, choose an optimization approach for an application, and receive recommendations with implementation and validation details.
Why use it?
It helps find unnecessary files, slow build steps, and common security or efficiency problems before containers are used in production.

Command for Claude Code

Written for Claude Code: $ARGUMENTS substitution.

Not installable: its command points at a path on the author’s own machine, so it runs nowhere else. The line is /home/appuser/.local.

Good fit Use it to review Dockerfiles, choose an optimization approach for an application, and receive recommendations with implementation and validation details.

Compare 6 commands from other repositories ↓
Install

Getting it into your agent

There is no command for this one: it runs only inside a plugin, and the catalogue could not identify which plugin ships it. The source is linked below.

Made for: Claude Code.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for docker-optimize

README.md
[![agentmods](https://agentmods.dev/badge/commands/georgekhananaev/claude-skills-vault/docker-optimize/github.svg)](https://agentmods.dev/commands/georgekhananaev/claude-skills-vault/docker-optimize)
Your own site
<a href="https://agentmods.dev/commands/georgekhananaev/claude-skills-vault/docker-optimize"><img src="https://agentmods.dev/badge/commands/georgekhananaev/claude-skills-vault/docker-optimize/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for docker-optimize

Your own site · 80×15
<a href="https://agentmods.dev/commands/georgekhananaev/claude-skills-vault/docker-optimize"><img src="https://agentmods.dev/badge/commands/georgekhananaev/claude-skills-vault/docker-optimize.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 0 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 17,600 The whole file, excluding the scripts and references it only reads on demand.
Security scan C 3 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00000 $0.17600
Opus 5 $0.00000 $0.08800
Sonnet 5 $0.00000 $0.03520
Haiku 4.5 $0.00000 $0.01760

Measured 10d ago against content hash 2450cf11f3db, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-10, from the pricing page.

Security

Grade C, and why

docker-optimize scanned grade C with 3 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 10d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Downloads and executes remote codemediumSupply chain

curl | sh runs whatever the server returns today, which is not necessarily what it returned when this was reviewed.

RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin && \

Downgraded: this mod is about security review, or the phrase is quoted, so it is likely naming the pattern rather than instructing it.

Recursive force deletemediumDestructive command

rm -rf with a variable or a broad path is one typo away from removing the wrong tree.

rm -rf /var/lib/apt/lists/*

Downgraded: this mod is about security review, or the phrase is quoted, so it is likely naming the pattern rather than instructing it.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

CMD python -c "import requests; requests.get('http://localhost:8000/health', timeout=5)"
.claude/commands/docker-optimize.md · 2,335 lines

How it starts

The opening of the file, as written. The whole thing — 2,335 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Docker Optimization

You are a Docker optimization expert specializing in creating efficient, secure, and minimal container images. Optimize Dockerfiles for size, build speed, security, and runtime performance while following container best practices.

Context

The user needs to optimize Docker images and containers for production use. Focus on reducing image size, improving build times, implementing security best practices, and ensuring efficient runtime performance.

Requirements

$ARGUMENTS

Instructions

1. Container Optimization Strategy Selection

Choose the right optimization approach based on your application type and requirements:

Optimization Strategy Matrix

from typing import Dict, List, Any, Optional
from dataclasses import dataclass
from pathlib import Path
import docker
import json
import subprocess
import tempfile

@dataclass
class OptimizationRecommendation:
    category: str
    priority: str
    impact: str
    effort: str
    description: str
    implementation: str
    validation: str

class SmartDockerOptimizer:
    def __init__(self):
        self.client = docker.from_env()
        self.optimization_strategies = {
            'web_application': {
                'priorities': ['security', 'size', 'startup_time', 'build_speed'],
                'recommended_base': 'alpine or distroless',
                'patterns': ['multi_stage', 'layer_caching', 'dependency_optimization']
            },
            'microservice': {
                'priorities': ['size', 'startup_time', 'security', 'resource_usage'],
                'recommended_base': 'scratch or distroless',
                'patterns': ['minimal_dependencies', 'static_compilation', 'health_checks']
            },
            'data_processing': {
                'priorities': ['performance', 'resource_usage', 'build_speed', 'size'],
                'recommended_base': 'slim or specific runtime',
                'patterns': ['parallel_processing', 'volume_optimization', 'memory_tuning']
            },
            'machine_learning': {
                'priorities': ['gpu_support', 'model_size', 'inference_speed', 'dependency_mgmt'],
                'recommended_base': 'nvidia/cuda or tensorflow/tensorflow',
                'patterns': ['model_optimization', 'cuda_optimization', 'multi_stage_ml']
            }
        }
    
    def detect_application_type(self, project_path: str) -> str:
        """Automatically detect application type from project structure"""
        path = Path(project_path)
        
        # Check for ML indicators
        ml_indicators = ['requirements.txt', 'environment.yml', 'model.pkl', 'model.h5']
        ml_keywords = ['tensorflow', 'pytorch', 'scikit-learn', 'keras', 'numpy', 'pandas']
        
        if any((path / f).exists() for f in ml_indicators):
            if (path / 'requirements.txt').exists():
                with open(path / 'requirements.txt') as f:
                    content = f.read().lower()
                    if any(keyword in content for keyword in ml_keywords):
                        return 'machine_learning'
        
        # Check for microservice indicators
        if any(f.name in ['go.mod', 'main.go', 'cmd'] for f in path.iterdir()):
            return 'microservice'
        
        # Check for data processing
        data_indicators = ['airflow', 'kafka', 'spark', 'hadoop']
        if any((path / f).exists() for f in ['docker-compose.yml', 'k8s']):
            return 'data_processing'
        
        # Default to web application
        return 'web_application'
    
    def analyze_dockerfile_comprehensively(self, dockerfile_path: str, project_path: str) -> Dict[str, Any]:
        """
        Comprehensive Dockerfile analysis with modern optimization recommendations
        """
        app_type = self.detect_application_type(project_path)
        
        with open(dockerfile_path, 'r') as f:
            content = f.read()
        
        analysis = {
            'application_type': app_type,
            'current_issues': [],
            'optimization_opportunities': [],
            'security_risks': [],
            'performance_improvements': [],
            'size_optimizations': [],
            'build_optimizations': [],
            'recommendations': []
        }
        
        # Comprehensive analysis
        self._analyze_base_image_strategy(content, analysis)
        self._analyze_layer_efficiency(content, analysis)
        self._analyze_security_posture(content, analysis)
        self._analyze_build_performance(content, analysis)
        self._analyze_runtime_optimization(content, analysis)
        self._generate_strategic_recommendations(analysis, app_type)
        
        return analysis
    
    def _analyze_base_image_strategy(self, content: str, analysis: Dict):
        """Analyze base image selection and optimization opportunities"""
        base_image_patterns = {
            'outdated_versions': {
                'pattern': r'FROM\s+([^:]+):(?!latest)([0-9]+\.[0-9]+)(?:\s|$)',
                'severity': 'medium',
                'recommendation': 'Consider updating to latest stable version'
            },
            'latest_tag': {
                'pattern': r'FROM\s+([^:]+):latest',
                'severity': 'high',
                'recommendation': 'Pin to specific version for reproducible builds'
            },
            'large_base_images': {
                'patterns': [
                    r'FROM\s+ubuntu(?!.*slim)',
                    r'FROM\s+centos',
                    r'FROM\s+debian(?!.*slim)',
                    r'FROM\s+node(?!.*alpine)'
                ],
                'severity': 'medium',
                'recommendation': 'Consider using smaller alternatives (alpine, slim, distroless)'
            },
            'missing_multi_stage': {
                'pattern': r'FROM\s+(?!.*AS\s+)',
                'count_threshold': 1,
                'severity': 'low',
                'recommendation': 'Consider multi-stage builds for smaller final images'
            }
        }
        
        # Check for base image optimization opportunities
        for issue_type, config in base_image_patterns.items():
            if 'patterns' in config:
                for pattern in config['patterns']:
                    if re.search(pattern, content, re.IGNORECASE):
                        analysis['size_optimizations'].append({
                            'type': issue_type,
                            'severity': config['severity'],
                            'description': config['recommendation'],
                            'potential_savings': self._estimate_size_savings(issue_type)
                        })
            elif 'pattern' in config:
                matches = re.findall(config['pattern'], content, re.IGNORECASE)
                if matches:
                    analysis['current_issues'].append({
                        'type': issue_type,
                        'severity': config['severity'],
                        'instances': len(matches),
                        'description': config['recommendation']
                    })
    
    def _analyze_layer_efficiency(self, content: str, analysis: Dict):
        """Analyze Docker layer efficiency and caching opportunities"""
        lines = content.split('\n')
        run_commands = [line for line in lines if line.strip().startswith('RUN')]
        
        # Multiple RUN commands analysis
        if len(run_commands) > 3:
            analysis['build_optimizations'].append({
                'type': 'excessive_layers',
                'severity': 'medium',
                'current_count': len(run_commands),
                'recommended_count': '1-3',
                'description': f'Found {len(run_commands)} RUN commands. Consider combining related operations.',
                'implementation': 'Combine RUN commands with && to reduce layers'
            })
        
        # Package manager cleanup analysis
        package_managers = {
            'apt': {'install': r'apt-get\s+install', 'cleanup': r'rm\s+-rf\s+/var/lib/apt/lists'},
            'yum': {'install': r'yum\s+install', 'cleanup': r'yum\s+clean\s+all'},
            'apk': {'install': r'apk\s+add', 'cleanup': r'rm\s+-rf\s+/var/cache/apk'}
        }
        
        for pm_name, patterns in package_managers.items():
            if re.search(patterns['install'], content) and not re.search(patterns['cleanup'], content):
                analysis['size_optimizations'].append({
                    'type': f'{pm_name}_cleanup_missing',
                    'severity': 'medium',
                    'description': f'Missing {pm_name} cache cleanup',
                    'potential_savings': '50-200MB',
                    'implementation': f'Add cleanup command in same RUN layer'
                })
        
        # Copy optimization analysis
        copy_commands = [line for line in lines if line.strip().startswith(('COPY', 'ADD'))]
        if any('.' in cmd for cmd in copy_commands):
            analysis['build_optimizations'].append({
                'type': 'inefficient_copy',
                'severity': 'low',
                'description': 'Consider using .dockerignore and specific COPY commands',
                'implementation': 'Copy only necessary files to improve build cache efficiency'
            })
    
    def _generate_strategic_recommendations(self, analysis: Dict, app_type: str):
        """Generate strategic optimization recommendations based on application type"""
        strategy = self.optimization_strategies[app_type]
        
        # Priority-based recommendations
        for priority in strategy['priorities']:
            if priority == 'security':
                analysis['recommendations'].append(OptimizationRecommendation(
                    category='Security',
                    priority='High',
                    impact='Critical',
                    effort='Medium',
                    description='Implement security scanning and hardening',
                    implementation=self._get_security_implementation(app_type),
                    validation='Run Trivy and Hadolint scans'
                ))
            elif priority == 'size':
                analysis['recommendations'].append(OptimizationRecommendation(
                    category='Size Optimization',
                    priority='High',
                    impact='High',
                    effort='Low',
                    description=f'Use {strategy["recommended_base"]} base image',
                    implementation=self._get_size_implementation(app_type),
                    validation='Compare image sizes before/after'
                ))
            elif priority == 'startup_time':
                analysis['recommendations'].append(OptimizationRecommendation(
                    category='Startup Performance',
                    priority='Medium',
                    impact='High',
                    effort='Medium',
                    description='Optimize application startup time',
                    implementation=self._get_startup_implementation(app_type),
                    validation='Measure container startup time'
                ))
    
    def _estimate_size_savings(self, optimization_type: str) -> str:
        """Estimate potential size savings for optimization"""
        savings_map = {
            'large_base_images': '200-800MB',
            'apt_cleanup_missing': '50-200MB',
            'yum_cleanup_missing': '100-300MB',
            'apk_cleanup_missing': '20-100MB',
            'excessive_layers': '10-50MB',
            'multi_stage_optimization': '100-500MB'
        }
        return savings_map.get(optimization_type, '10-50MB')
    
    def _get_security_implementation(self, app_type: str) -> str:
        """Get security implementation based on app type"""
        implementations = {
            'web_application': 'Non-root user, security scanning, minimal packages',
            'microservice': 'Distroless base, static compilation, capability dropping',
            'data_processing': 'Secure data handling, encrypted volumes, network policies',
            'machine_learning': 'Model encryption, secure model serving, GPU security'
        }
        return implementations.get(app_type, 'Standard security hardening')

Read the full file on GitHub · 2,335 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 10d ago First seen · 2,335 lines · 0 tokens per session scan C 2450cf11f3db

Subscribe to this mod's changes

docker-optimize is a command published in the GitHub repository georgekhananaev/claude-skills-vault (28 stars, last pushed 29d ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 17,600 tokens. A static security scan graded it C with 3 findings (downloads and executes remote code, recursive force delete, makes network calls). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.