# Packages: install, update and trust software

How apt and dnf install software with its dependencies, where packages come from, how to update a server safely, find what owns a file, pin versions, and when snap fits.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 10. About 30 minutes, beginner. Source: https://devops.rajeev.pro/courses/linux/10-package-management

## What you will learn

- Explain repositories, package indexes and dependencies, and what apt update actually does
- Install, remove, upgrade and search packages with apt (Debian, Ubuntu) and dnf (RHEL, Rocky, Fedora)
- Find which package owns a file, and list what's installed
- Add a third-party repository safely, with its signing key
- Update a production server without surprises, and hold a package at one version
- Choose between a distro package, snap, and a vendor's installer

## How a package manager works

**Before package managers.** Installing software on Linux used to mean: find the project's website,
download a `.tar.gz` of source code, run `./configure && make && make install`, and watch it fail
because it needs a library you don't have. So you download _that_ library, which needs two more.
Hours later it works, but nobody wrote down what was installed where. Updating means doing it all
again, and removing it cleanly is close to impossible, because the files are scattered across the
system and nothing remembers which ones belong to which program. This was called "dependency hell".

**What a package manager does instead.** It turns all of that into one command, and it keeps a
record. A **package** is a program bundled with its files, its configuration and a list of what it
needs to run. A **repository** is a server full of packages, published by your distribution or a
vendor. The **package manager** downloads the right packages, installs what they depend on, and
remembers every file it put on disk, so it can update or remove them cleanly later.

> **Figure.** How apt installs a package. Repositories listed in /etc/apt/sources.list.d publish package indexes. apt update downloads those indexes to the server. apt install nginx resolves dependencies from the indexes, downloads the .deb files, checks their signatures, and hands them to dpkg, which unpacks the files and runs the setup scripts. On RHEL-family systems dnf and rpm play the same roles.
>
> update refreshes the catalogue; install picks, downloads, verifies and unpacks.

Two families cover almost every server:

|                                         | Debian, Ubuntu                            | RHEL, Rocky, Alma, Fedora, Amazon Linux |
| --------------------------------------- | ----------------------------------------- | --------------------------------------- |
| Package file                            | `.deb`                                    | `.rpm`                                  |
| High level (repositories, dependencies) | `apt` (`apt-get`, `apt-cache` in scripts) | `dnf` (`yum` on older systems)          |
| Low level (one package file)            | `dpkg`                                    | `rpm`                                   |
| Repositories                            | `/etc/apt/sources.list.d/`                | `/etc/yum.repos.d/`                     |

Use the high-level tool almost always. `dpkg -i file.deb` or `rpm -i file.rpm` install one file and
**don't** fetch its dependencies, which is how servers end up half-broken.

## Everyday commands

The high-level package tool handles repositories and dependencies. On Debian and Ubuntu, use `apt` at an
interactive terminal and `apt-get` or `apt-cache` in scripts where stable output matters. On RHEL-family
systems, use `dnf`. Refreshing the package index does not install upgrades; it only updates the catalogue used
to choose candidate versions.

| Task                       | apt (Debian, Ubuntu)     | dnf (RHEL family)                     |
| -------------------------- | ------------------------ | ------------------------------------- |
| Refresh the lists          | `sudo apt update`        | (automatic; `sudo dnf makecache`)     |
| Search                     | `apt search nginx`       | `dnf search nginx`                    |
| Details                    | `apt show nginx`         | `dnf info nginx`                      |
| Install                    | `sudo apt install nginx` | `sudo dnf install nginx`              |
| Remove                     | `sudo apt remove nginx`  | `sudo dnf remove nginx`               |
| Remove with its config     | `sudo apt purge nginx`   | (config files are kept as `.rpmsave`) |
| Upgrade everything         | `sudo apt upgrade`       | `sudo dnf upgrade`                    |
| Remove unused dependencies | `sudo apt autoremove`    | `sudo dnf autoremove`                 |

```sh
$ apt-cache policy curl                 # installed version, and the version apt would install
curl:
  Installed: 8.18.0-1ubuntu2.7
  Candidate: 8.18.0-1ubuntu2.7
$ apt-get -s install tree               # -s: simulate. Shows what would happen, changes nothing
The following NEW packages will be installed:
  tree
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
$ sudo apt install -y tree              # -y: don't ask (for scripts)
```

`apt` is for people: progress bars and colour. In scripts, use `apt-get` and `apt-cache`: their
output stays stable between versions. Set `DEBIAN_FRONTEND=noninteractive` so no package stops a
script to ask a question.

