Sobes.tech
Senior

What are the best practices for reducing Docker image size and speeding up its build?

sobes.tech AI

Answer from AI

The following best practices exist for reducing the size of Docker images and speeding up their build:

  • Use minimal base images: for example, alpine instead of ubuntu or debian — this significantly reduces size.

  • Multi-stage builds: allow separating the build stage from the final image, resulting in only necessary artifacts being included in the final image.

  • Layer caching: structure the Dockerfile correctly so that frequently changing commands are at the bottom, and unchanging ones are at the top, to utilize cache and avoid rebuilding all layers.

  • Minimize the number of layers: combine RUN commands using && to reduce the number of layers.

  • Remove temporary files and caches inside the image after installing packages, for example, cleaning apt-get clean or deleting temporary build files.

  • Use .dockerignore to exclude unnecessary files and folders from the build context.

  • Optimize dependencies: install only necessary packages and libraries.

An example of a multi-stage build for a Java application:

# Build stage
FROM maven:3.8.5-openjdk-17 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests

# Final image
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY --from=build /app/target/myapp.jar ./myapp.jar
CMD ["java", "-jar", "myapp.jar"]

This approach allows creating a compact and quickly built image.