$npx -y skills add github/awesome-copilot --skill multi-stage-dockerfileCreate optimized multi-stage Dockerfiles for any language or framework
| 1 | Your goal is to help me create efficient multi-stage Dockerfiles that follow best practices, resulting in smaller, more secure container images. |
| 2 | |
| 3 | ## Multi-Stage Structure |
| 4 | |
| 5 | - Use a builder stage for compilation, dependency installation, and other build-time operations |
| 6 | - Use a separate runtime stage that only includes what's needed to run the application |
| 7 | - Copy only the necessary artifacts from the builder stage to the runtime stage |
| 8 | - Use meaningful stage names with the `AS` keyword (e.g., `FROM node:18 AS builder`) |
| 9 | - Place stages in logical order: dependencies → build → test → runtime |
| 10 | |
| 11 | ## Base Images |
| 12 | |
| 13 | - Start with official, minimal base images when possible |
| 14 | - Specify exact version tags to ensure reproducible builds (e.g., `python:3.11-slim` not just `python`) |
| 15 | - Consider distroless images for runtime stages where appropriate |
| 16 | - Use Alpine-based images for smaller footprints when compatible with your application |
| 17 | - Ensure the runtime image has the minimal necessary dependencies |
| 18 | |
| 19 | ## Layer Optimization |
| 20 | |
| 21 | - Organize commands to maximize layer caching |
| 22 | - Place commands that change frequently (like code changes) after commands that change less frequently (like dependency installation) |
| 23 | - Use `.dockerignore` to prevent unnecessary files from being included in the build context |
| 24 | - Combine related RUN commands with `&&` to reduce layer count |
| 25 | - Consider using COPY --chown to set permissions in one step |
| 26 | |
| 27 | ## Security Practices |
| 28 | |
| 29 | - Avoid running containers as root - use `USER` instruction to specify a non-root user |
| 30 | - Remove build tools and unnecessary packages from the final image |
| 31 | - Scan the final image for vulnerabilities |
| 32 | - Set restrictive file permissions |
| 33 | - Use multi-stage builds to avoid including build secrets in the final image |
| 34 | |
| 35 | ## Performance Considerations |
| 36 | |
| 37 | - Use build arguments for configuration that might change between environments |
| 38 | - Leverage build cache efficiently by ordering layers from least to most frequently changing |
| 39 | - Consider parallelization in build steps when possible |
| 40 | - Set appropriate environment variables like NODE_ENV=production to optimize runtime behavior |
| 41 | - Use appropriate healthchecks for the application type with the HEALTHCHECK instruction |