Dockerfile: Clean YUM Package Cache to Reduce Image Size

YUM cache left after install increases image size and scan surface. Run yum clean all in the same layer to keep container builds smaller and reproducible.

Problem

You do not run yum clean all after yum install. This leaves repository metadata and cache files inside image layers, increasing final image size.

Description

YUM keeps metadata and package cache files for faster host operations. In containers, those files are usually unnecessary after package installation. If they remain in the layer, every pull and scan processes extra data that provides no runtime value.

The most common failure mode is splitting install and cleanup steps across multiple layers. Even if cleanup runs later, the previous layer still contains the cache payload. Put install and cleanup in one RUN instruction so the cache is never persisted in the final layer.

Related rules: consolidate multiple RUN instructions, combine update and install in one RUN, clean DNF package cache.

Solution

Run yum clean all in the same layer as package installation. Keep package commands deterministic and avoid leaving temporary cache files in production images.

Problematic code

FROM centos:7
USER nobody
RUN yum install -y httpd

Verified code

FROM centos:7
USER nobody
RUN yum install -y httpd && yum clean all

Source of the description

yum(8) manual page