Add Docker Configuration Validator skill and CLAUDE.md

Added comprehensive Docker validation skill for Dockerfiles and Docker Compose files:

## Docker Configuration Validator (v1.0.0)
Complete validation framework for Docker configurations with best practices and security standards.

Features:
- Dockerfile validation with Hadolint integration
- Docker Compose validation with modern syntax enforcement (no obsolete version field)
- Multi-stage build verification and optimization
- Security audit (non-root users, exposed secrets, vulnerable images)
- Automated validation script generation
- CI/CD integration (GitHub Actions, GitLab CI, pre-commit hooks)
- Comprehensive checklists and tool installation guides

Workflow:
1. Initial assessment and scope identification
2. Dockerfile validation (syntax, security, best practices)
3. Docker Compose validation (modern syntax, service config)
4. Multi-stage build deep dive
5. Security audit
6. Detailed reporting with prioritized issues

Resources:
- SKILL.md: Complete validation workflow with 6 phases
- README.md: User documentation and usage guide
- validation-checklist.md: Complete validation checklists
- tool-installation.md: Tool setup guide for all platforms

## CLAUDE.md
Created comprehensive guidance file for Claude Code instances working in this repository.

Contents:
- Repository purpose and structure
- Skill categories and organization
- Working with skills (file structure, design principles)
- Creating and modifying skills
- Marketplace configuration
- Testing workflows
- Version control practices

## Marketplace Updates
- Updated to version 4.0.0
- Added Docker Configuration Validator to development category
- Updated main README with skill documentation
- Updated repository structure diagram
- Total skills in marketplace: 5

