In this chapter, we talk about applications in Linux. Sometimes, the term application (or simply app ) is used interchangeably with program , binary , or executable . We’ll explain the differences between these terms and initially will be focusing on terminology, including the definition of applications and packages.

We discuss how Linux starts up and brings all the services we depend on into being. This is also known as the boot process . We will focus on init systems, specifically on the de-facto standard, the systemd ecosystem.

We then move on to package management, where we first review the application supply chain in general terms and see what the different moving parts are about. Then, to give you some context about existing mechanisms and challenges, we focus on how apps were traditionally distributed and installed. We discuss package management in traditional Linux distros, from Red Hat to Debian-based systems, and also have a peek at programming language–specific package managers such as Python or Rust.

In the next part of the chapter, we focus on containers: what they are and how they work. We’ll review the building blocks of containers, what tooling you have available, and good practices around using containers.

To round off this chapter, we look at modern ways to manage Linux apps, especially in desktop environments. Most of those modern package manager solutions are also making use of containers in some form or another.

Running Example: greeter

To demonstrate certain technologies in this chapter, we’ll use a running example called greeter . It’s a simple shell script that echoes the name provided or a fallback greeting if nothing is provided.

If you want to follow along, now is a good time to paste the following bash script into a file called greeter.sh . Make it executable using chmod 750 greeter.sh (and if you don’t recall what this means, read up on it in “File Permissions” ):

#!/usr/bin/env bash

set -o errexit
set -o errtrace
set -o pipefail

name="${1}"

if [ -z "$name" ]
then
  printf "You are awesome!\n"
else
  printf "Hello %s, you are awesome!\n" ${name}
fi

And now, without further ado, let’s see what an application is and what other related terms there are.

Basics

Before we get into the nitty-gritty details of application management, init systems, and containers, let’s start with relevant definitions for this chapter and beyond. The reason why we only now go into details concerning apps is that there are a number of prerequisites (such as the Linux kernel, shell, filesystems, and security aspects) that you need to fully understand apps, and now that we’re in a position to build on what we’ve learned so far, we can tackle apps:

Program

This is usually either a binary file or a shell script that Linux can load into memory and execute. Another way to refer to this entity is executable . The type of the executable determines what exactly takes care of running it—for example, a shell (see “Shells” ) would interpret and execute a shell script.

Process

A running entity based on a program, loaded into main memory and either using the CPU or I/O, when not sleeping. See also “Process Management” and Chapter 3 .

Daemon

Short for daemon process , sometimes called service , this is a background process that provides a certain function to other processes. For example, a printer daemon allows you to print. There are also daemons for web services, logging, time, and many more utilities you rely on on a daily basis.

Application

A program including its dependencies. Usually a substantial program, including a user interface. We usually associate the term application with the entire life cycle of a program, its configuration, and its data: from finding and installing to upgrading to removing it.

Package

A file that contains programs and configurations; used to distribute software applications.

Package manager

A program that takes a package as an input and, based on its content and the user instruction, installs it, upgrades it, or removes it from a Linux environment.

Supply Chain

A collection of software producers and distributors that enable you to find and use applications based on packages; see “Linux Application Supply Chains” for details.

Booting

The startup sequence in Linux that involves hardware and operating system initialization steps, including loading the kernel and launching service (or daemon) programs with the goal to bring Linux into a state that it can be used; see “The Linux Startup Process” for details.

Equipped with these high-level definitions, we quite literally start at the beginning: let’s have a look at how Linux starts up and how all the daemons get launched so that we can use Linux to do our work.

The Linux Startup Process

The Linux boot process is typically a multiphase effort in which hardware and the kernel work together.

In Figure 6-1 , you can see the boot process end to end, with the following five steps:

lmlx 0601

Figure 6-1. The Linux startup process
  1. In modern environments, the Unified Extensible Firmware Interface (UEFI) spec defines the boot configuration (stored in NVRAM) and the boot loader. In older systems, in this step, after the Power On Self Test (POST) is completed, the Basic I/O System (BIOS; see “The BIOS and UEFI” ) would initialize hardware (managing I/O ports and interrupts) and hand over control to the boot loader.

  2. The boot loader has one goal: to bootstrap the kernel. Depending on the boot medium, the details may differ slightly. There are a range of boot loader options, both current (e.g., GRUB 2, systemd-boot, SYSLINUX, rEFInd) and legacy (e.g., LILO, GRUB 1).

  3. The kernel is usually located in the /boot directory in a compressed form. That means the first step is to extract and load the kernel into main memory. After the initialization of its subsystems, filesystems, and drivers (as discussed in Chapter 2 and “Mounting filesystems” ), the kernel hands over control to the init system, and with that the boot process proper ends.

  4. The init system is responsible for launching daemons (service processes) system-wide. This init process is the root of the process hierarchy and with it has the process ID (PID) 1. In other words, the process with PID 1 runs until you power off the system. Besides being responsible for launching other daemons, the PID 1 process traditionally also takes care of orphaned processes (processes that don’t have a parent process anymore).

  5. Usually, some other user-space-level initialization takes place after this, depending on the environment:

    • There is usually a terminal, environment, and shell initialization going on, as discussed in Chapter 3 .

    • Display manager, graphical server, and the like, for desktop environments with a GUI are launched, taking user preferences and configurations into account.

