Dockerfile: Combine Update and Install in One RUN Instruction

Running update and install in separate RUN layers can use stale package indexes. Combine them in one command for deterministic package installs.

Problem

Using RUN <package-manager> update alone is risky. It should be followed by <package-manager> install in the same RUN command.

Description

Running update and install in different layers can produce stale package metadata. If the cache layer is reused, installation may not reflect current repository state and can lead to inconsistent builds across environments.

Combining update and install in one step makes dependency resolution deterministic for that layer. This pattern also simplifies review and reduces the chance of build failures caused by transient repository changes.

Supported package managers include: apt-get, apt, yum, apk, dnf, and zypper.

Related rules: consolidate RUN instructions, use –no-install-recommends, clean package cache.

Solution

Combine <package-manager> update and <package-manager> install in one RUN command. This approach guarantees that the updated package list is applied immediately during installation.

Problematic code

FROM ubuntu:20.04
USER nobody
RUN apt-get update
RUN apt-get install -y --no-install-recommends build-essential

Verified code

FROM ubuntu:20.04
USER nobody
RUN apt-get update && apt-get install --no-install-recommends -y build-essential

Source of the description

Dockerfile best practices