performing-container-image-hardening

mukul975/Anthropic-Cybersecurity-Skills · updated May 25, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills install mukul975/Anthropic-Cybersecurity-Skills/performing-container-image-hardening
0 commentsdiscussion
summary

This skill covers hardening container images by minimizing attack surface, removing unnecessary packages, implementing multi-stage builds, configuring non-root users, and applying CIS Docker Benchmark recommendations to produce secure production-ready images.

skill.md
name
performing-container-image-hardening
description
'This skill covers hardening container images by minimizing attack surface, removing unnecessary packages, implementing multi-stage builds, configuring non-root users, and applying CIS Docker Benchmark recommendations to produce secure production-ready images. '
domain
cybersecurity
subdomain
devsecops
tags
- devsecops - cicd - container-hardening - docker - cis-benchmark - secure-sdlc
version
1.0.0
author
mahipal
license
Apache-2.0
nist_csf
- PR.PS-01 - GV.SC-07 - ID.IM-04 - PR.PS-04

Performing Container Image Hardening

When to Use

  • When building production container images that need minimal attack surface
  • When compliance requires CIS Docker Benchmark adherence for container configurations
  • When reducing image size to minimize vulnerability exposure from unused packages
  • When implementing defense-in-depth for containerized workloads
  • When migrating from fat base images to distroless or minimal images

Do not use for runtime container security monitoring (use Falco), for host-level Docker daemon hardening (use CIS Docker Benchmark host checks), or for container orchestration security (use Kubernetes security scanning).

Prerequisites

  • Docker or BuildKit for multi-stage builds
  • Base image options: distroless, Alpine, slim, or scratch
  • Container scanning tool (Trivy) for validation
  • CIS Docker Benchmark reference

Workflow

Step 1: Use Multi-Stage Builds to Minimize Image Size

# Build stage with all dependencies
FROM python:3.12-bookworm AS builder
WORKDIR /build
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
COPY src/ ./src/
RUN python -m compileall src/