With this high-level overview of the Linux startup process, we conclude our introductory section and focus on a vital, user-facing component: the init systems. This part (the preceding steps 4 and 5) is the most relevant for you, in the context of this book, allowing you to customize and extend your Linux installation.

There is a good comparison of init systems available via the Gentoo wiki. We’ll restrict our discussion to systemd , which almost all current Linux distributions are using.

System V Init

System V–style init programs (or SysV init for short) were the traditional init system in Linux. Linux inherited SysV from Unix, which defines so-called runlevels (think: system states such as halt , single-user , multi-user mode, or GUI mode) with the configuration usually stored in /etc/init.d . However, the sequential way of starting up daemons and the distro-specific handling of the configuration made this a not-very-portable option.

Here’s a fun fact: one of the book reviewers, Chris, was the first person to document SysV init in about 1984 (which an engineer designed over a weekend, reportedly).

systemd

systemd was initially an init system, a replacement for initd , but today it’s a powerful supervisor that includes functions such as logging, network configuration, and network time synchronization. It provides for a flexible, portable way to define daemons and their dependencies, and a uniform interface to control the configuration.

Almost all current Linux distributions are using systemd , including Fedora since May 2011, openSUSE since September 2012, CentOS since April 2014, RHEL since June 2014, SUSE Linux since October 2014, Debian since April 2015, and Ubuntu since April 2015.

In particular, systemd addresses the shortcomings of previous init systems by doing the following:

  • Providing a uniform way to manage startup across distros

  • Implementing a faster, more comprehensible service configuration

  • Offering a modern management suite including monitoring, resource usage control (via cgroups), and built-in auditing

Additionally, init starts services at initialization time in sequence (that is, in alphanumeric order), while systemd can start any service that has had its dependencies met, potentially speeding up the startup time.

The way you tell systemd what to run, when to run, and how to run is via units.

Units

A unit in systemd is a logical grouping with different semantics depending on its function and/or the resource it targets. systemd distinguishes a number of units, depending on the target resource:

service units

Describe how to manage a service or application

target units

Capture dependencies

mount units

Define a mountpoint

timer units

Define timers for cron jobs and the like

Other, less important unit types include the following:

socket

Describes a network or IPC socket

device

For udev or sysfs filesystems

automount

Configures automatic mountpoints

swap

Describes swap space

path

For path-based activation

snapshot

Allows for reconstructing the current state of the system after changes

slice

Associated with cgroups (see “Linux cgroups” )

scope

Manages sets of system processes created externally

To be known to systemd , a unit needs to be serialized into a file. systemd looks for unit files in multiple locations. The three most important filepaths are the following:

/lib/systemd/system

Package-installed units

/etc/systemd/system

System admin–configured units

/run/systemd/system

Nonpersistent runtime modifications

With the basic unit of work (no pun intended) in systemd defined, let’s move on to how you control it via the command line.

Management with systemctl

The tool you use to interact with systemd to manage services is systemctl .

In Table 6-1 I’ve compiled a list of often-used systemctl commands.

Table 6-1. Useful systemd commands | Command | Use case | | --- | --- | | systemctl enable XXXXX.service | Enable the service; ready to be started | | systemctl daemon-reload | Reload all unit files and re-create entire dependency tree | | systemctl start XXXXX.service | Start the service | | systemctl stop XXXXX.service | Stop the service | | systemctl restart XXXXX.service | Stop and then start the service | | systemctl reload XXXXX.service | Issue reload command to service; falls back to restart | | systemctl kill XXXXX.service | Stop service execution | | systemctl status XXXXX.service | Get a short summary of service state including some log lines |

Note that there are many more commands that systemctl offers, from dependency management and query to controlling the overall system ( reboot , for example).

The systemd ecosystem has a number of other command-line tools you may find handy and that you should at least be aware of. This includes but is not limited to the following:

bootctl

Allows you to check the boot loader status and manage available boot loaders.

timedatectl

Allows you to set and view time- and date-related information .

coredumpctl

Enables you to process saved core dumps. Consider this tool when you’re troubleshooting.

Monitoring with journalctl

The journal is a component of systemd ; technically it is a binary file managed by the systemd-journald daemon, providing a centralized location for all messages logged by systemd components. We’ll cover it in detail in “journalctl” . All you need to know for now is that this is the tool that allows you to view systemd -managed logs.

Example: scheduling greeter

After all that theory, let’s see systemd in action. As a simple use case example, let’s assume we want to launch our greeter app (see “Running Example: greeter” ) every hour.

First, we define a systemd unit file of type service . This tells systemd how to start the greeter app; store the following in a file called greeter.service (in any directory, could be a temporary one):

[Unit]
Description=My Greeting Service 

[Service]
Type=oneshot
ExecStart=/home/mh9/greeter.sh

1

The description of our services, shown when we use systemctl status

2

The location of our app

Next, we define a timer unit to launch the greeter service every hour. Store the following in a file called greeter.timer :

[Unit]
Description=Runs Greeting service at the top of the hour

[Timer]
OnCalendar=hourly

1

Defines the schedule using the systemd time and date format

Now we copy both unit files to /run/systemd/system so that systemd recognizes them:

$ sudo ls -al /run/systemd/system/
total 8
drwxr-xr-x  2 root root  80 Sep 12 13:08 .
drwxr-xr-x 21 root root 500 Sep 12 13:09 ..
-rw-r--r--  1 root root 117 Sep 12 13:08 greeter.service
-rw-r--r--  1 root root 107 Sep 12 13:08 greeter.timer

