Real-life proven strategies to reduce docker image size

Shristi
2 min readNov 10, 2023

--

Photo by Rubaitul Azad on Unsplash

Reducing the size of Docker images is crucial for optimizing resource usage, improving deployment times, and enhancing security.

Here are some proven strategies to reduce Docker image size:

1. Use Alpine-based Images:

- Alpine Linux is a lightweight and security-focused distribution. Choosing Alpine-based images as your base image can significantly reduce the image size compared to larger distributions.

FROM alpine:latest

2. Multi-stage Builds:

  • Use multi-stage builds to separate the build environment from the runtime environment. This helps discard unnecessary build dependencies and only include the final artifacts.
# Build Stage
FROM node:14 AS build
WORKDIR /app

COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Production-ready Stage
FROM nginx:alpine
WORKDIR /usr/share/nginx/html

COPY --from=build /app/build /usr/share/nginx/html

3. Minimize Layers:

- Combine multiple commands into a single RUN instruction to minimize the number of layers. This reduces the size of the image and improves caching efficiency.

FROM debian:bullseye

RUN apt-get update && \
apt-get install -y package1 package2 && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*

4. Clean Up After Installations:

  • Remove unnecessary files and cleanup package managers to reduce image size. This is important for package managers like apt, yum, or apk.
FROM debian:bullseye

RUN apt-get update && \
apt-get install -y package1 package2 && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*

5. Use .dockerignore File:

- Create a `.dockerignore` file to exclude unnecessary files and directories from being copied into the Docker image. This reduces the amount of data transferred to the image.

# .dockerignore
node_modules
.git
.vscode

6. Optimize Dockerfile Instructions:

- Be mindful of the order of instructions in your Dockerfile. Place instructions that are less likely to change towards the top to leverage Docker’s layer caching mechanism.

7. Choose Smaller Base Images:

  • Select the smallest base image that meets your application’s requirements. For example, if you need Python, choose a slim version or Alpine-based image.
FROM python:3.9-slim

8. Use Build Args to Parameterize:

  • Use build arguments to parameterize your Dockerfile. This can allow you to conditionally include/exclude certain dependencies during the build process.
ARG APP_VERSION=latest
FROM myapp-base:${APP_VERSION}

Remember that the effectiveness of these strategies may vary depending on the specific requirements and nature of your application. It’s a good practice to experiment and profile your images to find the best combination of optimizations for your use case.

--

--