# Production stage with minimal base
FROM python:3.12-slim-bookworm AS production
RUN apt-get update && \
    apt-get install -y --no-install-recommends libpq5 && \
    rm -rf /var/lib/apt/lists/* && \
    apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false

COPY --from=builder /install /usr/local
COPY --from=builder /build/src /app/src

RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser
RUN chown -R appuser:appuser /app

USER appuser
WORKDIR /app

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')" || exit 1

EXPOSE 8080
ENTRYPOINT ["python", "-m", "src.main"]

Step 2: Use Distroless Base Images

# Go application with distroless
FROM golang:1.22 AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /server .

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /server /server
USER nonroot:nonroot
ENTRYPOINT ["/server"]

Step 3: Remove Unnecessary Components

# Hardened image checklist
FROM ubuntu:24.04 AS base

RUN apt-get update && \
    apt-get install -y --no-install-recommends \
      ca-certificates \
      libssl3 && \
    # Remove package manager to prevent runtime package installation
    apt-get purge -y --auto-remove apt dpkg && \
    rm -rf /var/lib/apt/lists/* \
           /var/cache/apt/* \
           /tmp/* \
           /var/tmp/* \
           /usr/share/doc/* \
           /usr/share/man/* \
           /usr/share/info/* \
           /root/.cache

# Remove shells if not needed
RUN rm -f /bin/sh /bin/bash /usr/bin/sh 2>/dev/null || true

# Remove setuid/setgid binaries
RUN find / -perm /6000 -type f -exec chmod a-s {} + 2>/dev/null || true

Step 4: Configure Read-Only Filesystem

# Kubernetes deployment with read-only root filesystem
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hardened-app
spec:
  template:
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 65534
        fsGroup: 65534
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: app
          image: app:hardened
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: tmp
              mountPath: /tmp
            - name: cache
              mountPath: /app/cache
      volumes:
        - name: tmp
          emptyDir:
            sizeLimit: 100Mi
        - name: cache
          emptyDir:
            sizeLimit: 50Mi

Step 5: Pin Base Image by Digest

# Pin to exact image digest for reproducibility
FROM python:3.12-slim-bookworm@sha256:abcdef1234567890 AS production
# This ensures the exact same base image is used every time

Step 6: Validate Hardening with Automated Scanning

# Scan hardened image with Trivy
trivy image --severity HIGH,CRITICAL hardened-app:latest

# Check CIS Docker Benchmark compliance
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
  aquasec/docker-bench-security

# Verify no root processes
docker run --rm hardened-app:latest whoami
# Expected: appuser (NOT root)

# Verify read-only filesystem
docker run --rm hardened-app:latest touch /test 2>&1
# Expected: Read-only file system error

Key Concepts

TermDefinition
Multi-Stage BuildDocker build technique using multiple FROM stages to separate build and runtime, reducing final image size
DistrolessGoogle-maintained minimal container images containing only the application and runtime dependencies
Non-Root UserRunning container processes as unprivileged user to limit impact of container escape exploits
Read-Only RootMounting the container root filesystem as read-only to prevent runtime modification
Image DigestSHA256 hash uniquely identifying an exact image version, more precise than mutable tags
Scratch ImageEmpty Docker base image used for statically compiled binaries requiring no OS
Security ContextKubernetes pod/container-level security settings controlling privileges, filesystem, and capabilities

Tools & Systems

  • Docker BuildKit: Advanced Docker build engine supporting multi-stage builds and build secrets
  • Distroless Images: Google's minimal container base images (static, base, java, python, nodejs)
  • docker-bench-security: Script checking CIS Docker Benchmark compliance
  • Trivy: Container image vulnerability and misconfiguration scanner
  • Hadolint: Dockerfile linter enforcing best practices

Common Scenarios

Scenario: Reducing a 1.2GB Python Image to Under 150MB

Context: A data science team uses python:3.12 as base image (1.2GB) with scientific computing packages. The image has 200+ known CVEs from unnecessary system packages.

Approach:

  1. Switch to python:3.12-slim-bookworm as base (150MB) and install only required system libraries
  2. Use multi-stage build: compile C extensions in builder stage, copy wheels to production
  3. Pin numpy, pandas, and scipy to pre-built wheels to avoid build dependencies in production
  4. Remove pip, setuptools, and wheel from the final image
  5. Create non-root user and set filesystem permissions
  6. Validate with Trivy: expect CVE count to drop from 200+ to under 20

Pitfalls: Some Python packages require shared libraries at runtime (libgomp, libstdc++). Test the application thoroughly after removing system packages. Alpine-based images use musl libc which can cause compatibility issues with numpy and pandas.

Output Format

Container Image Hardening Report
==================================
Image: app:hardened
Base: python:3.12-slim-bookworm
Date: 2026-02-23

SIZE COMPARISON:
  Before hardening: 1,247 MB (python:3.12)
  After hardening:  143 MB  (python:3.12-slim + multi-stage)
  Reduction: 88.5%

SECURITY CHECKS:
  [PASS] Non-root user configured (appuser:1000)
  [PASS] HEALTHCHECK instruction present
  [PASS] No setuid/setgid binaries found
  [PASS] Package manager removed
  [PASS] Base image pinned by digest
  [PASS] No shell access (/bin/sh removed)
  [WARN] /tmp writable (emptyDir mounted)

VULNERABILITY COMPARISON:
  Before: 234 CVEs (12 Critical, 45 High)
  After:  18 CVEs (0 Critical, 3 High)
  Reduction: 92.3%
how to use performing-container-image-hardening

How to use performing-container-image-hardening on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add performing-container-image-hardening
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills install mukul975/Anthropic-Cybersecurity-Skills/performing-container-image-hardening

The skills CLI fetches performing-container-image-hardening from GitHub repository mukul975/Anthropic-Cybersecurity-Skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/performing-container-image-hardening

Reload or restart Cursor to activate performing-container-image-hardening. Access the skill through slash commands (e.g., /performing-container-image-hardening) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.638 reviews
  • Anika Patel· Dec 24, 2024

    performing-container-image-hardening is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Pratham Ware· Dec 4, 2024

    performing-container-image-hardening fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Kiara Johnson· Dec 4, 2024

    Solid pick for teams standardizing on skills: performing-container-image-hardening is focused, and the summary matches what you get after install.

  • Yash Thakker· Nov 23, 2024

    Registry listing for performing-container-image-hardening matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Kofi Tandon· Nov 15, 2024

    Useful defaults in performing-container-image-hardening — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Dhruvi Jain· Oct 14, 2024

    performing-container-image-hardening reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Kofi Wang· Oct 6, 2024

    I recommend performing-container-image-hardening for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Advait Sethi· Sep 25, 2024

    performing-container-image-hardening reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Advait Shah· Sep 9, 2024

    performing-container-image-hardening fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Oshnikdeep· Sep 5, 2024

    I recommend performing-container-image-hardening for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

showing 1-10 of 38

1 / 4