Simulate a change before installing on a sensitive host, and read which packages will be added or removed.
Use purge when you also intend to remove Debian package configuration; ordinary remove may retain it. A
common mistake is using `dpkg -i` for a package with dependencies: the low-level tool does not resolve and
download missing packages for you.

> **Video.** [Linux Crash Course - The apt Command](https://www.youtube.com/watch?v=1kicKTbK768) (Learn Linux TV)

## What's installed, and who owns this file?

When two copies of a tool exist, the name alone does not tell you which package installed the executable or
which version is active. Package databases answer that question and help you distinguish managed software
from a manually copied binary.

```sh
$ dpkg -l | grep -c '^ii'               # how many packages are installed
549
$ dpkg -l curl                          # one package: ii = installed
ii  curl           8.18.0-1ubuntu2.7 amd64        command line tool for transferring data
$ dpkg -S /usr/bin/curl                 # which package put this file here?
curl: /usr/bin/curl
$ dpkg -L curl                          # every file a package installed
$ apt list --upgradable                 # what has a newer version waiting
$ rpm -qa | sort                        # RHEL family: everything installed
$ rpm -qf /usr/sbin/nginx               # RHEL family: which package owns a file
```

`dpkg -S` and `rpm -qf` answer the classic question "where did this binary come from?", which
matters when two versions of a tool are installed and the wrong one runs.

Use `dpkg -L` or `rpm -ql` to inspect a package's files, and check the executable selected by `PATH` when a
command behaves unexpectedly. A file under `/usr/local/bin` may not belong to a package at all. A common
mistake is deleting a package-owned file directly; the package manager may restore it during an update or
continue to report the package as installed.

## Repositories and trust

Your distribution's repositories have most software you need. A vendor repository may provide a newer version,
but it also becomes a trusted source of code that can run as root during package installation. Adding one
means installing its signing key, configuring the repository and telling apt which key may sign its packages.

```sh
$ sudo install -d -m 0755 /etc/apt/keyrings
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo tee /etc/apt/keyrings/docker.asc > /dev/null
$ echo "deb [signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
    | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
$ sudo apt update
```

`signed-by=` ties that repository to that key only, so a key you add for Docker can't be used to
sign packages pretending to be Ubuntu's. Every package is checked against the key before it's
installed.

Scope each key to its repository with `signed-by=` instead of trusting it globally. Follow the vendor's
official instructions and review how updates are published. A common mistake is adding a key with a global
trust command; that can allow it to authenticate packages from other configured repositories too.

> **Adding a key is adding trust.** A repository can install anything on your server, as root, at every upgrade. Add only vendors you trust, over https, following their official instructions. Never pipe a random script from the internet straight into `sudo bash` on a production machine.

## Updating a production server

Updates fix security holes, so servers must get them. They also change software under running
apps. An upgrade can restart a service in the middle of the day, change a default setting, or bring
a new major version of a database. So treat updates as a planned change, not a background chore.
The routine below does that:

1. **Look first.** See exactly which packages will change.
2. **Hold the risky ones.** `apt-mark hold` freezes a package (a database, say) at its current
   version, so it's upgraded later, in its own maintenance window, with a backup taken first.
3. **Upgrade the rest.**
4. **Check whether a reboot is needed.** A new kernel only takes effect after a reboot, and Ubuntu
   leaves a marker file when one is due.

The commands, in that order:

```sh
$ sudo apt update && apt list --upgradable     # 1. see what would change
$ sudo apt-mark hold postgresql-16             # 2. hold anything that needs a planned window
$ sudo apt upgrade                             # 3. upgrade the rest
$ ls /var/run/reboot-required 2>/dev/null && cat /var/run/reboot-required.pkgs   # 4. kernel update?
$ sudo apt-mark unhold postgresql-16           # when its window comes
```

| Command            | Upgrades                                           | Removes or adds packages |
| ------------------ | -------------------------------------------------- | ------------------------ |
| `apt upgrade`      | everything that can be upgraded safely             | never removes            |
| `apt full-upgrade` | also changes that need adding or removing packages | may remove               |
| `dnf upgrade`      | everything                                         | may replace packages     |

Test upgrades on a staging server first, upgrade one production server at a time behind a load
balancer, and keep `unattended-upgrades` for security fixes only, so urgent patches still apply
by themselves.

Apply updates in small batches behind a load balancer, then check service health before continuing. A held
package is a temporary scheduling decision, not a reason to skip its security updates forever; track the
planned upgrade window. A common mistake is running `full-upgrade` without reviewing removals, which can
remove packages to complete dependency changes.

## snap and other installers

**snap** packages (Ubuntu) bundle a program with all its dependencies and update themselves. They're
convenient for desktop and developer tools (`sudo snap install --classic code`), and some
Ubuntu server tools ship this way. On servers, prefer the distribution's packages or the vendor's
repository: they integrate with systemd and your normal update process.

Some tools ship as a single binary (`kubectl`, `terraform`) or a vendor install script. Download
them from the official site, check the published checksum (`sha256sum -c`, from the _Text
processing_ lesson), and put them in `/usr/local/bin`, which is for software the package manager
doesn't manage.

> **In production.** Write down what you installed and why, or better, install it with code: Ansible, a Dockerfile, or a cloud-init script. A server built by hand from memory can't be rebuilt exactly, and one day it will need to be.

## Mission: Audit a server's packages before a change

Before upgrading a server, you want to know where its software comes from. Record which repositories it uses, how many packages are installed, what would be upgraded, and which package provides the curl binary. Save it to one report.

- You need: An Ubuntu or Debian server
- You'll have: ~/packages.txt

```sh
$ cat > ~/packages-report.sh <<'EOF'
#!/bin/bash
echo "== repositories"; grep -rh "^URIs\|^deb " /etc/apt/sources.list /etc/apt/sources.list.d/ 2>/dev/null | sort -u
echo "== installed: $(dpkg -l | grep -c '^ii') packages"
echo "== upgradable"; apt list --upgradable 2>/dev/null | tail -n +2
echo "== held"; apt-mark showhold
echo "== curl comes from"; dpkg -S "$(command -v curl)"
EOF
$ bash ~/packages-report.sh > ~/packages.txt
$ cat ~/packages.txt
== repositories
URIs: http://archive.ubuntu.com/ubuntu/
URIs: http://security.ubuntu.com/ubuntu/
== installed: 549 packages
== upgradable
== held
== curl comes from
curl: /usr/bin/curl
```

Newer Ubuntu releases describe repositories in `.sources` files (`URIs:` lines); older ones use
one-line `deb …` entries. The script reads both. An empty "upgradable" list right after `apt
update` means the server is current.

## Try it

- Run `apt-cache policy curl` and read the installed and candidate versions.
- Simulate an install with `apt-get -s install tree` and see what would be added.
- Find which package owns `/usr/bin/curl` with `dpkg -S`.
- Count your installed packages with `dpkg -l | grep -c '^ii'`.
- List the repositories your server uses under `/etc/apt/sources.list.d/`.
- Run `apt list --upgradable` after `sudo apt update` and decide what you'd upgrade first.

## Quiz

1. apt install says "Unable to locate package" for a package you know exists. What do you run first?
   - **sudo apt update, to refresh the package lists** (answer)
   - sudo apt upgrade
   - Reboot
   Why: apt install searches the local copy of each repository's index. apt update downloads fresh indexes; on a new server they're often empty or old.

2. What's the difference between apt update and apt upgrade?
   - They are the same
   - **update refreshes the lists of available packages; upgrade installs the newer versions** (answer)
   - upgrade refreshes the lists; update installs
   Why: update changes nothing installed. upgrade does the actual installing, so run update first, then upgrade.

3. Which command tells you which package installed /usr/sbin/nginx on Ubuntu?
   - which nginx
   - **dpkg -S /usr/sbin/nginx** (answer)
   - apt search nginx
   Why: dpkg -S searches the installed packages' file lists. On RHEL-family systems the same question is rpm -qf /usr/sbin/nginx.

4. A database upgrade must wait for a planned maintenance window, but other updates should continue. What do you do on Ubuntu?
   - Stop running apt upgrade
   - **sudo apt-mark hold postgresql-16 until the window, then apt-mark unhold** (answer)
   - Delete the package
   Why: A hold keeps that package at its current version while everything else updates. dnf has the same idea with the versionlock plugin.

5. Why does every repository come with a signing key?
   - To make downloads faster
   - **So apt can check each package really comes from that publisher and wasn't altered** (answer)
   - Keys are optional decoration
   Why: apt refuses packages whose signatures don't match a trusted key. That's also why adding a key is adding trust: only add keys from publishers you trust.

## Resources

- [apt(8) manual](https://manpages.ubuntu.com/manpages/noble/man8/apt.8.html) (Ubuntu manpages)
- [Ubuntu Server: package management](https://documentation.ubuntu.com/server/how-to/software/package-management/) (Ubuntu)
- [DNF command reference](https://dnf.readthedocs.io/en/latest/command_ref.html) (DNF)
- [Unattended upgrades on Ubuntu](https://documentation.ubuntu.com/server/how-to/software/automatic-updates/) (Ubuntu)
- [LPIC-1 objectives 102.4 and 102.5](https://wiki.lpi.org/wiki/LPIC-1_Objectives_V5.0) (Linux Professional Institute)