We’re now in a position to use the greeter timer, since systemd automatically picked it up when we copied it into the respective directory.

Note

Debian-based systems such as Ubuntu enable and start service units by default. Red Hat family systems won’t start the service without an explicit systemctl start greeter.timer . This is also true for enabling services on boot, where Debian-based distros enable services by default, whereas Red Hat distros require an explicit confirmation in the form of systemctl enable .

Let’s check the status of our greeter timer:

$ sudo systemctl status greeter.timer
● greeter.timer - Runs Greeting service at the top of the hour
   Loaded: loaded (/run/systemd/system/greeter.timer; static; \
   vendor preset: enabled)
   Active: active (waiting) since Sun 2021-09-12 13:10:35 IST; 2s ago
  Trigger: Sun 2021-09-12 14:00:00 IST; 49min left
Sep 12 13:10:35 starlite systemd[1]: \
Started Runs Greeting service at the top of the hour.

So systemd confirms that it knows about our greeter and that it’s scheduled to run. But how do you know if it worked? Let’s check the logs (note that the output was edited and that the stdout output is going directly to the logs):

$ journalctl -f -u greeter.service 
-- Logs begin at Sun 2021-01-24 14:36:30 GMT. --
Sep 12 14:00:01 starlite systemd[1]: Starting My Greeting Service...
Sep 12 14:00:01 starlite greeter.sh[21071]: You are awesome!
...

1

Using journalctl to look at and follow ( -f ) the logs of the greeter.service unit (selected with -u )

With this high-level systemd overview, let’s move on to how to manage applications the traditional way, with general-purpose package managers . But before we get into the technicalities of packages, let’s step back a bit and discuss apps, packages, and package managers in the context of a broader concept: supply chains.

Linux Application Supply Chains

Let’s start with what we mean by supply chain : a system of organizations and individuals supplying a product to a consumer. While you may not think about supply chains a lot, you’re dealing with them on a daily basis—for example, when you buy food or fuel your car. In our discussion, the products are applications made up of software artifacts, and you can think of the consumer as either yourself as the person using an app or as a tool that manages the apps for you.

On a conceptual level, Figure 6-2 shows the main actors and phases of a typical Linux application supply chain.

lmlx 0602

Figure 6-2. Linux app supply chain

The three distinct areas in a Linux application supply are as follows:

Software maintainers

These include individual developers, open source projects, and companies, such as independent software vendors (ISVs), that produce software artifacts and publish them, for example, as packages to a repository (repo).

Repository

This lists the package that contains all or part of an app together with metadata. The package usually captures the dependencies of an app. Dependencies are other packages that an app needs in order to function. This can be a library, some kind of exporters or importers, or other service programs. Keeping these dependencies up to date is hard.

Tooling (a package manager)

On the target-system side, this can look up packages in the repository and install, update, and remove apps as instructed by the human user. Note that one or more packages can represent the app and its dependencies.

While the details may differ from distribution to distribution and depend on the environment (server, desktop, etc.), the app supply chains all have the elements shown in Figure 6-2 in common.

There are many options available for package and dependency management, such as traditional package managers, container-based solutions, and more recent approaches.

In Figure 6-3 , I’ve tried to give you a high-level overview, without claiming this is a complete picture.

lmlx 0603

Figure 6-3. The Linux package management and application dependency management universe

A few notes on the three primary categories of options for package and dependency management:

Traditional package managers

Within this category, we usually differentiate between low-level and high-level tooling. If a package manager can resolve dependencies and provides a high-level interface (install, update, remove), we call it a high-level package manager.

Container-based solutions

These initially came out of the server and cloud computing realm. Given their capabilities, one use case, but not necessarily their primary one, is application management. In other words, as a developer you’ll love containers since they enable you to easily test things and make it straightforward to ship your production-ready app. See also “Containers” .

Modern package managers

These have their roots in desktop environments, and the main goal here is to make it as easy as possible for the end user to consume apps. See also “Modern Package Managers” .

Packages and Package Managers

In this section, we discuss package formats and package managers that have been in use for a long time, in some cases decades. These usually stem from two major Linux distribution families: Red Hat (RHEL, Fedora, CentOS, etc.) and Debian-based systems (Debian, Ubuntu, etc.).

The two concepts relevant to our discussions here are the following:

The packages themselves

Technically a file that usually is zipped and may contain metadata.

The tooling (called package managers )

Deals with those packages on the target system, to install and maintain apps. A package manager usually interacts with the repo on your behalf and maintains a local cache of packages.

The target system may be a desktop environment on your laptop or a server VM instance in the cloud, for example. Depending on the environment, packages may be more or less applicable—for example, a GUI app on a server is not necessarily something that makes sense.

RPM Package Manager

RPM Package Manager (for which the recursive acronym RPM is used) was originally created by Red Hat but is now widely used in various distros. The .rpm file format is used in Linux Standard Base and can contain binary or source files. The packages can be cryptographically verified and support delta updates via patch files.

Package managers that use RPM include the following:

yum

In Amazon Linux, CentOS, Fedora, and RHEL

DNF

In CentOS, Fedora, and RHEL

Zypper

In openSUSE and SUSE Linux Enterprise

Let’s see RPM in action: let’s say we have a fresh developer environment and want to install the Go programming language tool chain using yum .

Note that the output in the following shell sessions has been edited and shortened to fit the space (there are many lines in the output that are not relevant to understanding the usage).

