---
name: containerfile
description: Write optimized multi-stage Containerfiles — layer caching, minimal base images, non-root users, build secrets, OCI compliance, image size reduction.
license: MIT
---
Create efficient multi-stage Containerfiles for smaller, more secure OCI images.
## Multi-Stage Structure- Use a builder stage for compilation, dependency installation, and build-time
operations
- Use a separate runtime stage with only what's needed to run the application
- Copy only necessary artifacts from builder to runtime
- Use meaningful stage names with `AS` (e.g., `FROM node:18 AS builder`)
- Order stages logically: dependencies → build → test → runtime
## Base Images- Use official, minimal base images when possible
- Specify exact versions for reproducibility (e.g., `python:3.11-slim`)
- Consider distroless images for runtime
- Use Alpine-based images for smaller footprints when compatible
- Ensure runtime image has minimal dependencies
## Layer Optimization- Organize commands to maximize layer caching
- Put frequently changing commands (code) after less frequent changes
(dependencies)
- Use `.dockerignore` to exclude unnecessary files from build context
- Combine related RUN commands with `&&` to reduce layers
- Use `COPY --chown` to set permissions in one step
## Security- Avoid running as root - use `USER` for non-root user
- Remove build tools and unnecessary packages from final image
- Scan final image for vulnerabilities
- Set restrictive file permissions
- Use multi-stage builds to exclude build secrets from final image
## Performance- Use `ARG` for environment-specific configuration
- Order layers from least to most frequently changing
- Set appropriate environment variables (e.g., `NODE_ENV=production`)
- Add HEALTHCHECK for application monitoring