Prompt Details
Model
Chat - (gpt-5.2)
Token size
302
Example input
[app_type]: Python FastAPI fraud-detection microservice
[base_image]: python:3.11-slim
[security_level]: CIS Docker Benchmark–aligned hardened profile
[ci_cd_target]: GitHub Actions release-branch pipeline
Example output
1. Optimized Multi-Stage Dockerfile
# syntax=docker/dockerfile:1.7
############################
# Build arguments (global)
############################
ARG PYTHON_VERSION=3.11
ARG BASE_IMAGE=python:${PYTHON_VERSION}-slim
ARG APP_HOME=/app
############################
# Stage 1 — Base builder
############################
FROM ${BASE_IMAGE} AS builder
ARG APP_HOME
WORKDIR ${APP_HOME}
# Prevent Python from writing pyc files
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Install minimal build dependencies
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
build-essential \
gcc \
curl \
&& rm -rf /var/lib/apt/lists/*
# Create virtual environment for isolation
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
# Copy dependency manifests first (improves caching)
COPY requirements.txt .
# Install dependencies with BuildKit cache
RUN --mount=type=cache,target=/root/.cache/pip \
pip install --upgrade pip \
&& pip install --no-cache-dir -r requirements.txt
############################
# Stage 2 — Application build
############################
FROM builder AS build
ARG APP_HOME
WORKDIR ${APP_HOME}
# Copy application source
COPY . .
# Optional: compile Python bytecode for faster startup
RUN python -m compileall .
############################
# Stage 3 — Minimal runtime
############################
FROM ${BASE_IMAGE} AS runtime
ARG APP_HOME
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PATH="/opt/venv/bin:$PATH"
# Create non-root user (CIS Docker Benchmark aligned)
RUN groupadd --system appgroup \
&& useradd --system --gid appgroup --create-home appuser
# Copy virtual environment from builder
COPY --from=builder /opt/venv /opt/venv
# Copy only runtime files
WORKDIR ${APP_HOME}
COPY --from=build ${APP_HOME} ${APP_HOME}
# Restrict permissions
RUN chown -R appuser:appgroup ${APP_HOME}
USER appuser
EXPOSE 8000
# Healthcheck for service monitoring
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
# Run FastAPI via Uvicorn
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
---
2. Explanation of Build Stages
Stage 1 — Builder
Purpose:
Installs build dependencies required for compiling Python packages.
Creates a virtual environment for deterministic dependency isolation.
Installs dependencies using cached pip layers.
Benefits:
Build tools never reach the final runtime image.
Faster rebuilds due to dependency-layer caching.
---
Stage 2 — Application Build
Purpose:
Copies the application source code.
Compiles Python files to bytecode (optional).
Benefits:
Separates dependency install from source changes.
Improves incremental build performance.
---
Stage 3 — Runtime Image
Purpose:
Produces a minimal runtime container.
Includes only:
Python runtime
virtual environment
application code
Security Improvements:
Non-root user
minimal system packages
reduced attack surface.
---
3. Security Hardening Checklist
Recommended hardening practices aligned with CIS Docker Benchmark principles.
Container Runtime Security
Run container as non-root user
Avoid privileged containers
Use read-only filesystem when possible
Drop Linux capabilities:
docker run \
--cap-drop=ALL \
--read-only \
--tmpfs /tmp \
fraud-service
---
Dependency Security
Pin dependencies in requirements.txt
Example:
fastapi==0.110.0
uvicorn[standard]==0.27.1
pydantic==2.6.1
---
Base Image Policy
Use trusted base images only:
python:3.11-slim
distroless/python
Regularly update base images in CI.
---
Secrets Management
Never store secrets in Dockerfiles.
Use BuildKit secrets:
RUN --mount=type=secret,id=pip_token \
export TOKEN=$(cat /run/secrets/pip_token) && pip install private_pkg
Build command:
DOCKER_BUILDKIT=1 docker build \
--secret id=pip_token,src=.pip_token .
---
4. Caching Strategy
Optimized caching significantly reduces build time.
Layer Strategy
Correct layering order:
1. Base image
2. System dependencies
3. Python dependencies
4. Application code
Because application code changes most often.
---
Pip Cache Mount
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt
Benefits:
Reuses downloaded packages between builds
Faster CI pipelines.
---
Docker Build Cache
Use registry-based caching in CI:
docker buildx build \
--cache-from=type=registry,ref=myrepo/app:buildcache \
--cache-to=type=registry,ref=myrepo/app:buildcache,mode=max
---
5. Image Size Optimization Techniques
Remove unnecessary packages
apt-get install --no-install-recommends
---
Clean package lists
rm -rf /var/lib/apt/lists/*
---
Multi-stage builds
Keeps only runtime dependencies.
---
Use slim Python base
python:3.11-slim
instead of
python:3.11
---
Exclude unnecessary files via .dockerignore
Example:
.git
tests
docs
node_modules
__pycache__
*.pyc
.env
---
6. Vulnerability Scanning Integration
Integrate container scanning in CI using tools like:
Trivy
Grype
Docker Scout
Example using Trivy:
trivy image myorg/fraud-service:latest
Fail pipeline on high severity vulnerabilities:
trivy image --exit-code 1 --severity HIGH,CRITICAL myimage
---
7. SBOM Generation Guidance
Software Bill of Materials improves supply-chain transparency.
Recommended tools:
Syft
Docker SBOM
CycloneDX
Example:
syft myorg/fraud-service:latest -o cyclonedx-json > sbom.json
Benefits:
Dependency traceability
compliance readiness
vulnerability auditing.
---
8. CI/CD Integration Snippet (GitHub Actions)
Example job compatible with release-branch pipelines.
name: build-container
on:
push:
branches:
- release/*
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
security-events: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to container registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ghcr.io/myorg/fraud-service:${{ github.sha }}
cache-from: type=registry,ref=ghcr.io/myorg/fraud-service:buildcache
cache-to: type=registry,ref=ghcr.io/myorg/fraud-service:buildcache,mode=max
- name: Vulnerability scan
uses: aquasecurity/trivy-action@master
with:
image-ref: ghcr.io/myorg/fraud-service:${{ github.sha }}
---
9. Operational Best Practices
For production FastAPI services:
Recommended runtime settings
uvicorn app.main:app \
--workers 4 \
--host 0.0.0.0 \
--port 8000
Or run behind:
Nginx
Envoy
Kubernetes Ingress.
---
Resource limits
Set CPU and memory limits in orchestration layer:
cpu: 500m
memory: 512Mi
---
Logging
Prefer stdout structured logs for observability.
---
✅ This architecture provides:
deterministic builds
reduced attack surface
faster CI builds
minimal runtime images
supply-chain visibility
compatibility with hardened container policies.
---
If you'd like, I can also generate an ultra-secure variant used by fintech/ML fraud detection systems (distroless + rootless + signed images + SLSA provenance) which is typically used in high-security production environments.
By purchasing this prompt, you agree to our terms of service
GPT-5.2
A concise, production-focused prompt that helps produce smaller, faster, and more secure container images while keeping builds reproducible and auditable.
It solves common pain points—bloat, slow caches, secret leakage, and unclear supply chains—by generating hardened multi-stage Dockerfiles, SBOM guidance, and CI/CD integration patterns.
Ideal for microservices, legacy app containerization, CI pipelines, platform teams, and edge/serverless deployments that need consistent, auditable images...
...more
Added over 1 month ago