First off, we need to find the package for Go:

# yum search golang 
Loaded plugins: ovl, priorities
================= N/S matched: golang =================
golang-bin.x86_64 : Golang core compiler tools
golang-docs.noarch : Golang compiler docs
...
golang-googlecode-net-devel.noarch : Supplementary Go networking libraries
golang-googlecode-sqlite-devel.x86_64 : Trivial sqlite3 binding for Go

1

Search for the Go package. Note the # prompt, suggesting we’re logged in as root. Perhaps a better way would be to use sudo yum .

Equipped with this info about the package, we can now install it using the following:

# yum install golang 
Loaded plugins: ovl, priorities
Resolving Dependencies 
--> Running transaction check
---> Package golang.x86_64 0:1.15.14-1.amzn2.0.1 will be installed
--> Processing Dependency: golang-src = 1.15.14-1.amzn2.0.1 for package:
    golang-1.15.14-1.amzn2.0.1.x86_64
...
Transaction Summary
===============================================================================
Install  1 Package (+101 Dependent packages)

Total download size: 183 M
Installed size: 624 M
Is this ok [y/d/N]: y 
Dependencies Resolved

===============================================================================
 Package                     Arch    Version             Repository    Size
===============================================================================
Installing:
 golang                      x86_64  1.15.14-1.amzn2.0.1 amzn2-core    705 k
Installing for dependencies:
 acl                         x86_64  2.2.51-14.amzn2     amzn2-core     82 k
 apr                         x86_64  1.6.3-5.amzn2.0.2   amzn2-core    118 k
 ...

  Verifying  : groff-base-1.22.2-8.amzn2.0.2.x86_64                     101/102
  Verifying  : perl-Text-ParseWords-3.29-4.amzn2.noarch                 102/102

Installed: 
  golang.x86_64 0:1.15.14-1.amzn2.0.1

Dependency Installed:
  acl.x86_64 0:2.2.51-14.amzn2   apr.x86_64 0:1.6.3-5.amzn2.0.2
  ...

Complete!

1

Install the Go package.

2

yum ’s first step is to determine Go’s dependencies.

3

Here yum provides us with a summary of what it found in terms of dependencies and tells us what it plans to do. I need to confirm here interactively by entering a y . However, in a script I would use the yum install golang -y form of the command to automatically accept this.

4

After verifying that all dependencies and the main package are installed, yum reports success.

Last but not least, we want to verify the package, checking exactly what we have installed and where:

# yum info golang
Loaded plugins: ovl, priorities
Installed Packages
Name        : golang
Arch        : x86_64
Version     : 1.15.14
Release     : 1.amzn2.0.1
Size        : 7.8 M
Repo        : installed
From repo   : amzn2-core
Summary     : The Go Programming Language
URL         : http://golang.org/
License     : BSD and Public Domain
Description : The Go Programming Language.

Next , let’s have a look at the other widely used package manager using Debian packages.

Debian deb

deb packages and the .deb file format originate from the Debian distro. The deb packages can also contain binary or source files. Multiple package managers use deb, including low-level, no-dependency-management ones such as dpkg , and high-level ones such as apt-get , apt , and aptitude . Given that Ubuntu is a Debian-based distro, deb packages are widely used, on the desktop and server alike.

To see deb packages in action, let’s assume we want to install the curl utility with apt . This is a useful tool to interact with HTTP APIs and to download files from a range of locations. Note that we again edited the output to make it fit.

First, we search for the curl package:

# apt search curl 
Sorting... Done
Full Text Search... Done
curl/focal-updates,focal-security 7.68.0-1ubuntu2.6 amd64
  command line tool for transferring data with URL syntax

curlftpfs/focal 0.9.2-9build1 amd64
  filesystem to access FTP hosts based on FUSE and cURL

flickcurl-doc/focal 1.26-5 all
  utilities to call the Flickr API from command line - documentation

flickcurl-utils/focal 1.26-5 amd64
  utilities to call the Flickr API from command line

gambas3-gb-net-curl/focal 3.14.3-2ubuntu3.1 amd64
  Gambas advanced networking component
...

1

Search for the curl package with apt . Note that there were overall dozens of more search results shown, most of them libraries and language-specific bindings (Python, Ruby, Go, Rust, etc.).

Next, we install the curl package like so:

# apt install curl 
Reading package lists... Done
Building dependency tree 
Reading state information... Done
The following additional packages will be installed:
  ca-certificates krb5-locales libasn1-8-heimdal libbrotli1 ...

Suggested packages:
  krb5-doc krb5-user libsasl2-modules-gssapi-mit ...

The following NEW packages will be installed:
  ca-certificates curl krb5-locales libasn1-8-heimdal ...

0 upgraded, 32 newly installed, 0 to remove and 2 not upgraded.
Need to get 5447 kB of archives.
After this operation, 16.7 MB of additional disk space will be used.
Do you want to continue? [Y/n] 

Get:1 http://archive.ubuntu.com/ubuntu focal-updates/main amd64
      libssl1.1 amd64 1.1.1f-1ubuntu2.8 [1320 kB]
Get:2 http://archive.ubuntu.com/ubuntu focal-updates/main amd64
      openssl amd64 1.1.1f-1ubuntu2.8 [620 kB]
