BudiBadu Logo
Samplebadu

Dockerfile by Example: Package Installation Setup

Docker Engine 20.10+

Installing system packages is a common task. This sample code demonstrates the best practices for apt-get and apk to keep images clean and avoid caching stale lists.

Code

FROM ubuntu:22.04

# Combine update, install, and cleanup in a SINGLE RUN instruction
# This ensures the layer is self-contained and minimal.
RUN apt-get update && apt-get install -y \
    curl \
    git \
    vim \
    && rm -rf /var/lib/apt/lists/*

# For Alpine Linux, use --no-cache
FROM alpine:3.18
RUN apk add --no-cache \
    curl \
    git \
    bash

Explanation

Efficient package installation is critical for keeping Docker images small and maintainable. When using apt-get on Debian/Ubuntu, it is best practice to combine apt-get update and apt-get install into a single RUN instruction. This prevents Docker from caching an old "update" layer that might reference outdated package versions, ensuring you always install the latest available packages and avoiding "package not found" errors.

Package manager best practices include:

  • Combine update, install, and cleanup steps in one RUN command
  • Use --no-install-recommends with apt to avoid unnecessary dependencies
  • Clean up package lists (rm -rf /var/lib/apt/lists/*) to reduce layer size
  • Use apk add --no-cache on Alpine to avoid storing local index

For Alpine Linux, the apk package manager offers a --no-cache flag that installs packages without storing the package index locally, eliminating the need for a separate cleanup step. Failing to clean up package caches (like /var/lib/apt/lists) results in bloated images because even if you delete the files in a later layer, the data remains physically present in the underlying layer history.

Code Breakdown

5
apt-get update && install ensures package lists are fresh for this install.
9
rm -rf ... removes temporary lists. Must be in same RUN command to save space.
13
apk add --no-cache installs without saving index, optimized for Alpine.
5-9
Backslashes allow splitting long commands for readability.