When installing packages an index is cached locally by default. The index can be used on-the-fly and not stored locally.
Why is this an issue?
Docker images should only contain necessary data. The package index is optional for the correct working of the installed software. Storing an index
also increases the size of the Docker image. It should be reduced to speed up deployments and reduce storage and bandwidth.
How to fix it
Code examples
Noncompliant code example
For apk:
RUN apk add nginx
For apt-get:
RUN apt-get update \
&& apt-get install nginx
For aptitude:
RUN aptitude update \
&& aptitude install nginx
For apt:
RUN apt update \
&& apt install nginx
Compliant solution
For apk:
RUN apk --no-cache add nginx
RUN apk add nginx \
&& apk cache clean
RUN apk add nginx \
&& rm -rf /var/cache/apk/*
# This cache location is only used in specific distributions / configurations
RUN apk add nginx \
&& rm -rf /etc/apk/cache/*
For apt-get:
RUN apt-get update \
&& apt-get install nginx \
&& apt-get clean
RUN apt-get update \
&& apt-get install nginx \
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/*
For aptitude:
RUN aptitude update \
&& aptitude install nginx \
&& aptitude clean
RUN aptitude update \
&& aptitude install nginx \
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/*
For apt:
RUN apt update \
&& apt install nginx \
&& apt clean
RUN apt update \
&& apt install nginx \
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/*
How does this work?
When installing packages using apt-get
, aptitude
or apt
they store an index in the Docker image layer in
/var/lib/apt/lists
. Using apk
, it will store an index in /var/cache/apk/
. In some distributions and
configurations the cache will be created in /etc/apk/cache
.
This index is not needed after installation, so it can be removed. To do that, execute the clean
command, or run rm -rf
<location>
for the cache location of you package manager tool.
Additionally, for apt-get
, aptitude
and apt
some lock files are stored in
/var/cache/apt/archives
, which can also be removed safely. They are not removed by the clean
command, so they need to be
removed manually.
Resources
Documentation