...
Fetched 5447 kB in 1s (3882 kB/s)
Selecting previously unselected package libssl1.1:amd64.
(Reading database ... 4127 files and directories currently installed.)
Preparing to unpack .../00-libssl1.1_1.1.1f-1ubuntu2.8_amd64.deb ...
Unpacking libssl1.1:amd64 (1.1.1f-1ubuntu2.8) ...
...
Setting up libkeyutils1:amd64 (1.6-6ubuntu1) ...
...
Processing triggers for ca-certificates (20210119~20.04.1) ...
Updating certificates in /etc/ssl/certs...
1 added, 0 removed; done. 
Running hooks in /etc/ca-certificates/update.d...
Done.

1

Install the curl package.

2

apt ’s first step is to determine the dependencies.

3

Here apt provides us with a dependencies summary and tells us what it will install. Interactive confirmation is needed here; in a script I would use apt install curl -y to automatically accept it.

4

After verifying that all dependencies and the main package are installed, apt reports success.

And finally we verify the curl package:

# apt show curl
Package: curl
Version: 7.68.0-1ubuntu2.6
Priority: optional
Section: web
Origin: Ubuntu
Maintainer: Ubuntu Developers <[email protected]>
Original-Maintainer: Alessandro Ghedini <[email protected]>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 411 kB
Depends: libc6 (>= 2.17), libcurl4 (= 7.68.0-1ubuntu2.6), zlib1g (>= 1:1.1.4)
Homepage: http://curl.haxx.se
Task: server, cloud-image, ubuntu-budgie-desktop
Download-Size: 161 kB
APT-Manual-Installed: yes
APT-Sources: http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages
Description: command line tool for transferring data with URL syntax

N: There is 1 additional record. Please use the '-a' switch to see it

Let’s now move on to programming language–specific package managers.

Language-Specific Package Managers

There are also programming language–specific package managers, such as the following:

C/C++

Have many different package managers , including Conan and vcpkg

Go

Has package management built in ( go get , go mod )

Node.js

Has npm and others

Java

Has maven and nuts and others

Python

Has pip and PyPM

Ruby

Has rubygems and Rails

Rust

Has cargo

With that, let’s look at containers and how you can manage applications with them.

Containers

In the context of this book, we understand a container as a Linux process group that uses Linux namespaces, cgroups, and optionally CoW filesystems to provide application-level dependency management. Use cases for containers range from local testing and development to working with distributed systems—for example, working with containerized microservices in Kubernetes .

While containers are very useful for developers and sys admins, as an end user you will more likely be comfortable using higher-level tooling to manage applications—for example, the ones discussed in “Modern Package Managers” .

If Only I Had Containers

In a previous job, I once had to put together a proof of concept that involved a time series database called InfluxDB. The overall setup required a number of prerequisites (directories created, data copied) as well as dependencies installed. When it came to handing it over to a colleague for demonstration to the customer, I ended up writing up a detailed document that enumerated all the steps and checks to make sure everything worked as planned.

If only at that time container solutions such as Docker had been available, I could have saved myself and my colleague a lot of time by simply packaging up everything into a container. This would not only have made it easy to use for my colleague, but I could also guarantee that it would run in their environment exactly as it did on my laptop.

Containers are, per se, nothing new in Linux. However, they’ve enjoyed mainstream adoption only due to Docker, starting in roughly 2014. Before that, we had a number of attempts to introduce containers, often targeting system administrators rather than developers, including the following:

What all of these approaches have in common is that they use the basic building blocks the Linux kernel provides, such as namespaces or cgroups, to allow users to run applications.

Docker innovated on the concept and introduced two groundbreaking elements: a standardized way to define the packaging via container images and a human-friendly user interface (for example, docker run ). The way container images are defined and distributed, as well as how containers are executed, formed the basis for what is now known as the Open Container Initiative (OCI) core specifications. When we talk about containers here, we focus on OCI-compliant implementations.

The three core OCI container specifications are as follows:

Runtime specification

Defines what a runtime needs to support, including operations and life-cycle phases

Image format specification

Defines how container images are constructed, based on metadata and layers

Distribution specification

Defines how container images are shipped, effectively the way repositories work in the context of containers

Another idea associated with containers is immutability . This means that once a configuration is put together, you cannot change it during its usage. In other words, changes require creating a new (static) configuration and a new resource (such as a process) with it. We will revisit this in the context of container images.

Now that you’re aware of what containers are on a conceptual level, let’s have a closer look at the building blocks of OCI-compliant containers.

Linux Namespaces

As we discussed in Chapter 1 , Linux initially had a global view on resources. To allow processes to have a local view on a resource (such as a filesystem, networking, or even users), Linux introduced namespaces.

In other words, Linux namespaces are all about resource visibility and can be used to isolate different aspects of the operating system resources. Isolation in this context is mostly about what a process sees, not necessarily a hard boundary (from a security perspective).

To create namespaces, you have three relevant syscalls at your disposal:

clone

Used to create a child process that can share parts of its execution context with the parent process

unshare

Used to remove a shared execution context from an existing process

setns

Used to join an existing process to an existing namespace

The preceding syscalls take a range of flags as parameters, enabling you to have fine-grained control over the namespaces you want to create, join, or leave:

CLONE_NEWNS

Use for filesystem mount points . Visible via /proc/$PID/mounts . Supported since Linux 2.4.19.

CLONE_NEWUTS

Use to create hostname and (NIS) domain name isolation. Visible via uname -n and hostname -f . Supported since Linux 2.6.19.

