Almost everything on a Linux server arrived as a package: a signed archive with files, dependencies, and scripts, from a repository the system trusts. Debian and Ubuntu use apt and .deb; Red Hat, Rocky, Alma, and Fedora use dnf and .rpm. Package management is how you install software, keep it patched, and keep versions from changing under you. This lesson follows one security fix from the repository to a running process, and the two places it usually stops short.
Difficulty: Intermediate · Know this first: Lesson 02, Lesson 15
This bar adds up admin minutes from a published fix to a patched, running system. It is a worked example, not a measurement. The pin and restart hops are where an update either breaks things or quietly changes nothing.
Two repositories offer the runtime. Choose whether it is held or pinned, and see which version apt picks on the next upgrade.
Pinned: no 20.x update yet, so nothing changes
Three questions. No score is saved anywhere — this is just you against the material.
Package management grows in four levels: installing and querying, safe upgrades, repositories and pinning, and patching a fleet.
At the basic level you can install software and find out what is installed.
apt update, apt install, apt remove, apt search, apt show, dpkg -l, dpkg -S FILE.dnf install, dnf remove, dnf search, dnf info, rpm -qa, rpm -qf FILE.Where it breaks: installing from a random .deb or .rpm downloaded from a web page, which skips repository signatures and never gets updates.
Try it: Basic
Which command tells you which package installed /usr/bin/curl on Ubuntu?
Now do it: Find the owning package of three binaries in /usr/bin.
At the intermediate level you upgrade with a plan.
apt-get -s upgrade), apply, then needrestart or dnf needs-restarting.unattended-upgrades or dnf-automatic for security updates, staged by environment./var/log/apt/history.log, dnf history undo.Try it: Intermediate
After an upgrade, needrestart lists nginx and php-fpm. What do you do?
Now do it: Run needrestart -r l on a host after its next update.
At the advanced level you control exactly what can change.
Signed-By: per repository; priorities in preferences.d.fpm, dpkg-deb, rpmbuild) in your own signed repository.Try it: Advanced
A vendor asks you to add their repository with [trusted=yes]. What is the risk?
Now do it: grep -r trusted /etc/apt/sources.list.d/ on your hosts.
At the master level patching is a measured process.
Trade-off: fast automatic patching closes holes sooner and occasionally breaks things; slow, manual patching breaks less and leaves holes open for weeks. Rings and health gates get most of both.
Try it: Master
Why snapshot repositories for a fleet?
Now do it: Compare dpkg -l output on two hosts that are supposed to be identical.
The same tasks on both families. Run them in a container (docker run -it --rm ubuntu:24.04 or rockylinux:9) to practise.
apt update apt list --upgradable apt-get -s upgrade | grep ^Inst # simulate apt install -y --no-install-recommends curl dpkg -S "$(command -v curl)" # which package owns a file apt-mark hold curl; apt-mark showhold; apt-mark unhold curl cat /etc/apt/sources.list.d/*.sources # deb822 sources with Signed-By tail -20 /var/log/apt/history.log
dnf check-update dnf updateinfo list --security dnf install -y curl rpm -qf "$(command -v curl)" dnf install -y 'dnf-command(versionlock)' && dnf versionlock add curl && dnf versionlock list dnf history list | head dnf needs-restarting -s # services to restart after an update
# /etc/apt/preferences.d/nodejs Package: nodejs Pin: version 20.* Pin-Priority: 1001
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A fleet was "patched" for weeks without being protected.
needrestart runs in automatic mode with a rolling restart job, the scanner checks libraries mapped by running processes, and "time to patched in memory" is a tracked metric.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Type each one, read what it prints, and compare it with the note above it.
See what an upgrade would change before changing anything (Debian or Ubuntu).
sudo apt update -qq; apt list --upgradable 2>/dev/null | head; apt-get -s upgrade | grep -c "^Inst"
Which package owns a file, and what it depends on.
dpkg -S "$(command -v curl)"; apt-cache depends curl | head -8
Hold a package, see the hold, and release it.
sudo apt-mark hold curl; apt-mark showhold; sudo apt-mark unhold curl
Find processes still using old libraries after an update (sudo apt install -y needrestart).
sudo needrestart -r l -b 2>/dev/null | head || echo "install needrestart to try"; tail -5 /var/log/apt/history.log
pin_resolver.pyThis program resolves which version apt-style pinning would install from two repositories, for an unpinned package, a series pin, and a hold, against a patch release and a major release. Save it as pin_resolver.py, then run it.
# pin_resolver.py
def ver(v):
return tuple(int(x) for x in v.split("."))
def candidate(installed, offered, rule):
if rule == "hold":
return installed
allowed = [v for v in offered if rule == "none" or v.startswith(rule.rstrip("*"))]
best = max(allowed, key=ver) if allowed else installed
return best if ver(best) > ver(installed) else installed
installed = "20.18.0"
for offered_label, offered in [("a patch is out", ["20.18.0", "20.18.1"]), ("a new major is out", ["20.18.0", "22.11.0"])]:
print(f"== {offered_label}: {offered}")
for rule in ["none", "20.*", "hold"]:
c = candidate(installed, offered, rule)
change = "no change" if c == installed else ("MAJOR upgrade" if c.split(".")[0] != installed.split(".")[0] else "patch")
print(f" pin {rule:<5} -> installs {c:<8} ({change})")
Run it, and you should see this output:
$ python3 pin_resolver.py == a patch is out: ['20.18.0', '20.18.1'] pin none -> installs 20.18.1 (patch) pin 20.* -> installs 20.18.1 (patch) pin hold -> installs 20.18.0 (no change) == a new major is out: ['20.18.0', '22.11.0'] pin none -> installs 22.11.0 (MAJOR upgrade) pin 20.* -> installs 20.18.0 (no change) pin hold -> installs 20.18.0 (no change)
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/linux-package-management && cd ~/labs/linux-package-management) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Package Management: apt, dnf, Repositories, and Updates", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'See what an upgrade would change before changing anything (Debian or Ubuntu).'
'Which package owns a file, and what it depends on.'
'Hold a package, see the hold, and release it.'
'Find processes still using old libraries after an update (sudo apt install -y needrestart).'
)
step_1() {
sudo apt update -qq; apt list --upgradable 2>/dev/null | head; apt-get -s upgrade | grep -c "^Inst"
}
step_2() {
dpkg -S "$(command -v curl)"; apt-cache depends curl | head -8
}
step_3() {
sudo apt-mark hold curl; apt-mark showhold; sudo apt-mark unhold curl
}
step_4() {
sudo needrestart -r l -b 2>/dev/null | head || echo "install needrestart to try"; tail -5 /var/log/apt/history.log
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
grep, head, tail, curl, echo, Pipes, Redirection, If...Else.Design patching for 200 Ubuntu servers and 50 Rocky Linux servers running web services and databases.
Where do packages come from, and are versions the same everywhere? How fast must critical fixes be running? What may change automatically and what needs a change ticket? How are restarts and reboots done without downtime?
Say a 48-hour target for critical fixes in memory, weekly routine patching, and monthly kernel reboots.
Internal mirrors with dated snapshots; unattended-upgrades and dnf-automatic for security, in rings (canary, staging, production) with health gates; runtime and database majors pinned; needrestart and dnf needs-restarting driving rolling restarts behind the load balancer; monthly rolling reboots; a report of patched-in-memory per host.
Snapshots make environments identical and add a promotion step that can delay urgent fixes, so keep a fast path for critical CVEs. Automatic restarts close the in-memory gap and need health checks good enough to stop a bad rollout.