Sub topic 11
Cleaning up with autoremove and cache cleaning
Patching adds files to a server. Package managers download archives, pull in new dependencies, and install new kernels beside the old ones. This chapter covers what each tool leaves behind, how to remove it safely, and which cleanup commands undermine your rollback options.
It assumes you can apply updates with apt or dnf (previous chapters) and read df output. You need sudo on a Debian/Ubuntu or RHEL-family test machine.
What accumulates after patching
Four kinds of leftovers build up:
- Orphaned dependencies. Package A needed library B, so B was installed automatically. Later A is removed or replaced, and B stays.
- Old kernels. A kernel update installs a new kernel next to the running one. The old one is kept so you can boot it if the new one fails.
- Downloaded package files. Archives are cached in
/var/cache/apt/archives(apt) or/var/cache/dnf(dnf). - Residual configuration. On Debian and Ubuntu,
apt removedeletes a package's program files but keeps its configuration files.
Only some of these are safe to delete immediately. The table shows where each lives and what removing it costs.
| Leftover | apt location | dnf location | Removal cost |
|---|---|---|---|
| Orphaned dependencies | dpkg database | rpm database | Low, if you review the list first |
| Old kernels | `/boot`, `/lib/modules` | `/boot`, `/lib/modules` | You lose the fallback kernel |
| Cached packages | `/var/cache/apt/archives` | `/var/cache/dnf` | You lose offline downgrade files |
| Metadata | `/var/lib/apt/lists` | `/var/cache/dnf` | Next refresh downloads it again |
| Residual config | `/etc` (status `rc`) | `.rpmsave` files | You lose old settings |
How automatic and manual installs are tracked
Both tools record why each package is present. A package you named on the command line is manual. A package installed only to satisfy a dependency is automatic. A package that is automatic and has no remaining dependents is a candidate for removal.
apt-mark showmanual | head
apt-mark showauto | headOn dnf systems, the equivalent is the reason recorded in the history database:
dnf repoquery --userinstalled | head
dnf repoquery --unneededThe second command lists packages that dnf autoremove would remove.
If a package is on the removal list but you use it, mark it manual. The tool then stops treating it as an orphan:
sudo apt-mark manual libexample1
sudo dnf mark install libexampleIn both cases, replace the name with the real package. dnf mark install sets the reason to "user installed". (On dnf 4, which RHEL 8 and 9 use, this subcommand exists. Check dnf mark --help if you run something older.)
Removing orphaned packages
On Debian and Ubuntu
Always simulate first. The simulation prints a Remv line for each package that would go.
sudo apt autoremove --dry-runRead the list. If it looks right, run it for real:
sudo apt autoremoveAdd --purge to also delete the configuration files of the removed packages:
sudo apt autoremove --purgeUse --purge when the packages were true orphans and you do not expect to reinstall them. Skip it if the configuration took effort to write.
On RHEL-family systems
dnf autoremove prompts before it acts, and --assumeno turns that into a dry run:
sudo dnf autoremove --assumeno
sudo dnf autoremoveBecause dnf stores the removal as a transaction, dnf history undo last can reverse it. apt has no equivalent, so on apt systems the simulation is your only safety net.
Old kernels
Kernels are the largest leftovers and the most dangerous to remove, because the old kernel is your fallback.
On Ubuntu, kernel packages are installed as automatic, with a meta-package such as linux-image-generic marked manual. Ubuntu's apt configuration protects the running kernel and the newest installed kernel from autoremove. Older ones are removed. Debian behaves the same way for most setups.
On RHEL-family systems, dnf handles this itself through installonly_limit in /etc/dnf/dnf.conf. The default is 3, so a kernel update installs the new kernel and removes the oldest once there are more than three. You normally do not run autoremove for kernels at all.
Check what you have:
uname -r
rpm -q kernel # RHEL family
dpkg -l 'linux-image-*' | grep '^ii' # Debian/Ubuntu
df -h /bootFollow this order:
- Patch and reboot.
- Verify that the server works on the new kernel.
- Only then remove old kernels.
If you autoremove before rebooting, the currently running kernel is protected, but the version you just installed has not been tested. Wait until the new kernel has proven itself.
To reduce the kept kernels on a dnf system, lower installonly_limit (the minimum allowed is 2) and run the next update. To remove extras immediately:
sudo dnf remove --oldinstallonly --setopt installonly_limit=2 kernelAlways keep at least two kernels: the running one and one known-good fallback.
Cleaning the package cache
apt
| Command | What it removes |
|---|---|
| `apt clean` | Every downloaded `.deb` in `/var/cache/apt/archives` |
| `apt autoclean` | Only `.deb` files that can no longer be downloaded (superseded versions) |
Measure first, then clean:
du -sh /var/cache/apt/archives
sudo apt clean
du -sh /var/cache/apt/archivesapt clean does not touch /var/lib/apt/lists. That directory holds the metadata apt update fetched. Deleting it by hand is a repair step for corrupted lists, not routine cleanup.
dnf
du -sh /var/cache/dnf
sudo dnf clean packages # downloaded .rpm files
sudo dnf clean metadata # repository metadata
sudo dnf clean all # everything dnf cachesBy default dnf deletes packages after a successful install (keepcache=False), so the cache is mostly metadata. After dnf clean all, the next dnf check-update downloads metadata again, which is slower and needs network access. Run sudo dnf makecache if you want to rebuild it in advance.
Removing residual configuration on Debian and Ubuntu
Packages removed without --purge show status rc ("removed, config remains") in dpkg -l. List them first:
dpkg -l | awk '/^rc/ {print $2}'Review that list. Purge only entries you are sure you no longer need:
dpkg -l | awk '/^rc/ {print $2}' | xargs -r sudo apt purge -yThe -r flag stops xargs from running apt purge with no arguments when the list is empty.
On RHEL-family systems, rpm saves modified config files as *.rpmsave or *.rpmnew. Find them with:
sudo find /etc -name '*.rpmnew' -o -name '*.rpmsave'Compare each with the live file before deleting it. An .rpmnew file often contains settings the new package version expects.
A cleanup routine
This diagram shows the order and the checks that gate each step.
A short script for Debian and Ubuntu that stops before changing anything unless you confirm:
#!/usr/bin/env bash
set -euo pipefail
echo "Running kernel: $(uname -r)"
df -h /boot /var | sed 's/^/ /'
echo "--- packages autoremove would remove ---"
apt-get -s autoremove | grep '^Remv' || echo "none"
read -r -p "Run autoremove and apt clean? [y/N] " answer
if [ "$answer" = "y" ]; then
sudo apt-get autoremove -y
sudo apt-get clean
fiThe grep exits with status 1 when nothing matches, and the || echo keeps set -e from ending the script.
Common errors and gotchas
/bootis full and updates fail. Old kernels filled the partition. Boot the current kernel, runsudo apt autoremove --purge, and re-run the upgrade. On dnf, checkinstallonly_limit.- A service disappears after autoremove. The package was only ever marked automatic. Reinstall it, then run
apt-mark manualso it is not removed again. On dnf,dnf history undo lastrestores it. - Cleaning the cache and then needing to downgrade. After
apt clean, an older.debis no longer on disk. You must download it from the repository, which may have dropped it. Hold the cleanup until a patch has been verified. dnf history undofails afterdnf clean all. Undo re-downloads old package versions. If the repository no longer carries them, the undo fails whether or not you cleaned the cache.- Removing config you needed.
--purgeis irreversible. Back up/etc/<service>before purging anything you configured by hand. - Cleaning on every patch run. Cleaning removes your rollback material the moment it is created. Clean after verification, not as the last line of the patch script.
Automating cleanup
unattended-upgrades can do part of this for you. These options go in /etc/apt/apt.conf.d/50unattended-upgrades:
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "false";Removing unused kernels is on by default and is a reasonable choice. Removing unused dependencies is off by default, and leaving it off is the conservative choice, because it removes packages without anyone reading the list. dnf-automatic has no cleanup setting. Kernel pruning comes from installonly_limit, so schedule any other cleanup yourself after the verification step.
Exercise
A server runs Ubuntu. You applied a kernel update yesterday and rebooted, and the application works. apt autoremove --dry-run lists libfoo2, but your monitoring agent uses that library directly. What should you do before running apt autoremove, and why should you not run apt clean first if you might still need to downgrade a package?
Show answer
Run sudo apt-mark manual libfoo2 (or whatever package the agent actually needs) so apt no longer treats it as an orphan, then simulate again to confirm it is off the list and run apt autoremove. Do not run apt clean yet, because it deletes every cached .deb. That includes the older package versions you would use for a downgrade, and the repository may no longer serve them. Clean the cache once the patch has been verified and you no longer need to roll back.