π¨ The Problem with Single-Stage Builds
- The final image contains unnecessary dependencies (e.g., compilers, libraries, build tools).
- This makes the image large, slow to deploy, and less secure.
β The Solution: Multi-Stage Builds
- First stage (Build Stage): Installs dependencies, compiles the app.
- Second stage (Runtime Stage): Copies only the necessary files, keeping the image small and secure.
π Multi-Stage Build for a Python FastAPI App
This example optimizes a Python FastAPI application.
# π’ Stage 1: Build Environment (Full Python + Dependencies)
FROM python:3.10 AS builder
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# π’ Stage 2: Production Image (Minimal Python)
FROM python:3.10-slim AS runner
WORKDIR /app
# Copy only necessary files from the builder stage
COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages
COPY . .
# Set environment variables
ENV PORT=5000
# Expose port and run the application
EXPOSE 5000
CMD ["python", "app.py"]
π Why is This Better?
β
Smaller Image: Only includes necessary runtime files.
β
Faster Build: Dependencies are installed only once in the builder stage.
β
More Secure: The final image does not contain compilers or extra tools.
β Multi-Stage Build for a Java Spring Boot App
Since Java requires a JDK for compilation but only needs a JRE for runtime, a multi-stage build is ideal.
# π’ Stage 1: Build Application (Using JDK)
FROM maven:3.8.6-openjdk-17 AS builder
WORKDIR /app
# Copy source code and build the JAR file
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests
# π’ Stage 2: Production Image (Using JRE)
FROM openjdk:17-jdk-slim AS runner
WORKDIR /app
# Copy only the compiled JAR file
COPY --from=builder /app/target/myapp.jar myapp.jar
# Run the application
EXPOSE 8080
CMD ["java", "-jar", "myapp.jar"]
π Why is This Better?
β
Smaller Image: Uses jdk-slim
, avoiding unnecessary files.
β
Faster Startup: No need for Maven in production.
β
Better Performance: Minimal runtime environment.
π Single-Stage vs. Multi-Stage Builds: A Quick Comparison
Feature | Single-Stage Build | Multi-Stage Build |
---|---|---|
Image Size | Large (includes build tools) | Small (only runtime files) |
Security | More vulnerable (contains unnecessary tools) | More secure (minimal runtime) |
Performance | Slower startup | Faster startup |
Best For | Dev/test environments | Production deployments |
β When Should You Use Multi-Stage Builds?
- If your app has build-time dependencies (e.g., Maven, Node.js, Python libraries).
- If you want a smaller and more secure image.
- If you donβt need build tools in the final image.
Top comments (0)