CLONE_NEWIPC

Use to do interprocess communication (IPC) resource isolation like System V IPC objects or POSIX message queues. Visible via /proc/sys/fs/mqueue , /proc/sys/kernel , and /proc/sysvipc . Supported since Linux 2.6.19.

CLONE_NEWPID

Use for PID number space isolation (PID inside/PID outside the namespace). You can gather details about it via /proc/$PID/status . Supported since Linux 2.6.24.

CLONE_NEWNET

Use to control visibility of network system resources such as network devices, IP addresses, IP routing tables, and port numbers. You can view it via ip netns list , /proc/net , and /sys/class/net . Supported since Linux 2.6.29.

CLONE_NEWUSER

Use to map UID+GIDs inside/outside the namespace. You can query UIDs and GIDs and their mappings via the id command and /proc/$PID/uid_map and /proc/$PID/gid_map . Supported since Linux 3.8.

CLONE_NEWCGROUP

Use to manage cgroups in a namespace . You can see it via /sys/fs/cgroup , /proc/cgroups , and /proc/$PID/cgroup . Supported since Linux 4.6.

One way to view namespaces in use on your system is as follows (output edited to fit):

$ sudo lsns
        NS TYPE   NPROCS   PID USER             COMMAND
4026531835 cgroup    251     1 root             /sbin/init splash
4026531836 pid       245     1 root             /sbin/init splash
4026531837 user      245     1 root             /sbin/init splash
4026531838 uts       251     1 root             /sbin/init splash
4026531839 ipc       251     1 root             /sbin/init splash
4026531840 mnt       241     1 root             /sbin/init splash
4026531860 mnt         1    33 root             kdevtmpfs
4026531992 net       244     1 root             /sbin/init splash
4026532233 mnt         1   432 root             /lib/systemd/systemd-udevd
4026532250 user        1  5319 mh9              /opt/google/chrome/nacl_helper
4026532316 mnt         1   684 systemd-timesync /lib/systemd/systemd-timesyncd
4026532491 mnt         1   688 systemd-resolve  /lib/systemd/systemd-resolved
...

The next container building block focuses on resource consumption limits and reporting on resource usage.

Linux cgroups

Where namespaces are about visibility, cgroups provide a different kind of functionality: they are a mechanism to organize process groups. Along with the hierarchical organization, you can use cgroups to control system resources usage. In addition, cgroups provide resource usage tracking; for example, they show how much RAM or CPU seconds a process (group) is using. Think of cgroups as the declarative unit and the controller as a piece of kernel code that enforces a certain resource limitation or reports on its usage.

At this time of writing, there are two versions of cgroups available in the kernel: cgroups v1 and v2. cgroup v1 is still widely used, but v2 will eventually replace v1, so you should focus on v2.

cgroup v1

With cgroup v1 , the community had an ad hoc approach, adding new cgroups and controllers as needed. The following v1 cgroups and controllers exist (ordered from oldest to newest; note that the docs are all over the place and inconsistent):

CFS bandwidth control

Used via the cpu cgroup. Supported since Linux 2.6.24.

CPU accounting controller

Used via the cpuacct cgroup. Supported since Linux 2.6.24.

cpusets cgroup

Allows you to assign CPU and memory to a task. Supported since Linux 2.6.24.

Memory resource controller

Allows you to isolate the memory behavior of tasks. Supported since Linux 2.6.25.

Device whitelist controller

Allows you to control device file usage. Supported since Linux 2.6.26.

freezer cgroup

Used for batch job management. Supported since Linux 2.6.28.

Network classifier cgroup

Used to assign different priorities to packets. Supported since Linux 2.6.29.

Block IO controller

Allows you to throttle block I/O. Supported since Linux 2.6.33.

perf_event command

Allows you to collect performance data. Supported since Linux 2.6.39.

Network priority cgroup

Allows you to dynamically set the priority of network traffic. Supported since Linux 3.3.

HugeTLB controller

Allows you to limit HugeTLB usage. Supported since Linux 3.5.

Process number controller

Used to allow a cgroup hierarchy to stop creating new processes after a certain limit is reached. Supported since Linux 4.3.

cgroup v2

cgroup v2 is a total rewrite of cgroups with the lessons learned from v1. This is true both in terms of consistent configuration and use of the cgroups as well as the (centralized and uniform) documentation. Unlike the per-process cgroup v1 design, cgroup v2 has only single hierarchy, and all controllers are managed the same way. Here are the v2 controllers:

CPU controller

Regulates distribution of CPU cycles, supporting different models (weight, max) and includes usage reporting

Memory controller

Regulates distribution of memory with a range of control parameters, supporting user-space memory, kernel data structures such as dentries and inodes, and TCP socket buffers

I/O controller

Regulates the distribution of I/O resources with both weight-based and absolute bandwidth or I/O operations per second (IOPS) limits, reporting on bytes and IOPS read/writes

Process number (PID) controller

Is similar to the v1 version

cpuset controller

Is similar to the v1 version

device controller

Manages access to device files, implemented on top of eBPF

rdma controller

Regulates the distribution and accounting of remote direct memory access (RDMA) resources

HugeTLB controller

Is similar to the v1 version

There are also miscellaneous cgroups in v2 that allow resource limits and tracking mechanisms for scalar resources (which can’t be abstracted like other cgroup resources).

