DEV Community

Shriharsh
Shriharsh

Posted on • Updated on

Today I Learned: A simple trick to slim down a Docker image

You may want to reduce the space used by your image. If you are building on top of an Ubuntu image and during the build, you are invoking apt-get update (you would be for sure if you are installing latest versions!) then you can delete some files downloaded by apt-get that won't be required later. The following Dockerfile snippet shows a way how it should be done. Notice that RUN instruction is doing 3 things, update the package cache, installing ant, and deleting the cache. This is done in such a ways so that Docker does all of this in a single layer of the image. If these steps are split in different RUN instructions then your Docker host and/or registry will use more space.


FROM jenkins/jenkins:lts

#Change user to root and install ant version 1.9.9-1 (available in Ubuntu packages)
USER root

#
RUN apt-get update && \
        apt-get install -y ant=1.9.9-1 && \
        rm -rf /var/lib/apt/lists/* # remove the cached files.

Enter fullscreen mode Exit fullscreen mode

In my case, it saved about 138M of space. However, YMMV.

By the way, what are you deleting? You are only deleting the information about latest packages and versions available for download using apt-get install or apt-get upgrade. apt-get caches this information later use. It is highly likely that you wouldn't need this information when you are running the containers based on this image. Installing software while running the container would be a big NO!.

Similar, cache files would exist in other Linux distributions as well.

I hope this helps you slim down your ubuntu images.

Top comments (1)

Collapse
 
ikemkrueger profile image
Ikem Krueger • Edited

I am not sure if the package cache is automatically cleaned, but you could do it manually with „apt-get clean“.