Remove Package Manager Caches for Smaller Image Sizes

Keeping images small is a key Docker best practices. But how do you do that when you need to install packages for your application to work? One way is to clean out package manager caches. In this short tutorial, I'm going to show you how to do that with Debian and Alpine Linux base images.

Want to learn more about Docker?

Are you tired of hearing how "simple" it is to deploy apps with Docker Compose, because your experience is more one of frustration? Have you read countless blog posts and forum threads that promised to teach you how to deploy apps with Docker Compose, only for one or more essential steps to be missing, outdated, or broken?

Check it out

Let's assume that you're building a small CakePHP application which requires PHP's intl extension for internationalisation support, and PDO's PostgreSQL driver, for the purposes of this tutorial. To install it, you need to install libicu-dev, which you can see in the small Dockerfile example below.

FROM php:8.3.7-apache-bookworm

RUN apt-get update \
    && apt-get install -y libicu-dev \
    && docker-php-ext-install bcmath intl pdo pdo_mysql

RUN a2enmod rewrite

The essence of the post is to encourage people to remove or clean up package manager caches when building images in Dockerfiles, so that the images are as small as possible. I'll use APT and APK as examples, showing how to clean them with commands such as apt clean, and rm -rvf.