You can view all of the v2 cgroups in your Linux system in a nice tree rendering via the systemctl command, as shown in the following example (output shortened and edited to fit):

$ systemctl status 
starlite
    State: degraded
     Jobs: 0 queued
   Failed: 1 units
    Since: Tue 2021-09-07 11:49:08 IST; 1 weeks 1 days ago
   CGroup: /
           ├─22160 bpfilter_umh
           ├─user.slice
           │ └─user-1000.slice 
           │   ├─[email protected]
           │   │ ├─gvfs-goa-volume-monitor.service
           │   │ │ └─14497 /usr/lib/gvfs/gvfs-goa-volume-monitor
   ...

1

Using the systemctl tool to render cgroups

2

An example of a specific cgroup that systemd manages

Another useful view on cgroups is interactive resource usage, as shown in the following (output edited to fit):

$ systemd-cgtop
Control Group                        Tasks   %CPU   Memory  Input/s Output/s
/                                      623   15.7     5.8G        -        -
/docker                                  -      -    48.3M        -        -
/system.slice                          122    6.2     1.6G        -        -
/system.slice/ModemManager.service       3      -   748.0K        -        -
...
/system.slice/rsyslog.service            4      -   420.0K        -        -
/system.slice/snapd.service             17      -     5.1M        -        -

Going forward, you can expect that, as modern kernel versions are more widely used, the cgroups v2 will become the standard. There are indeed certain distros, such as Arch , Fedora 31+, and Ubuntu 21.10, that already have v2 by default.

Copy-on-Write Filesystems

The third building block of containers are CoW filesystems, as discussed in greater detail in “Copy-on-Write Filesystems” . These are used at build time. They package the application and all of its dependencies into a single, self-contained file that you can distribute. Usually the CoW filesystems are used in combination with bind mounts to layer the content of the different dependencies on top of each other in an efficient manner.

Docker

Docker is a human-friendly container implementation developed and popularized by Docker Inc. in 2014. With Docker, it’s easy to package up programs and their dependencies and launch them in a range of environments, from desktops to the cloud. What’s so unique about Docker is not the building blocks (namespaces, cgroups, CoW filesystems, and bind mounts). These existed a while before Docker came into being. What’s so special is that Docker combined these building blocks in a way that makes them easy to use by hiding the complexity of managing the low-level bits like namespaces and cgroups.

As shown in Figure 6-4 and described in the passage that follows, there are two main concepts in Docker: the image and the running container.

lmlx 0604

Figure 6-4. High-level Docker architecture

The container image

A compressed archive file that contains metadata in JSON files and the layers, which are effectively directories. The Docker daemon pulls the container images as needed from a container registry.

The container as the runtime artifact (for example, app A/B/C)

You can start, stop, kill, and remove it. You interact with the Docker daemon using a client CLI tool ( docker ). This CLI tool sends commands to the daemon, which in turn executes the respective operation, such as building or running a container.

Table 6-2 presents a short reference of often-used Docker CLI commands, covering both the build-time and the runtime phases. To get the full reference, including use cases, refer to the Docker docs .

Table 6-2. Often-used Docker commands | Command | Description | Example | | --- | --- | --- | | run | Launch a container | Run NGINX as a daemon and remove container on exit: docker run -d --rm nginx:1.21 | | ps | List containers | List all containers (including nonrunning): docker ps -a | | inspect | Display low-level info | To query the container IP: docker inspect -f '{{.Network​Set⁠tings.IPAddress}}' | | build | Generate a container image locally | Build image based on current directory and tag: docker build -t some:tag . | | push | Upload a container image to a registry | Push to AWS registry: docker push public.ecr.aws/some:tag | | pull | Download a container image from a registry | Pull from AWS registry: docker pull public.ecr.aws/some:tag | | images | List local container images | List images from a certain registry: docker images ubuntu | | image | Manage container images | Remove all unused images: docker image prune -all |

Let’s now have a closer look at the build-time artifact: the container image that Docker uses.

Container Images

To define the instructions on how to build a container image, you use a plain text file format called Dockerfile .

There are different directives you can have in a Dockerfile:

Base images

FROM ; can be multiple for build/run phases

Metadata

LABEL for lineage

Arguments and environment variables

ARGS , ENV

Build-time specifications

COPY , RUN , etc., which define how the image is constructed, layer for layer

Runtime specifications

CMD and ENTRYPOINT , which define how the container can be run

Using the docker build command, you turn a collection of files that represent your application (either as source or in binary format), along with the Dockerfile, into a container image. This container image is the artifact that you can then run or push to a registry, in order to distribute it for others to pull and eventually run.

Running containers

You can run containers with interactive input (terminal attached) or as daemons (background). The docker run command takes a container image and a set of runtime inputs, such as environment variables, ports to expose, and volumes to mount. With this information, Docker creates the necessary namespaces and cgroups and launches the application defined in the container image ( CMD or ENTRYPOINT ).

With the Docker theory out of the way, let’s see it in action.

Example: containerized greeter

Let’s now put our greeter app (see “Running Example: greeter” ) into a container and run it.

First off, we need to define the Dockerfile, which contains the instructions to build the container image:

FROM ubuntu:20.04 
LABEL org.opencontainers.image.authors="Michael Hausenblas" 
COPY greeter.sh /app/ 
WORKDIR /app 
RUN chown -R 1001:1 /app 
USER 1001
ENTRYPOINT ["/app/greeter.sh"]

1

