OneBite.Dev - Coding blog in a bite size

reduce docker image size

Simple docker step by step how to reduce docker image size with explanation

Docker images can quickly grow in size, hindering their transfer and slowing down deployment. This article will showcase some effective ways to reduce Docker image size.

Start with a Small Base Image

Begin with a lightweight base image, such as Alpine, which is only 5MB. Larger base images like Ubuntu or Debian can unnecessarily increase the size of your image.

FROM alpine:3.7

Be Selective With Build Artefacts

Eliminate unnecessary files from the final image. Avoid adding non-essential build artifacts and debug tools.

ADD https://example.com/big-file /tmp/
RUN cp /tmp/big-file /app/

Chain Your Commands

Try to chain as many commands as possible in one Docker layer. This technique, however, can make the Dockerfile harder to read.

RUN command1 && command2 && command3

Use .dockerignore File

Use a .dockerignore file to exclude irrelevant files and directories. This file works same as .gitignore.

.dockerignore file sample:

**/*.pyc
**/*.pyo
**/__pycache__
*.log
.dockerenv
.git

Limit RUN Instruction’s Cache

Limit the Docker instruction RUN caches by conditioning the RUN instruction.

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

Clean the Apt Cache

After installing packages using apt, delete the package cache to save space.

RUN apt-get clean && rm -rf /var/lib/apt/lists/*

Use Multi-Stage Builds

This feature allows you to drastically reduce the size of your images by creating a temporary image to compile/build your application, then transferring only the necessary files to a smaller base image.

# Build stage
FROM golang:1.9-alpine AS builder
WORKDIR /source
COPY . .
RUN go build -o app

# Run stage
FROM alpine:3.9
COPY --from=builder /source/app /app
ENTRYPOINT ["/app"]

By following these steps, you’ll end up with a slimmer, faster, and more efficient Docker image.

docker