Skills by category:
- Development (3): Python Architecture Review, UI/UX Design Review, Docker Validation
- Design (2): Web Design Builder, SVG Logo Designer

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Roland Knall
2025-10-18 17:18:34 +02:00
parent a3c2dadbd5
commit 400d3af2c3
8 changed files with 3516 additions and 5 deletions
+9 -2
View File
@@ -1,8 +1,8 @@
{
"$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
"name": "rknall-custom-skills",
"version": "3.0.0",
"description": "Custom Claude Code skills marketplace for architecture review, accessibility expertise, and creative design generation",
"version": "4.0.0",
"description": "Custom Claude Code skills marketplace for architecture review, accessibility expertise, creative design generation, and DevOps validation",
"owner": {
"name": "rknall"
},
@@ -21,6 +21,13 @@
"version": "1.0.0",
"category": "development"
},
{
"name": "docker-validation",
"source": "./docker-validation",
"description": "Comprehensive Docker and Docker Compose validation following best practices and security standards. Validates Dockerfiles, multi-stage builds, modern Compose syntax, and generates automation scripts",
"version": "1.0.0",
"category": "development"
},
{
"name": "web-design-builder",
"source": "./web-design-builder",
+184
View File
@@ -0,0 +1,184 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Repository Purpose
This is a **Claude Code Skills Marketplace** containing custom skills that extend Claude's capabilities. Skills are specialized prompts with supporting documentation that guide Claude to perform expert-level tasks in specific domains.
## Repository Structure
```
Skills/
├── .claude-plugin/
│ └── marketplace.json # Marketplace configuration with all skills metadata
├── {skill-name}/ # Each skill has its own directory
│ ├── SKILL.md # Main skill definition with YAML frontmatter (REQUIRED)
│ ├── README.md # User-facing documentation (REQUIRED)
│ └── *.md # Supporting resources (checklists, patterns, templates)
└── CLAUDE.md # This file
```
## Skill Categories
Current skills are organized into two categories:
**Development**: Architecture and design reviews
- `python-architecture-review`: Backend Python application architecture reviews
- `ui-design-review`: UI/UX and WCAG 2.1/2.2 accessibility compliance reviews
**Design**: Creative generation and design work
- `web-design-builder`: HTML5/JavaScript web design generation with Playwright verification
- `svg-logo-designer`: Professional SVG logo creation with multiple variations
## Working with Skills
### Skill File Structure
Every skill MUST have this structure:
**SKILL.md** (Required):
```markdown
---
name: "Display Name"
description: "What the skill does and WHEN to use it. Be explicit about trigger phrases."
---
# Skill Name
[Comprehensive instructions for Claude...]
```
**README.md** (Required):
- User-facing documentation
- Installation instructions
- Usage examples
- When to use the skill
**Supporting Files** (Optional but recommended):
- Checklists (e.g., `wcag-checklist.md`, `architecture-checklist.md`)
- Pattern libraries (e.g., `common-patterns.md`, `design-patterns-library.md`)
- Reference materials (e.g., `technology-recommendations.md`, `design-templates.md`)
### Skill Design Principles
1. **Comprehensive Instructions**: Skills should contain detailed, step-by-step workflows that Claude can follow autonomously
2. **Clear Triggers**: The `description` field must explicitly state when Claude should use this skill
3. **Supporting Resources**: Complex skills should include reference materials that Claude can consult
4. **Structured Output**: Skills should define clear output formats and deliverables
5. **Best Practices**: Include domain-specific best practices and current (2025) recommendations
### Creating New Skills
When adding a new skill:
1. **Create skill directory**: `mkdir new-skill-name`
2. **Create SKILL.md** with YAML frontmatter and comprehensive instructions
3. **Create README.md** with user documentation
4. **Add supporting resources** as separate `.md` files
5. **Update marketplace.json**:
```json
{
"name": "skill-name",
"source": "./skill-name",
"description": "Clear description with trigger phrases",
"version": "1.0.0",
"category": "development" | "design"
}
```
6. **Update main README.md** with new skill documentation
7. **Increment marketplace version** in `marketplace.json`
### Modifying Existing Skills
When updating a skill:
1. **Edit skill files** (SKILL.md, README.md, supporting docs)
2. **Update version number** in `marketplace.json`
3. **Update main README.md** if significant changes
4. **Document changes** in README.md version history
5. **Test locally** before committing
## Marketplace Configuration
The `.claude-plugin/marketplace.json` file is the source of truth for:
- Marketplace metadata (name, version, description)
- All available skills and their metadata
- Skill categorization
**Current marketplace version**: Check `marketplace.json` for latest version
## Testing Skills Locally
Before committing skill changes:
1. Install the skill locally:
```bash
/plugin install skill-name
```
2. Test by triggering the skill with appropriate prompts
3. Verify all supporting resources are accessible
4. Check that output matches expected format
## Skill Architecture Patterns
### Review Skills (Python Architecture Review, UI/UX Design Review)
Structure:
- **When to Use This Skill**: Clear trigger conditions
- **Review Framework**: Comprehensive evaluation dimensions
- **Review Output Format**: Structured deliverables
- **Communication Style**: How to interact with users
- **Reference Standards**: Industry standards and guidelines
- **Tools & Resources**: Recommended tools for the domain
### Generation Skills (Web Design Builder, SVG Logo Designer)
Structure:
- **When to Use This Skill**: Clear trigger conditions
- **Core Workflow**: Phase-by-phase process
- **Requirements Gathering**: Questions to ask users
- **Generation/Creation**: Step-by-step creation process
- **Verification/Review**: Quality checks and testing
- **Deliverables**: What to provide to users
- **Best Practices**: Domain-specific patterns and examples
## Git Workflow
This repository uses standard git practices:
**Branch**: `main` (primary branch)
**Commit conventions**: Use descriptive commit messages that explain what was added/changed
**Testing**: Always test skills locally before pushing
## Key Files to Update When Making Changes
| Change Type | Files to Update |
|-------------|----------------|
| New skill | `marketplace.json`, `README.md`, new skill directory |
| Skill update | Skill files, `marketplace.json` (version), potentially `README.md` |
| Marketplace metadata | `marketplace.json`, `README.md` |
| Documentation | Relevant `README.md` and skill documentation files |
## Important Notes
- **YAML Frontmatter**: SKILL.md must have valid YAML frontmatter with `name` and `description`
- **Descriptions**: Should explain BOTH what the skill does AND when to use it
- **Supporting Files**: Keep supporting documentation in separate `.md` files for modularity
- **Versioning**: Follow semantic versioning (MAJOR.MINOR.PATCH)
- **Categories**: Currently using "development" and "design" - maintain consistency
- **File Naming**: Use kebab-case for directories and files (e.g., `ui-design-review`)
## Distribution
This marketplace is designed to be distributed via git repository and installed with:
```bash
/plugin marketplace add rknall/Skills
```
Skills can then be installed individually or as a set.
+55 -3
View File
@@ -102,7 +102,42 @@ A production-ready skill that provides expert-level design reviews covering:
[View Full Documentation](./ui-design-review/README.md)
### 3. Web Design Builder
### 3. Docker Configuration Validator
**Version:** 1.0.0
**Category:** Development
**Description:** Comprehensive Docker and Docker Compose validation following best practices and security standards
A production-ready skill that provides expert-level Docker configuration validation:
- **Dockerfile Validation**: Syntax, multi-stage builds, security, best practices
- **Docker Compose Validation**: Modern syntax (no obsolete version field), service configuration
- **Security Audit**: Non-root users, exposed secrets, vulnerable base images
- **Multi-Stage Build Verification**: Proper stage implementation and optimization
- **Automation**: Generates validation scripts, CI/CD integrations, pre-commit hooks
- **Comprehensive Reporting**: Detailed issues with fixes, prioritized by severity
**Key Features:**
- Hadolint integration for deep Dockerfile analysis
- DCLint integration for Compose file linting
- Modern Compose syntax enforcement (v2.27.0+)
- Multi-stage build pattern validation
- Security vulnerability identification
- Automated validation script generation
- GitHub Actions and GitLab CI templates
- Complete validation checklists
**When to Use:**
- Validate Dockerfiles before deployment
- Audit Docker security and compliance
- Modernize Docker Compose files
- Review production readiness
- Create automated validation workflows
- Set up CI/CD pipeline validation
- Fix Docker configuration issues
[View Full Documentation](./docker-validation/README.md)
### 4. Web Design Builder
**Version:** 1.0.0
**Category:** Design
@@ -136,7 +171,7 @@ A production-ready skill that generates complete, accessible web designs from sp
[View Full Documentation](./web-design-builder/README.md)
### 4. SVG Logo Designer
### 5. SVG Logo Designer
**Version:** 1.0.0
**Category:** Design
@@ -188,6 +223,11 @@ Skills/
│ ├── wcag-checklist.md # WCAG 2.1/2.2 compliance checklist
│ ├── design-patterns-library.md # Accessible component patterns
│ └── testing-resources.md # Testing tools and methods
├── docker-validation/ # Docker Configuration Validator Skill
│ ├── SKILL.md # Main skill definition
│ ├── README.md # Skill documentation
│ ├── validation-checklist.md # Complete validation checklist
│ └── tool-installation.md # Tool setup guide
├── web-design-builder/ # Web Design Builder Skill
│ ├── SKILL.md # Main skill definition
│ ├── README.md # Skill documentation
@@ -317,6 +357,17 @@ Users install it with a single command:
## Version History
### 4.0.0 (2025-10-18)
- Added Docker Configuration Validator skill v1.0.0
- Comprehensive Dockerfile and Docker Compose validation
- Modern Compose syntax enforcement (no obsolete version field)
- Multi-stage build verification
- Security audit capabilities
- Hadolint and DCLint integration
- Automated validation script generation
- CI/CD integration templates (GitHub Actions, GitLab CI)
- Complete validation checklists and tool installation guides
### 3.0.0 (2025-10-18)
- Added Web Design Builder skill v1.0.0
- HTML5/JavaScript design generation
@@ -361,6 +412,7 @@ To add or improve skills in this marketplace:
Planned skills for future releases:
- Frontend Architecture Review (React/Vue/Angular)
- Infrastructure as Code Review (Terraform/CloudFormation)
- Kubernetes Configuration Validator (manifest validation, best practices)
- Security Audit Skill (penetration testing, threat modeling)
- Performance Optimization Skill (profiling, benchmarking)
- Database Schema Review Skill
@@ -387,6 +439,6 @@ These skills are provided as-is for use with Claude Code. Individual skills may
---
**Marketplace Version:** 1.0.0
**Marketplace Version:** 4.0.0
**Last Updated:** 2025-10-18
**Maintainer:** rknall
+383
View File
@@ -0,0 +1,383 @@
# Docker Configuration Validator
**Version:** 1.0.0
**Category:** Development
**Description:** Comprehensive Docker and Docker Compose validation following best practices and security standards
## Overview
The Docker Configuration Validator skill provides expert-level validation of Dockerfiles and Docker Compose files, ensuring your Docker configurations follow modern best practices, security standards, and syntax requirements. This skill automates the validation process, identifies issues, and provides specific, actionable fixes.
## Features
### Dockerfile Validation
-**Syntax Validation**: Hadolint integration for deep Dockerfile analysis
-**Multi-Stage Build Verification**: Ensures proper multi-stage implementation
-**Security Audit**: Checks for root users, exposed secrets, vulnerable images
-**Best Practices**: Enforces Docker best practices and optimization patterns
-**Layer Optimization**: Identifies inefficient layer structure
### Docker Compose Validation
-**Modern Syntax Compliance**: Ensures no obsolete `version` field (Compose v2.27.0+)
-**Image Tag Validation**: Checks for `:latest` tags and unpinned versions
-**Service Configuration**: Validates restart policies, health checks, resource limits
-**Network & Volume Best Practices**: Ensures proper networking and persistence
-**Security Review**: Checks for hardcoded secrets, privilege escalation
### Automation & Integration
-**Validation Scripts**: Generates custom bash scripts for automated validation
-**CI/CD Integration**: Provides GitHub Actions and GitLab CI configurations
-**Pre-commit Hooks**: Creates hooks for local validation before commits
-**Comprehensive Reports**: Detailed validation reports with prioritized issues
## When to Use This Skill
Use this skill when you need to:
- Validate Dockerfiles before committing to version control
- Review Docker configurations for production readiness
- Audit Docker security and identify vulnerabilities
- Ensure compliance with Docker best practices
- Modernize Docker Compose files (remove obsolete syntax)
- Create automated validation workflows
- Set up CI/CD pipeline validation
- Generate validation reports for team review
- Fix Docker configuration issues
## How It Works
### 1. Initial Assessment
The skill starts by understanding what you need validated:
- Which files to check (Dockerfile, Compose, or both)
- Specific concerns or focus areas
- Whether automation is needed
### 2. Comprehensive Validation
Performs multi-layered validation:
- **Syntax validation** using Hadolint and DCLint (if available)
- **Manual validation** covering all critical best practices
- **Security audit** for vulnerabilities and misconfigurations
- **Multi-stage build analysis** for optimization opportunities
- **Modern syntax compliance** (especially for Compose files)
### 3. Issue Classification
Categorizes findings by severity:
- **CRITICAL**: Must fix before deployment (security, functionality)
- **HIGH**: Should fix before production (reliability, best practices)
- **MEDIUM**: Recommended improvements (optimization, maintainability)
- **LOW**: Nice-to-have enhancements (polish, edge cases)
### 4. Detailed Reporting
Generates comprehensive reports including:
- Executive summary with overall status
- Specific issues with line numbers
- Before/after code examples
- Impact assessment for each issue
- Prioritized recommendations
- Effort estimates for fixes
### 5. Automation (Optional)
Can create:
- Custom validation scripts
- CI/CD pipeline configurations
- Pre-commit hooks
- Regular security scan setups
## Prerequisites
### Required
- **Docker**: Validation needs Docker CLI for syntax checking
```bash
docker --version # Should be 20.10+
docker compose version # Should be v2.27.0+
```
### Recommended
- **Hadolint**: Dockerfile linter (highly recommended)
```bash
# macOS
brew install hadolint
# Linux
wget -O /usr/local/bin/hadolint https://github.com/hadolint/hadolint/releases/download/v2.12.0/hadolint-Linux-x86_64
chmod +x /usr/local/bin/hadolint
# Verify
hadolint --version
```
- **DCLint**: Docker Compose linter (recommended)
```bash
# Install via npm
npm install -g docker-compose-linter
# Verify
dclint --version
```
**Note:** The skill can perform validation even without these tools, but they significantly enhance the validation quality.
## Example Usage
### Basic Validation
```
User: "Can you validate my Dockerfile?"
Claude: "I'll validate your Dockerfile for best practices and security. Let me check..."
[Claude performs comprehensive validation and provides detailed report]
```
### Docker Compose Modernization
```
User: "Check my docker-compose.yml for issues"
Claude: "I'll validate your Docker Compose file. Checking for modern syntax compliance..."
[Claude identifies obsolete version field and other issues]
"❌ CRITICAL: Found obsolete 'version' field. This is deprecated in Compose v2.27.0+.
Remove the 'version: 3.8' line from your compose file."
```
### Full Project Audit
```
User: "Audit all Docker configs in my project for production readiness"
Claude: "I'll perform a comprehensive audit of all Dockerfiles and Compose files..."
[Claude validates all files and generates full security and best practices report]
```
### Automation Setup
```
User: "Create a validation script I can run in CI/CD"
Claude: "I'll create a comprehensive validation script with CI/CD integration..."
[Claude generates bash script + GitHub Actions workflow]
```
## Key Validation Checks
### Dockerfile Checks
- ❌ No `:latest` tags → Pin specific versions
- ❌ Running as root → Use non-root USER
- ❌ Single-stage build → Implement multi-stage
- ❌ Using ADD → Prefer COPY unless extracting
- ❌ No HEALTHCHECK → Add health monitoring
- ❌ No cache cleanup → Clean package manager caches
- ❌ Relative WORKDIR → Use absolute paths
### Docker Compose Checks
- ❌ `version:` field present → REMOVE (obsolete)
- ❌ `:latest` tags → Pin specific versions
- ❌ No restart policy → Add restart directives
- ❌ No health checks → Configure health monitoring
- ❌ No named volumes → Use named volumes for persistence
- ❌ No custom networks → Define custom networks
- ❌ Hardcoded secrets → Use environment variables or secrets management
### Security Checks
- ❌ Running as root user
- ❌ Secrets in image layers
- ❌ Unnecessary privileges
- ❌ Vulnerable base images
- ❌ Excessive port exposure
- ❌ Missing security updates
## Validation Report Example
```markdown
# Docker Configuration Validation Report
## Executive Summary
- Total Dockerfiles: 3
- Total Compose Files: 1
- Critical Issues: 2
- High Priority: 4
- Status: ⚠️ REQUIRES FIXES
## Critical Issues
1. Dockerfile (line 1): Using :latest tag
Fix: FROM node:20-bullseye
Impact: Unpredictable builds
2. docker-compose.yml (line 1): Obsolete version field
Fix: Remove 'version: 3.8' line
Impact: Using deprecated syntax
## Recommendations
- Immediate: Pin all image versions, remove version field
- High Priority: Add health checks, configure restart policies
- Medium: Implement multi-stage builds for optimization
```
## Common Issues & Fixes
### Issue: Obsolete Docker Compose Version Field
**Problem:**
```yaml
version: '3.8' # ❌ Obsolete!
services:
web:
image: nginx
```
**Fix:**
```yaml
# No version field needed!
services:
web:
image: nginx:1.24-alpine
```
### Issue: Running as Root
**Problem:**
```dockerfile
FROM alpine
COPY app /app
CMD ["/app/server"] # Runs as root!
```
**Fix:**
```dockerfile
FROM alpine
RUN addgroup -g 1001 appuser && \
adduser -D -u 1001 -G appuser appuser
COPY --chown=appuser:appuser app /app
USER appuser
CMD ["/app/server"]
```
### Issue: No Multi-Stage Build
**Problem:**
```dockerfile
FROM node:18
COPY . .
RUN npm install # Includes dev dependencies!
CMD ["npm", "start"]
```
**Fix:**
```dockerfile
# Build stage
FROM node:18 AS builder
COPY . .
RUN npm ci && npm run build
# Runtime stage
FROM node:18-alpine
COPY --from=builder /app/dist ./dist
RUN npm ci --only=production
CMD ["node", "dist/index.js"]
```
## Best Practices Enforced
### Dockerfile Best Practices
- Use specific image tags (no `:latest`)
- Implement multi-stage builds
- Run as non-root user
- Use COPY instead of ADD
- Add HEALTHCHECK instructions
- Clean package manager caches
- Use absolute WORKDIR paths
- Add appropriate labels
### Docker Compose Best Practices
- No `version` field (obsolete in v2.27.0+)
- Pin all image versions
- Define restart policies
- Configure health checks
- Use named volumes
- Define custom networks
- Manage secrets properly
- Set resource limits
### Security Best Practices
- Never run as root
- No secrets in images
- Use minimal base images
- Regular security scans
- Least privilege principle
- Network isolation
- Read-only root filesystem (where applicable)
## Integration Examples
### GitHub Actions
```yaml
name: Docker Validation
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hadolint/hadolint-action@v3.1.0
with:
dockerfile: Dockerfile
- run: docker compose config --quiet
```
### GitLab CI
```yaml
docker-validation:
stage: validate
image: hadolint/hadolint:latest
script:
- hadolint Dockerfile
- docker compose config --quiet
```
### Pre-commit Hook
```bash
#!/bin/bash
# .git/hooks/pre-commit
if git diff --cached --name-only | grep -q "Dockerfile"; then
hadolint Dockerfile || exit 1
fi
```
## Resources
### Validation Tools
- [Hadolint](https://github.com/hadolint/hadolint) - Dockerfile linter
- [DCLint](https://github.com/zavoloklom/docker-compose-linter) - Compose linter
- [Trivy](https://github.com/aquasecurity/trivy) - Security scanner
### Documentation
- [Docker Best Practices](https://docs.docker.com/develop/dev-best-practices/)
- [Dockerfile Reference](https://docs.docker.com/engine/reference/builder/)
- [Compose Specification](https://docs.docker.com/compose/compose-file/)
- [Hadolint Rules](https://github.com/hadolint/hadolint#rules)
### Learning Resources
- [Multi-Stage Builds Guide](https://docs.docker.com/build/building/multi-stage/)
- [Security Best Practices](https://docs.docker.com/engine/security/)
- [Compose v2 Migration](https://docs.docker.com/compose/migrate/)
## Support
For issues with this skill or suggestions for improvements:
- Check the skill's SKILL.md for detailed workflow
- Review validation-checklist.md for complete rule set
- Consult tool-installation.md for setup help
## Version History
### 1.0.0 (2025-10-18)
- Initial release
- Comprehensive Dockerfile validation
- Docker Compose validation with modern syntax checking
- Multi-stage build verification
- Security audit capabilities
- Automation script generation
- CI/CD integration templates
---
**Maintainer:** rknall
**Last Updated:** 2025-10-18
**Skill Type:** Development / DevOps
+758
View File
@@ -0,0 +1,758 @@
---
name: "Docker Configuration Validator"
description: "Comprehensive Docker and Docker Compose validation following best practices and security standards. Use this skill when users ask to validate Dockerfiles, review Docker configurations, check Docker Compose files, verify multi-stage builds, audit Docker security, or ensure compliance with Docker best practices. Validates syntax, security, multi-stage builds, and modern Docker Compose requirements."
---
# Docker Configuration Validator
This skill provides comprehensive validation for Dockerfiles and Docker Compose files, ensuring compliance with best practices, security standards, and modern syntax requirements.
## When to Use This Skill
Activate this skill when the user requests:
- Validate Dockerfiles or Docker Compose files
- Review Docker configurations for best practices
- Check for Docker security issues
- Verify multi-stage build implementation
- Audit Docker setup for production readiness
- Ensure modern Docker Compose syntax compliance
- Fix Docker configuration issues
- Create validation scripts or CI/CD integration
## Core Workflow
### Phase 1: Initial Assessment
When a user requests Docker validation, start by understanding the scope:
1. **Identify What to Validate**
- Single Dockerfile or multiple?
- Docker Compose file(s)?
- Entire project directory?
- Specific concerns or focus areas?
- Production vs development environment?
2. **Understand Requirements**
- Security compliance level needed?
- Multi-stage build requirement?
- Performance constraints?
- CI/CD integration needed?
- Automated validation script desired?
3. **Check Available Tools**
- Is Hadolint available? (Dockerfile linter)
- Is DCLint available? (Docker Compose linter)
- Is Docker CLI available?
- Should tools be installed as part of process?
### Phase 2: Dockerfile Validation
#### Step 1: Locate Dockerfiles
Find all Dockerfiles in the project:
```bash
find . -type f \( -name "Dockerfile*" ! -name "*.md" \)
```
#### Step 2: Run Hadolint Validation
**If Hadolint is available:**
```bash
# Validate each Dockerfile
hadolint Dockerfile
# JSON output for programmatic analysis
hadolint --format json Dockerfile
# Set failure threshold
hadolint --failure-threshold error Dockerfile
```
**If Hadolint is NOT available:**
- Perform manual validation using built-in checks (see Step 3)
- Recommend Hadolint installation
- Provide installation instructions
#### Step 3: Manual Dockerfile Validation
Check each Dockerfile for critical issues:
**1. Base Image Best Practices**
- ✅ Check: No `:latest` tags
- ✅ Check: Specific version pinned
- ✅ Check: Uses minimal base images (alpine/slim variants)
- ✅ Check: Trusted registry used
**2. Multi-Stage Build Verification**
```bash
# Count FROM statements (should be >= 2 for multi-stage)
FROM_COUNT=$(grep -c "^FROM " Dockerfile)
# Check for named stages
NAMED_STAGES=$(grep -c "^FROM .* AS " Dockerfile)
# Check for inter-stage copies
COPY_FROM=$(grep -c "COPY --from=" Dockerfile)
```
**Analysis:**
- If FROM_COUNT >= 2: Multi-stage build detected ✅
- If COPY_FROM == 0 and FROM_COUNT >= 2: Warning - artifacts may not be transferred
- If FROM_COUNT == 1: Single-stage build - recommend multi-stage for optimization
**3. Security Checks**
- ✅ Check: USER directive present (non-root)
- ✅ Check: Last USER is not root
- ✅ Check: No secrets in Dockerfile
- ✅ Check: WORKDIR uses absolute paths
- ✅ Check: No unnecessary privileges
**4. Layer Optimization**
- ✅ Check: Combined RUN commands
- ✅ Check: Package manager cache cleaned
- ✅ Check: COPY before RUN for better caching
- ✅ Check: .dockerignore file exists
**5. Best Practices**
- ✅ Check: HEALTHCHECK defined
- ✅ Check: WORKDIR used (not cd)
- ✅ Check: COPY preferred over ADD
- ✅ Check: CMD/ENTRYPOINT uses JSON notation
- ✅ Check: Labels included (maintainer, version)
#### Step 4: Dockerfile Issue Classification
Classify findings by severity:
**CRITICAL (Must Fix):**
- Running as root user
- Using `:latest` tags
- Secrets exposed in image
- Invalid syntax
**HIGH (Should Fix):**
- No multi-stage build when applicable
- No HEALTHCHECK
- Package versions not pinned
- Security vulnerabilities
**MEDIUM (Recommended):**
- Using ADD instead of COPY
- Not cleaning package cache
- Missing labels
- Inefficient layer structure
**LOW (Nice to Have):**
- Could use slimmer base image
- Could combine more RUN commands
- Could improve comments
### Phase 3: Docker Compose Validation
#### Step 1: Locate Compose Files
Find all Docker Compose files:
```bash
find . -maxdepth 3 -type f \( -name "docker-compose*.yml" -o -name "docker-compose*.yaml" -o -name "compose*.yml" \)
```
#### Step 2: Check for Obsolete Version Field
**CRITICAL CHECK:** Modern Docker Compose (v2.27.0+) does NOT use version field
```bash
# Check for obsolete version field
if grep -q "^version:" docker-compose.yml; then
echo "❌ ERROR: Found obsolete 'version' field"
echo "Remove 'version:' line - it's obsolete in Compose v2.27.0+"
fi
```
**Old (Deprecated):**
```yaml
version: '3.8' # ❌ REMOVE THIS
services:
web:
image: nginx:latest
```
**New (Modern):**
```yaml
# No version field!
services:
web:
image: nginx:1.24-alpine
```
#### Step 3: Built-in Docker Compose Validation
```bash
# Syntax validation
docker compose config --quiet
# Show resolved configuration
docker compose config
# Validate specific file
docker compose -f docker-compose.prod.yml config --quiet
```
#### Step 4: DCLint Validation (if available)
```bash
# Lint compose file
dclint docker-compose.yml
# Auto-fix issues
dclint --fix docker-compose.yml
# JSON output
dclint --format json docker-compose.yml
```
#### Step 5: Manual Compose Validation
**1. Image Best Practices**
- ✅ Check: No `:latest` tags
- ✅ Check: Specific versions specified
- ✅ Check: Images from trusted sources
**2. Service Configuration**
- ✅ Check: Restart policies defined
- ✅ Check: Health checks configured
- ✅ Check: Resource limits set (optional but recommended)
- ✅ Check: Proper service dependencies (depends_on)
**3. Networking**
- ✅ Check: Custom networks defined
- ✅ Check: Network isolation implemented
- ✅ Check: Appropriate network drivers used
**4. Volumes & Persistence**
- ✅ Check: Named volumes for persistence
- ✅ Check: Volume drivers specified
- ✅ Check: Bind mounts use absolute paths
- ✅ Check: No sensitive data in volumes
**5. Environment & Secrets**
- ✅ Check: Environment variables properly managed
- ✅ Check: No hardcoded secrets
- ✅ Check: .env file usage recommended
- ✅ Check: Secrets management configured
**6. Security**
- ✅ Check: No privileged mode (unless necessary)
- ✅ Check: Capabilities properly configured
- ✅ Check: User/group specified
- ✅ Check: Read-only root filesystem (where applicable)
### Phase 4: Multi-Stage Build Deep Dive
When validating multi-stage builds, ensure:
**1. Stage Structure**
```dockerfile
# Build stage
FROM node:20-bullseye AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm run test
# Production stage
FROM node:20-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
USER node
CMD ["node", "dist/index.js"]
```
**2. Validation Checklist**
- ✅ At least 2 stages (build + runtime)
- ✅ All stages are named with AS keyword
- ✅ Artifacts copied between stages using COPY --from
- ✅ Final stage uses minimal base image
- ✅ Build tools NOT in final stage
- ✅ Only necessary files in final image
- ✅ Final stage runs as non-root user
**3. Common Patterns to Check**
**Node.js Multi-Stage:**
- Build stage: Install all deps, build, test
- Runtime stage: Production deps only, built artifacts
**Python Multi-Stage:**
- Build stage: Compile dependencies, build wheels
- Runtime stage: Install pre-built wheels, app only
**Go Multi-Stage:**
- Build stage: Full Go toolchain, compile binary
- Runtime stage: Scratch/distroless, binary only
### Phase 5: Security Audit
Perform comprehensive security checks:
**1. User & Permissions**
```bash
# Check for USER directive
USER_COUNT=$(grep -c "^USER " Dockerfile)
LAST_USER=$(grep "^USER " Dockerfile | tail -1 | awk '{print $2}')
if [ "$USER_COUNT" -eq 0 ]; then
echo "❌ CRITICAL: No USER specified (runs as root!)"
elif [ "$LAST_USER" == "root" ] || [ "$LAST_USER" == "0" ]; then
echo "❌ CRITICAL: Final USER is root"
fi
```
**2. Exposed Secrets**
- Check for passwords in ENV
- Check for API keys in COPY/ADD
- Check for credentials in RUN commands
- Recommend secrets management solutions
**3. Vulnerable Base Images**
- Check base image age and support status
- Recommend security scanning (Trivy, Snyk)
- Suggest pinned, supported versions
**4. Network Exposure**
- Review EXPOSE directives
- Check if unnecessary ports exposed
- Validate port mappings in Compose
### Phase 6: Generate Validation Report
Structure the validation report:
```markdown
# Docker Configuration Validation Report
## Executive Summary
- **Total Dockerfiles Analyzed**: X
- **Total Compose Files Analyzed**: X
- **Critical Issues**: X
- **High Priority Issues**: X
- **Medium Priority Issues**: X
- **Low Priority Issues**: X
- **Overall Status**: ✅ PASS / ⚠️ WARNINGS / ❌ FAIL
## Dockerfile Analysis
### [Dockerfile Path]
#### Validation Results
**PASSED**: Multi-stage build implemented
**PASSED**: Running as non-root user
⚠️ **WARNING**: Using ADD instead of COPY (line 15)
**FAILED**: Base image uses :latest tag (line 1)
#### Security Assessment
- **User**: nodejs (non-root) ✅
- **Base Image**: node:latest ❌
- **Secrets**: None detected ✅
- **Health Check**: Present ✅
#### Multi-Stage Build Analysis
- **Stages**: 2 (builder, runtime)
- **Named Stages**: Yes ✅
- **Inter-Stage Copies**: 1 ✅
- **Final Base**: node:20-alpine ✅
- **Build Tools in Final**: No ✅
#### Issues Found
**CRITICAL:**
1. Line 1: Using :latest tag
- Issue: `FROM node:latest`
- Fix: `FROM node:20-bullseye`
- Impact: Unpredictable builds, security risk
**HIGH:**
2. Line 45: Package cache not cleaned
- Issue: `RUN apt-get install -y curl`
- Fix: Add `&& rm -rf /var/lib/apt/lists/*`
- Impact: Larger image size
**MEDIUM:**
3. Line 15: Using ADD instead of COPY
- Issue: `ADD app.tar.gz /app/`
- Fix: `COPY app.tar.gz /app/` (or extract separately)
- Impact: Less explicit behavior
## Docker Compose Analysis
### [Compose File Path]
#### Validation Results
**FAILED**: Obsolete 'version' field present
⚠️ **WARNING**: 3 services using :latest tags
**PASSED**: Custom networks defined
**PASSED**: Named volumes configured
#### Modern Syntax Compliance
- **Version Field**: Present ❌ (MUST REMOVE)
- **Specific Tags**: 2 of 5 services ⚠️
- **Restart Policies**: All services ✅
- **Health Checks**: 3 of 5 services ⚠️
#### Issues Found
**CRITICAL:**
1. Obsolete 'version' field
- Issue: `version: '3.8'`
- Fix: Remove the entire line
- Impact: Using deprecated syntax
**HIGH:**
2. Service 'web' uses :latest tag
- Issue: `image: nginx:latest`
- Fix: `image: nginx:1.24-alpine`
- Impact: Unpredictable deployments
3. No restart policy on 'cache' service
- Issue: Missing `restart:` directive
- Fix: Add `restart: unless-stopped`
- Impact: Service won't auto-recover
## Recommendations
### Immediate Actions (Critical)
1. Pin all Docker image versions (remove :latest)
2. Remove obsolete 'version' field from Compose files
3. Ensure all services run as non-root users
4. Clean package manager caches in all Dockerfiles
### High Priority (Before Production)
1. Implement health checks for all services
2. Add restart policies to all Compose services
3. Set up resource limits (memory, CPU)
4. Implement proper secrets management
### Medium Priority (Best Practices)
1. Use COPY instead of ADD unless extracting archives
2. Add labels for better organization
3. Implement logging drivers
4. Add metadata to images
### Low Priority (Optimizations)
1. Consider slimmer base images where possible
2. Optimize layer caching with better ordering
3. Add comprehensive comments
4. Implement .dockerignore files
## Next Steps
1. **Fix Critical Issues** (Estimated: 30 minutes)
- Pin image versions
- Remove version field from Compose
- Add USER directives
2. **Address High Priority** (Estimated: 1-2 hours)
- Add health checks
- Configure restart policies
- Set resource limits
3. **Re-validate** (Estimated: 10 minutes)
- Run validation again after fixes
- Ensure all critical issues resolved
4. **Set Up Automation** (Estimated: 1 hour)
- Add pre-commit hooks
- Integrate into CI/CD
- Schedule regular security scans
## Validation Tools Recommendations
### Install Required Tools
```bash
# Hadolint (Dockerfile linter)
brew install hadolint # macOS
# or
wget -O /usr/local/bin/hadolint https://github.com/hadolint/hadolint/releases/download/v2.12.0/hadolint-Linux-x86_64
# DCLint (Docker Compose linter)
npm install -g docker-compose-linter
# Trivy (Security scanner)
brew install aquasecurity/trivy/trivy
```
### Automated Validation Script
[Provide custom validation script based on project needs]
### CI/CD Integration
[Provide GitHub Actions / GitLab CI configuration]
```
## Deliverables
At the end of validation, provide:
1. **Comprehensive Validation Report**
- Executive summary with overall status
- Detailed findings per file
- Issue classification (Critical → Low)
- Specific fixes for each issue
- Recommendations prioritized
2. **Fixed Configuration Files** (if requested)
- Corrected Dockerfiles
- Updated Compose files
- .hadolint.yaml configuration
- .dclintrc.json configuration
3. **Validation Script** (if requested)
- Custom bash script for automated validation
- Checks for project-specific requirements
- Color-coded output
- Exit codes for CI/CD
4. **CI/CD Integration** (if requested)
- GitHub Actions workflow
- GitLab CI configuration
- Pre-commit hooks
- Integration with existing pipeline
5. **Documentation**
- How to run validation locally
- Tool installation instructions
- Best practices guide
- Common issues and solutions
## Validation Script Template
When user requests automated validation, create this script:
```bash
#!/bin/bash
# docker-validation.sh
set -e
# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
ERRORS=0
WARNINGS=0
echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║ Docker Configuration Validator ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
# 1. Prerequisites check
echo -e "\n${BLUE}━━━ Checking Prerequisites ━━━${NC}"
command -v docker >/dev/null || { echo "❌ Docker not found"; exit 1; }
command -v hadolint >/dev/null || echo "⚠️ Hadolint not installed"
# 2. Dockerfile validation
echo -e "\n${BLUE}━━━ Validating Dockerfiles ━━━${NC}"
find . -name "Dockerfile*" -type f | while read df; do
echo "Checking: $df"
# [Validation logic here]
done
# 3. Multi-stage build check
echo -e "\n${BLUE}━━━ Checking Multi-Stage Builds ━━━${NC}"
# [Multi-stage validation logic]
# 4. Compose validation
echo -e "\n${BLUE}━━━ Validating Docker Compose ━━━${NC}"
find . -name "*compose*.yml" | while read cf; do
# Check for obsolete version field
if grep -q "^version:" "$cf"; then
echo -e "${RED}❌ $cf: Obsolete version field${NC}"
ERRORS=$((ERRORS + 1))
fi
# Validate syntax
docker compose -f "$cf" config --quiet || ERRORS=$((ERRORS + 1))
done
# 5. Security checks
echo -e "\n${BLUE}━━━ Security Audit ━━━${NC}"
# [Security validation logic]
# Final report
echo -e "\n${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║ Validation Summary ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
if [ $ERRORS -eq 0 ]; then
echo -e "${GREEN}✅ All checks passed!${NC}"
exit 0
else
echo -e "${RED}❌ Found $ERRORS error(s), $WARNINGS warning(s)${NC}"
exit 1
fi
```
## CI/CD Integration Templates
### GitHub Actions
```yaml
name: Docker Validation
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Lint Dockerfiles
uses: hadolint/hadolint-action@v3.1.0
with:
dockerfile: ./Dockerfile
failure-threshold: error
- name: Validate Compose files
run: |
for f in $(find . -name "*compose*.yml"); do
docker compose -f "$f" config --quiet
done
- name: Check for obsolete version field
run: |
if grep -r "^version:" . --include="*compose*.yml"; then
echo "ERROR: Found obsolete version field"
exit 1
fi
```
### GitLab CI
```yaml
stages:
- validate
docker-validation:
stage: validate
image: hadolint/hadolint:latest-debian
script:
- find . -name "Dockerfile*" -exec hadolint {} \;
- |
for f in $(find . -name "*compose*.yml"); do
if grep -q "^version:" "$f"; then
echo "ERROR: Obsolete version field in $f"
exit 1
fi
done
```
## Communication Style
When conducting validation:
1. **Be Thorough**
- Check all aspects systematically
- Don't skip manual checks if tools unavailable
- Validate both syntax and best practices
2. **Prioritize Clearly**
- Critical issues first (security, functionality)
- High priority next (production readiness)
- Medium and low as improvements
3. **Provide Specific Fixes**
- Show exact line numbers
- Provide before/after code
- Explain why the fix is needed
- Include impact assessment
4. **Educate**
- Explain Docker best practices
- Reference official documentation
- Provide learning resources
- Share modern syntax requirements
5. **Be Actionable**
- Give step-by-step remediation
- Provide automation scripts
- Suggest CI/CD integration
- Estimate effort for fixes
## Common Validation Patterns
### Pattern 1: Quick Syntax Check
- Run Hadolint and DCLint
- Check for obsolete version field
- Validate with Docker Compose config
- Report critical syntax errors only
### Pattern 2: Full Production Audit
- Complete Dockerfile validation
- Multi-stage build verification
- Security audit
- Compose best practices
- Generate comprehensive report
- Provide automation scripts
### Pattern 3: Security-Focused Review
- User privilege checks
- Secret exposure scan
- Base image security
- Network exposure audit
- Security scanning integration
### Pattern 4: Optimization Review
- Multi-stage build effectiveness
- Layer optimization
- Image size analysis
- Build time improvements
- Caching strategies
## Key Rules to Enforce
### Dockerfile Rules (Critical)
- ✅ No `:latest` tags (DL3006)
- ✅ Last USER not root (DL3002)
- ✅ Use absolute WORKDIR (DL3000)
- ✅ Pin package versions (DL3008, DL3013)
- ✅ Clean package cache (DL3009)
### Docker Compose Rules (Critical)
- ✅ NO version field (obsolete since v2.27.0)
- ✅ No `:latest` tags
- ✅ Restart policies defined
- ✅ Health checks configured
- ✅ Named volumes for persistence
### Multi-Stage Build Rules
- ✅ Minimum 2 stages
- ✅ Named stages with AS
- ✅ COPY --from for artifacts
- ✅ Minimal final base image
- ✅ No build tools in final stage
### Security Rules (Critical)
- ✅ Run as non-root USER
- ✅ No secrets in images
- ✅ Minimal base images
- ✅ Regular security scans
- ✅ Least privilege principle
## Reference Resources
When providing recommendations, reference:
- **Docker Best Practices**: Official Docker documentation
- **Hadolint Rules**: Complete rule reference
- **Compose Specification**: Latest Compose spec
- **Security Standards**: CIS Docker Benchmark
- **Multi-Stage Builds**: Official guide and examples
Remember: Docker validation is about ensuring reliable, secure, and efficient containerized applications. Always prioritize security and production readiness while maintaining developer experience.
+534
View File
@@ -0,0 +1,534 @@
# Docker Validation Tools Installation Guide
Complete installation instructions for all tools needed for Docker configuration validation.
## Required Tools
### 1. Docker & Docker Compose
#### macOS
```bash
# Install Docker Desktop (includes Docker and Compose)
brew install --cask docker
# Start Docker Desktop application
open -a Docker
# Verify installation
docker --version
docker compose version
```
#### Linux (Ubuntu/Debian)
```bash
# Install Docker Engine
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# Add user to docker group
sudo usermod -aG docker $USER
newgrp docker
# Install Docker Compose
sudo apt-get update
sudo apt-get install docker-compose-plugin
# Verify installation
docker --version
docker compose version
```
#### Windows
```powershell
# Install Docker Desktop via Chocolatey
choco install docker-desktop
# Or download from https://www.docker.com/products/docker-desktop
# Verify installation
docker --version
docker compose version
```
**Minimum Versions:**
- Docker: 20.10.0+
- Docker Compose: v2.27.0+ (for modern syntax support)
## Validation Tools
### 2. Hadolint (Dockerfile Linter)
**Why Hadolint?**
- Parses Dockerfile into AST for deep analysis
- Integrates ShellCheck for bash validation
- Enforces Docker best practices
- Highly configurable
#### macOS
```bash
# Install via Homebrew (recommended)
brew install hadolint
# Verify installation
hadolint --version
```
#### Linux
```bash
# Download binary (x86_64)
HADOLINT_VERSION=v2.12.0
wget -O /usr/local/bin/hadolint \
https://github.com/hadolint/hadolint/releases/download/${HADOLINT_VERSION}/hadolint-Linux-x86_64
# Make executable
chmod +x /usr/local/bin/hadolint
# Verify installation
hadolint --version
```
#### Windows
```powershell
# Download binary
$HADOLINT_VERSION = "v2.12.0"
Invoke-WebRequest -Uri "https://github.com/hadolint/hadolint/releases/download/${HADOLINT_VERSION}/hadolint-Windows-x86_64.exe" -OutFile "hadolint.exe"
# Move to PATH location
Move-Item hadolint.exe C:\Windows\System32\hadolint.exe
# Verify installation
hadolint --version
```
#### Using Docker (Cross-platform)
```bash
# Run Hadolint in container
docker run --rm -i hadolint/hadolint:latest < Dockerfile
# Create alias for convenience
echo 'alias hadolint="docker run --rm -i hadolint/hadolint:latest"' >> ~/.bashrc
source ~/.bashrc
# Verify
hadolint --version
```
#### VS Code Integration
```bash
# Install VS Code extension
code --install-extension exiasr.hadolint
# Extension will automatically use hadolint if installed
```
### 3. DCLint (Docker Compose Linter)
**Why DCLint?**
- Validates Docker Compose syntax
- Enforces best practices
- Checks for obsolete version field
- Auto-fix capabilities
#### Prerequisites
```bash
# Requires Node.js 20.19.0+
node --version
# If not installed:
# macOS
brew install node
# Linux (Ubuntu/Debian)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# Windows
choco install nodejs
```
#### Installation
```bash
# Install globally via npm (recommended)
npm install -g docker-compose-linter
# Or install locally in project
npm install --save-dev docker-compose-linter
# Verify installation
dclint --version
```
#### Using npx (No Installation)
```bash
# Run without global install
npx dclint docker-compose.yml
```
### 4. Trivy (Security Scanner)
**Why Trivy?**
- Comprehensive vulnerability scanner
- Scans images, filesystems, and configs
- Free and open-source
- Fast and easy to use
#### macOS
```bash
# Install via Homebrew
brew install aquasecurity/trivy/trivy
# Verify installation
trivy --version
```
#### Linux (Debian/Ubuntu)
```bash
# Add repository
sudo apt-get install wget gnupg
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | gpg --dearmor | sudo tee /usr/share/keyrings/trivy.gpg > /dev/null
echo "deb [signed-by=/usr/share/keyrings/trivy.gpg] https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main" | sudo tee -a /etc/apt/sources.list.d/trivy.list
# Install
sudo apt-get update
sudo apt-get install trivy
# Verify installation
trivy --version
```
#### Using Docker
```bash
# Run Trivy in container
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest image nginx:latest
# Scan Dockerfile
docker run --rm -v $(pwd):/app aquasec/trivy:latest config /app/Dockerfile
```
## Optional But Recommended Tools
### 5. Dive (Image Layer Analyzer)
Analyzes Docker image layers to optimize size.
```bash
# macOS
brew install dive
# Linux
wget https://github.com/wagoodman/dive/releases/download/v0.11.0/dive_0.11.0_linux_amd64.deb
sudo apt install ./dive_0.11.0_linux_amd64.deb
# Usage
dive nginx:latest
```
### 6. Docker Bench Security
Automated security audit for Docker deployments.
```bash
# Run security audit
docker run --rm --net host --pid host --userns host --cap-add audit_control \
-e DOCKER_CONTENT_TRUST=$DOCKER_CONTENT_TRUST \
-v /etc:/etc:ro \
-v /usr/bin/containerd:/usr/bin/containerd:ro \
-v /usr/bin/runc:/usr/bin/runc:ro \
-v /usr/lib/systemd:/usr/lib/systemd:ro \
-v /var/lib:/var/lib:ro \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
--label docker_bench_security \
docker/docker-bench-security
```
### 7. Snyk (Alternative Security Scanner)
```bash
# Install Snyk CLI
npm install -g snyk
# Authenticate
snyk auth
# Test Dockerfile
snyk container test nginx:latest
# Test Docker image
snyk container test myapp:latest --file=Dockerfile
```
## Configuration Files Setup
### Create .hadolint.yaml
```bash
cat > .hadolint.yaml << 'EOF'
---
ignored:
- DL3008 # Pin versions in apt-get (sometimes too strict)
- DL3013 # Pin versions in pip
- DL3018 # Pin versions in apk
override:
error:
- DL3002 # Last user should not be root
- DL3020 # Use COPY instead of ADD
warning:
- DL3003 # Use WORKDIR instead of cd
trustedRegistries:
- docker.io
- ghcr.io
- gcr.io
- quay.io
strict-labels: true
EOF
```
### Create .dclintrc.json
```bash
cat > .dclintrc.json << 'EOF'
{
"rules": {
"no-version-field": "error",
"require-quotes": "warning",
"service-name-case": ["error", "kebab-case"],
"no-duplicate-keys": "error",
"require-restart": "warning"
},
"exclude": [
"node_modules/**",
".git/**",
"dist/**"
]
}
EOF
```
### Create .dockerignore
```bash
cat > .dockerignore << 'EOF'
# Git
.git
.gitignore
.gitattributes
# CI/CD
.github
.gitlab-ci.yml
Jenkinsfile
# Documentation
README.md
CHANGELOG.md
docs/
# Dependencies
node_modules/
vendor/
__pycache__/
*.pyc
# Build artifacts
dist/
build/
target/
*.log
# IDE
.vscode/
.idea/
*.swp
*.swo
# Environment
.env
.env.local
*.pem
*.key
EOF
```
## Verification Script
Create a script to verify all tools are installed:
```bash
#!/bin/bash
# verify-tools.sh
echo "🔍 Checking Docker Validation Tools..."
echo ""
# Check Docker
if command -v docker &> /dev/null; then
echo "✅ Docker: $(docker --version)"
else
echo "❌ Docker: NOT INSTALLED"
fi
# Check Docker Compose
if docker compose version &> /dev/null; then
echo "✅ Docker Compose: $(docker compose version)"
else
echo "❌ Docker Compose: NOT INSTALLED"
fi
# Check Hadolint
if command -v hadolint &> /dev/null; then
echo "✅ Hadolint: $(hadolint --version)"
else
echo "⚠️ Hadolint: NOT INSTALLED (recommended)"
fi
# Check DCLint
if command -v dclint &> /dev/null; then
echo "✅ DCLint: $(dclint --version 2>&1 | head -1)"
else
echo "⚠️ DCLint: NOT INSTALLED (recommended)"
fi
# Check Trivy
if command -v trivy &> /dev/null; then
echo "✅ Trivy: $(trivy --version | head -1)"
else
echo "⚠️ Trivy: NOT INSTALLED (optional)"
fi
# Check Node.js (for DCLint)
if command -v node &> /dev/null; then
echo "✅ Node.js: $(node --version)"
else
echo "⚠️ Node.js: NOT INSTALLED (needed for DCLint)"
fi
echo ""
echo "📊 Installation Summary:"
echo " Required tools: Docker, Docker Compose"
echo " Recommended: Hadolint, DCLint"
echo " Optional: Trivy, Dive, Docker Bench"
```
Make it executable and run:
```bash
chmod +x verify-tools.sh
./verify-tools.sh
```
## Quick Start Commands
After installation, test the tools:
```bash
# Test Hadolint
echo 'FROM node:latest' > test.Dockerfile
hadolint test.Dockerfile
rm test.Dockerfile
# Test DCLint
echo 'services:
web:
image: nginx:latest' > test-compose.yml
dclint test-compose.yml
rm test-compose.yml
# Test Docker Compose validation
docker compose config --quiet
# Test Trivy (if installed)
trivy image nginx:latest
# Test full validation
./validate-docker.sh # (if you have the validation script)
```
## Troubleshooting
### Hadolint: Command not found
```bash
# Check if binary exists
ls -la /usr/local/bin/hadolint
# Check PATH
echo $PATH
# Add to PATH if needed
export PATH="/usr/local/bin:$PATH"
echo 'export PATH="/usr/local/bin:$PATH"' >> ~/.bashrc
```
### DCLint: Module not found
```bash
# Check npm global prefix
npm config get prefix
# If not in PATH, add it
export PATH="$(npm config get prefix)/bin:$PATH"
# Or use npx
npx dclint docker-compose.yml
```
### Docker Compose: version command not recognized
```bash
# Check Docker Compose version
docker compose version # New (v2)
docker-compose --version # Old (v1, deprecated)
# If using v1, upgrade to v2
# Follow Docker documentation for your OS
```
### Permission Denied (Linux)
```bash
# Add user to docker group
sudo usermod -aG docker $USER
newgrp docker
# Verify
docker ps
```
## CI/CD Integration
### GitHub Actions
Already includes all tools in standard ubuntu-latest runner:
```yaml
- name: Validate Docker configs
run: |
docker --version
docker compose version
# Install additional tools if needed
```
### GitLab CI
```yaml
before_script:
- apt-get update
- apt-get install -y wget
- wget -O /usr/local/bin/hadolint https://github.com/hadolint/hadolint/releases/download/v2.12.0/hadolint-Linux-x86_64
- chmod +x /usr/local/bin/hadolint
```
## Update Tools
Keep tools up to date:
```bash
# Update Hadolint (macOS)
brew upgrade hadolint
# Update DCLint
npm update -g docker-compose-linter
# Update Trivy (macOS)
brew upgrade trivy
# Update Docker Desktop
# Use built-in updater or:
brew upgrade --cask docker
```
---
**All tools installed? Run `./verify-tools.sh` to confirm!**
+351
View File
@@ -0,0 +1,351 @@
# Docker Validation Checklist
Complete checklist for validating Docker configurations. Use this as a reference when performing manual validation.
## Dockerfile Validation Checklist
### Base Image (Critical)
- [ ] No `:latest` tags used
- [ ] Specific version pinned (e.g., `node:20.11.0-alpine`)
- [ ] Uses minimal base image (alpine, slim, or distroless variants)
- [ ] Trusted registry used (docker.io, ghcr.io, gcr.io, quay.io)
- [ ] Base image is actively maintained and supported
### Multi-Stage Build (High Priority)
- [ ] At least 2 stages for production builds (build + runtime)
- [ ] All stages named with `AS` keyword
- [ ] Artifacts copied between stages using `COPY --from=`
- [ ] Final stage uses minimal base image
- [ ] Build tools NOT present in final stage
- [ ] Only necessary files in final image
### Security (Critical)
- [ ] `USER` directive present (non-root user specified)
- [ ] Last `USER` is NOT root or 0
- [ ] No secrets in ENV variables
- [ ] No secrets in COPY/ADD commands
- [ ] No secrets in RUN commands
- [ ] No hardcoded passwords or API keys
- [ ] Uses `--chown` when copying files for non-root user
### Directory & Paths (High Priority)
- [ ] `WORKDIR` uses absolute paths (not relative)
- [ ] No use of `cd` in RUN commands
- [ ] `.dockerignore` file present
- [ ] Build context is minimal (excludes unnecessary files)
### Layer Optimization (Medium Priority)
- [ ] RUN commands combined where logical (using `&&`)
- [ ] Package manager cache cleaned (apt, apk, yum)
- [ ] Dependency files copied before source code (for better caching)
- [ ] Multi-line commands use backslash continuation
- [ ] No unnecessary layers created
### Package Management (High Priority)
- [ ] Package versions pinned (apt-get, apk, yum)
- [ ] Package cache cleaned after installation
- [ ] Uses `--no-install-recommends` for apt-get
- [ ] Uses `--virtual` for build dependencies in alpine
- [ ] Python: Versions pinned in requirements.txt
- [ ] Node: Uses `npm ci` instead of `npm install`
### Best Practices (Medium Priority)
- [ ] `HEALTHCHECK` instruction defined
- [ ] Uses `COPY` instead of `ADD` (unless extracting archives)
- [ ] `CMD` and `ENTRYPOINT` use JSON notation
- [ ] Labels included (maintainer, version, description)
- [ ] Appropriate EXPOSE directives for documented ports
- [ ] ENV variables clearly defined
- [ ] Build args used for customization points
### Documentation (Low Priority)
- [ ] Comments explain complex operations
- [ ] Each stage has descriptive comment
- [ ] Unusual patterns are documented
- [ ] Maintainer/author documented in labels
## Hadolint Rule Reference
| Rule | Description | Severity | Check |
|------|-------------|----------|-------|
| DL3000 | Use absolute WORKDIR | Error | [ ] |
| DL3001 | Some commands should not be used | Warning | [ ] |
| DL3002 | Last USER should not be root | Error | [ ] |
| DL3003 | Use WORKDIR to switch directories | Warning | [ ] |
| DL3006 | Always tag image explicitly | Warning | [ ] |
| DL3007 | Using latest is prone to errors | Warning | [ ] |
| DL3008 | Pin versions in apt-get install | Warning | [ ] |
| DL3009 | Delete apt-get lists after installing | Info | [ ] |
| DL3013 | Pin versions in pip | Warning | [ ] |
| DL3014 | Use -y flag with apt-get | Warning | [ ] |
| DL3015 | Avoid additional packages | Info | [ ] |
| DL3016 | Pin versions in npm | Warning | [ ] |
| DL3018 | Pin versions in apk add | Warning | [ ] |
| DL3019 | Use --no-cache with apk add | Info | [ ] |
| DL3020 | Use COPY instead of ADD | Error | [ ] |
| DL3022 | COPY --from should reference stage | Error | [ ] |
| DL3025 | Use JSON for CMD and ENTRYPOINT | Warning | [ ] |
## Docker Compose Validation Checklist
### Modern Syntax (Critical)
- [ ] NO `version` field present (obsolete since Compose v2.27.0)
- [ ] File uses modern Compose Specification syntax
- [ ] Compatible with Docker Compose v2.27.0+
### Service Configuration (High Priority)
- [ ] All services have specific image tags (no `:latest`)
- [ ] Restart policies defined (`restart: unless-stopped`)
- [ ] Service dependencies specified (`depends_on`)
- [ ] Container names specified (optional but recommended)
- [ ] All services have descriptive names (kebab-case)
### Health Checks (High Priority)
- [ ] Critical services have health checks
- [ ] Health check intervals are reasonable
- [ ] Health check timeout values appropriate
- [ ] Start period allows for initialization
- [ ] Retries configured for reliability
### Resource Management (Medium Priority)
- [ ] Resource limits defined (memory, CPU)
- [ ] Resource reservations specified
- [ ] PID limits set (if applicable)
- [ ] Ulimits configured (if needed)
### Networking (High Priority)
- [ ] Custom networks defined (not default bridge)
- [ ] Network drivers specified
- [ ] Network isolation implemented
- [ ] Port mappings use host IP when needed
- [ ] Internal networks used for backend services
### Volumes & Persistence (High Priority)
- [ ] Named volumes used for persistence
- [ ] Volume drivers specified
- [ ] Bind mounts use absolute paths
- [ ] Volume permissions appropriate
- [ ] No sensitive data in bind mounts
- [ ] Volumes section defines named volumes
### Environment & Configuration (Critical)
- [ ] Environment variables properly defined
- [ ] No hardcoded secrets in compose file
- [ ] `.env` file used for configuration
- [ ] Secrets managed with Docker secrets or external
- [ ] ENV files specified with `env_file`
### Security (Critical)
- [ ] No `privileged: true` (unless absolutely necessary)
- [ ] Capabilities properly configured
- [ ] User/group specified for services
- [ ] Read-only root filesystem (where applicable)
- [ ] Security options configured
- [ ] AppArmor/SELinux profiles defined
### Logging (Medium Priority)
- [ ] Logging drivers configured
- [ ] Log rotation configured
- [ ] Log size limits set
- [ ] Appropriate log drivers for environment
### Build Configuration (if using build)
- [ ] Build context clearly specified
- [ ] Build args defined if needed
- [ ] Dockerignore file present
- [ ] Target stage specified for multi-stage
- [ ] Cache from configured for faster builds
## Multi-Stage Build Specific Checks
### Stage Structure
- [ ] Build stage uses full toolchain image
- [ ] Build stage installs ALL dependencies
- [ ] Build stage compiles/builds artifacts
- [ ] Runtime stage uses minimal image
- [ ] Runtime stage copies only artifacts
- [ ] Runtime stage installs only runtime deps
### Node.js Multi-Stage
- [ ] Build stage: `npm ci` (not `npm install`)
- [ ] Build stage: `npm run build`
- [ ] Build stage: `npm run test` (optional)
- [ ] Runtime stage: `npm ci --only=production`
- [ ] Runtime stage: Copies from builder `dist/build` folder
- [ ] Runtime stage: Uses alpine variant
### Python Multi-Stage
- [ ] Build stage: Compiles wheels
- [ ] Build stage: Installs build dependencies
- [ ] Build stage: Creates virtual environment
- [ ] Runtime stage: Installs pre-built wheels
- [ ] Runtime stage: Minimal Python image (alpine/slim)
- [ ] Runtime stage: No compiler or build tools
### Go Multi-Stage
- [ ] Build stage: Full Go image
- [ ] Build stage: CGO_ENABLED=0 for static binary
- [ ] Build stage: Builds binary
- [ ] Runtime stage: `scratch` or `distroless`
- [ ] Runtime stage: Only binary copied
- [ ] Runtime stage: Certificates copied if needed
## Security Checklist
### Image Security
- [ ] Base images scanned for vulnerabilities
- [ ] No images older than 6 months without review
- [ ] Images from trusted sources only
- [ ] Image digests used for critical deployments
- [ ] Regular security updates applied
### Runtime Security
- [ ] Runs as non-root user (UID > 0)
- [ ] Minimal capabilities granted
- [ ] No unnecessary privileges
- [ ] Read-only root filesystem where possible
- [ ] Temporary directories properly configured
### Network Security
- [ ] Only necessary ports exposed
- [ ] Internal networks for backend communication
- [ ] No host network mode (unless required)
- [ ] Firewall rules configured
- [ ] TLS/SSL for external communications
### Data Security
- [ ] No secrets in image layers
- [ ] Secrets managed via secrets management
- [ ] Sensitive volumes properly protected
- [ ] Encryption at rest configured
- [ ] Backup strategy for persistent data
### Access Control
- [ ] Least privilege principle applied
- [ ] Appropriate user permissions
- [ ] No root access to containers
- [ ] Host resources properly isolated
- [ ] Volume mounts restricted
## CI/CD Integration Checklist
### Pre-commit Validation
- [ ] Pre-commit hook validates Dockerfiles
- [ ] Pre-commit hook checks Compose files
- [ ] Hook checks for obsolete version field
- [ ] Hook runs Hadolint/DCLint
- [ ] Hook prevents commits with critical issues
### Pipeline Validation
- [ ] Hadolint runs on all Dockerfiles
- [ ] Docker Compose config validation
- [ ] DCLint runs on Compose files
- [ ] Security scanning integrated (Trivy, Snyk)
- [ ] Build tests before merge
- [ ] Automated PR comments with issues
### Deployment Validation
- [ ] Validation runs before deployment
- [ ] Rollback on validation failure
- [ ] Health checks verified post-deployment
- [ ] Smoke tests after deployment
- [ ] Monitoring alerts configured
## Common Issue Quick Reference
### ❌ Using :latest Tag
**Check:** `grep -r ":latest" Dockerfile docker-compose.yml`
**Fix:** Pin specific version (e.g., `nginx:1.24-alpine`)
### ❌ Obsolete Version Field
**Check:** `grep "^version:" docker-compose.yml`
**Fix:** Remove the entire `version:` line
### ❌ Running as Root
**Check:** `grep "^USER" Dockerfile | tail -1`
**Fix:** Add `USER <non-root-user>` before CMD/ENTRYPOINT
### ❌ No Multi-Stage Build
**Check:** `grep -c "^FROM" Dockerfile`
**Fix:** Implement at least 2 stages
### ❌ Package Cache Not Cleaned
**Check:** Look for apt/apk without cleanup
**Fix:** Add `rm -rf /var/lib/apt/lists/*` or `--no-cache`
### ❌ Using ADD Instead of COPY
**Check:** `grep "^ADD" Dockerfile`
**Fix:** Replace with `COPY` unless extracting archives
### ❌ No Health Check
**Check:** `grep "HEALTHCHECK" Dockerfile`
**Fix:** Add appropriate HEALTHCHECK instruction
### ❌ No Restart Policy
**Check:** `grep "restart:" docker-compose.yml`
**Fix:** Add `restart: unless-stopped` to services
## Validation Priority Matrix
| Priority | Dockerfile | Docker Compose | Multi-Stage | Security |
|----------|-----------|----------------|-------------|----------|
| CRITICAL | No :latest, USER set | No version field | N/A | Non-root user |
| HIGH | HEALTHCHECK, WORKDIR | Restart policy, Health checks | 2+ stages | No secrets |
| MEDIUM | Layer optimization | Resource limits | Named stages | Minimal image |
| LOW | Comments, Labels | Logging config | Optimization | Hardening |
## Tool-Specific Validation
### Hadolint Configuration (.hadolint.yaml)
```yaml
ignored:
- DL3008 # Pin apt versions (too strict for some use cases)
override:
error:
- DL3002 # Last USER must not be root
- DL3020 # Use COPY not ADD
trustedRegistries:
- docker.io
- ghcr.io
- gcr.io
```
### DCLint Configuration (.dclintrc.json)
```json
{
"rules": {
"no-version-field": "error",
"require-quotes": "warning",
"no-duplicate-keys": "error"
}
}
```
## Quick Validation Commands
```bash
# Validate Dockerfile
hadolint Dockerfile
# Validate Docker Compose
docker compose config --quiet
# Check for obsolete version field
grep "^version:" docker-compose.yml
# Count FROM statements (multi-stage check)
grep -c "^FROM" Dockerfile
# Check final USER
grep "^USER" Dockerfile | tail -1
# Find :latest tags
grep -r ":latest" .
# Full validation
./validate-docker.sh
```
---
**Use this checklist to ensure comprehensive validation of all Docker configurations.**
File diff suppressed because it is too large Load Diff