Define the base image using an explicit tag ( 20.04 ).

2

Assign some metadata via a label .

3

Copy shell script. This could be a binary, a JAR file, or a Python script.

4

Set the working directory.

5

This and the next line define the user running the app. If you don’t do this, it will unnecessarily run as root .

6

Define what to run, in our case the shell script. The way we defined it, using ENTRYPOINT , it is possible to pass a parameter by running docker run greeter:1 _SOME_PARAMETER_ .

Next, we build the container image:

$ sudo docker build -t greeter:1 . 
Sending build context to Docker daemon  3.072kB
Step 1/7 : FROM ubuntu:20.04 
20.04: Pulling from library/ubuntu
35807b77a593: Pull complete
Digest: sha256:9d6a8699fb5c9c39cf08a0871bd6219f0400981c570894cd8cbea30d3424a31f
Status: Downloaded newer image for ubuntu:20.04
 ---> fb52e22af1b0
Step 2/7 : LABEL org.opencontainers.image.authors="Michael Hausenblas"
 ---> Running in 6aa921276c3b
Removing intermediate container 6aa921276c3b
 ---> def717e3352b
Step 3/7 : COPY greeter.sh /app/
 ---> 5f3eb160fea3
Step 4/7 : WORKDIR /app
 ---> Running in 698c29938a96
Removing intermediate container 698c29938a96
 ---> d73572886c13
Step 5/7 : RUN chown -R 1001:1 /app
 ---> Running in 5b5eb5d1935a
Removing intermediate container 5b5eb5d1935a
 ---> 42c35a6db6e2
Step 6/7 : USER 1001
 ---> Running in bec92deaac6e
Removing intermediate container bec92deaac6e
 ---> b6e0e27f253b
Step 7/7 : CMD ["/app/greeter.sh"]
 ---> Running in 6d3b439f7e50
Removing intermediate container 6d3b439f7e50
 ---> 433a5f10d84e
Successfully built 433a5f10d84e
Successfully tagged greeter:1

1

Build the container image and label it (with -t greeter:1 ). The . means that it uses the current directory and assumes that a Dockerfile is present there.

2

This and the next lines pull the base image and build it layer by layer.

Let’s check if the container image is there:

$ sudo docker images
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
greeter      1         433a5f10d84e   35 seconds ago   72.8MB
ubuntu       20.04     fb52e22af1b0   2 weeks ago      72.8MB

Now we can run a container based on the greeter:1 image, like so:

 $ sudo docker run greeter:1
You are awesome!

That wraps up our Docker 101 . We’ll now take a quick look at related tooling.

Other Container Tooling

You don’t have to use Docker to work with OCI containers; as an alternative, you can use a Red Hat–led and –sponsored combo: podman and buildah . These daemon-less tools allow you to build OCI container images ( buildah ) and run them ( podman ).

In addition, there are a number of tools that make working with OCI containers, namespaces, and cgroups easier, including but not limited to the following:

containerd

A daemon that manages the OCI container life cycle, from image transfer and storage to container runtime supervision

skopeo

For container image manipulation (copying, inspecting manifest, etc.)

systemd-cgtop

A kind of cgroups-aware variant of top that shows resource usage interactively

nsenter

Allows you to execute a program in a specified, existing namespace

unshare

Allows you to run a program with specific namespaces (opt in via flags)

lsns

Lists information about Linux namespaces

cinf

Lists information about Linux namespaces and cgroups associated with process IDs

With this we end our containers tour. Let’s now look at modern package managers and how they utilize containers to isolate applications from each other.

Modern Package Managers

In addition to the more traditional package managers that often are distribution-specific, there is a new sort of package manager. These modern solutions often make use of containers and aim to be cross-distribution or target specific environments. For example, they can make it easy for Linux desktop users to install GUI apps.

Snap

A Canonical Ltd.–designed and –promoted software packaging and deployment system. It comes with a refined sandboxing setup and can be used in desktop, cloud, and IoT environments.

Flatpak

Optimized for Linux desktop environments, using cgroups, namespaces, bind mounts, and seccomp as its building blocks. While initially from the Red Hat part of the Linux distro universe, it is now available for dozens of distros, including Fedora, Mint, Ubuntu, Arch, Debian, openSUSE, and Chrome OS.

AppImage

Has been around for years and promotes the idea that one app equals one file; that is, it requires no dependencies other than what is included in the targeted Linux system. Over time, a number of interesting features have found their way into AppImage, from efficient updates to desktop integration to software catalogs.

Homebrew

Originally from the macOS world but available for Linux and enjoying increasing popularity. It’s written in Ruby and has a powerful yet intuitive user interface.

Conclusion

In this chapter, we covered a wide range of topics, all related to how to install, maintain, and use applications on Linux.

We first defined basic application terms, then we looked at the Linux startup process, discussing systemd , the now standard way of managing startup and components.

To distribute applications, Linux uses packages and package managers. We discussed various managers in this context and how you can use containers for development and testing as well as dependency management. Docker containers use Linux primitives (cgroups, namespaces, CoW filesystems) to provide you with application-level dependency management (via container images).

Finally, we looked at custom solutions for app management, including Snap and others.

If you’re interested in further reading on the topics in this chapter, have a look at the following resources:

Startup process and init systems

Package management

Containers

Now that you know all the basics around applications let’s move on from the scope of a single Linux system to an interconnected setup and its necessary precondition: networking.