The size of a Docker image affects its runtime and the performance of your application. Small containers run faster, are easier to manage, and take up less disk space.

There are several ways to reduce the size of Docker images. In particular, you can use Alpine Linux images which are much smaller than the rest.

Reduce the Size of an Existing Docker Image With Alpine

A Docker image is a template with instructions on how to build a Docker container. It has everything you need to set up and run an application. This may include dependencies, commands, and even environment variables.

There are two ways to reduce Docker images with Alpine images. One is by pulling an Alpine version of the image, and the second is by editing Dockerfile to use an Alpine image.

Pull Docker Image From Docker Hub

Let's pull an Nginx Docker image and then reduce its size. Navigate to the Docker registry. From the official Docker images, pull a Nginx Image with the following command:

        docker pull nginx
    

Run the following command on the terminal to check whether the image is in your system.

        docker image ls
    
downloaded nginx image 2

Notice the size of the downloaded Nginx image is 142MB. Next, let's reduce the size of this image using an Alpine Linux Image.

Alpine Linux is a very small distribution, so images based on it are small as well as simple and secure. Check the Docker registry for an Nginx image version with the Alpine tag.

nginx  alpine image links

Then run the following command on the terminal:

        docker pull nginx:stable-alpine
    

Notice that now the size is smaller, almost a quarter of the initial image.

Docker image reduce size by Alpine 2

Edit Dockerfile to Use Alpine Images

Alternatively, edit the Dockerfile of an existing application to use the Alpine image.

        FROM python: alpine

ENV PYTHONUNBUFFERED 1

WORKDIR /app

ADD . /app/

Next, when you build the image with an Alpine image, you will notice the size of the Python image has reduced.

Why Use Alpine Images?

Use Alpine images to reduce the size of Docker images quickly. Docker recommends the use of such official images for common use cases.

An Alpine Linux image creates small manageable containers in both development and production. It is easy to pull, configure, and use.

At the same time, it helps build and deploy lightweight applications across all platforms. It's no wonder that Alpine is a developer-favorite Linux distro on the Docker platform.