This page describes a highlighted problem produced by the Docker and Kubernetes Security scanner plugin.
You could find more details on the internal page: Cloud (IaC) Security plugin
If this project has been helpful to you, please consider giving it a ⭐ on GitHub to help others discover it.
What’s the problem with dnf cache?
The dnf package manager stores cached metadata and packages in /var/cache/dnf/ to speed up subsequent installations. While this cache is beneficial for regular system operations, it becomes dead weight in Docker images, potentially increasing image size by hundreds of megabytes. In Docker environments, cached package data from DNF can dramatically bloat images if not properly managed.
The Docker Layer Problem
Docker images consist of immutable layers where each Dockerfile instruction creates a new layer. When you install packages and clean the cache in separate RUN commands, the cache persists in intermediate layers even after deletion. This occurs because each layer contains only the differences from the previous layer, and deleted files in subsequent layers don’t remove them from earlier layers – they simply mark them as hidden
Comprehensive DNF Cache Types
DNF maintains several types of cache that should be addressed:
- Database caches (
dnf clean dbcache) – Store package metadata and file lists - Metadata caches (
dnf clean metadata) – Repository information for enabled repos - Package caches (
dnf clean packages) – Downloaded package files - Complete cache (
dnf clean all) – All cached data combined
Using dnf clean all is the most comprehensive solution, removing all cached data types in a single command
Solution
The critical optimization technique involves chaining installation and cleanup in a single RUN instruction using the && operator. This approach ensures that cache cleanup occurs in the same layer where packages are installed, preventing cache persistence in the final image
For maximum optimization, combine dnf clean all with manual cache directory removal
RUN dnf install -y httpd && \
dnf clean all && \
rm -rf /var/cache/dnfThis double-cleanup approach ensures the complete removal of all DNF-related cached data
Problematic code
FROM fedora:version
USER nobody
RUN dnf install -y httpdVerified code
FROM fedora:version
USER nobody
RUN dnf install -y httpd && dnf clean all