Skip to content
ImagineWorld

Configuring Software

node_idnode-book_the-software-developer-s-guide-to-linux_chapter-08-configuring-software
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleConfiguring Software
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Sooner or later, everyone has to configure software on a Linux system. And while there are many ways to do that, there is thankfully a general pattern that you can follow to get the results you want. On Linux, this is especially common; because much of the standard tooling in Linux follows the “small, sharp tools” philosophy, the tendency is toward lots of small, powerful programs that provide flexibility by supporting extensive configuration.

In this chapter, you’ll learn about the configuration hierarchy that well-designed programs tend to use. Whether you just need to check a manual page to find a command-line argument for a single command or whether you want to set an environment variable that applies to all commands you run in your shell, you’ll see how to do it.

From there, we’ll show you the general configuration hierarchy that almost all Unix software uses, so that you’ll always know where to check if a program isn’t quite behaving how you expect based on the configuration you’ve given it.

Finally, you’ll see how this configuration translates to programs managed through systemd, the most popular service management tool on Linux.

To summarize, this chapter will cover the following topics:

  • The configuration hierarchy
  • Command-line arguments
  • Environment variables
  • Configuration files
  • Configuration in Docker

One of the first things that you’ll do when running programs on Linux is to tweak them to your specific needs. In fact, you’ve already done that: by passing arguments to commands like ls, grep, and others, you have changed how these programs behave.

You probably have an intuitive feeling about how this should work because you’ve been around software your whole life. For example, it might seem natural to you that passing command-line arguments would override program defaults: ls -l gives you output that’s different from the default output of ls.

Let’s now dive into this intuition a bit more rigorously and see if we can map out some heuristics for how configuration generally works in a Unix environment. One of the norms that most standard Unix command-line programs conform to is a specific configuration hierarchy, where earlier values are overridden by later values. If you’ve written software that takes user configuration, you may have created a priority hierarchy like this before:

  1. Set configurable values to built-in defaults.
  2. Check for values passed via configuration files, overriding those defaults.
  3. Check for environment variables (people may refer to these as env vars), overriding configuration files and earlier values.
  4. Check for command-line interface arguments (you may hear these referred to as CLI args), and update values as necessary, overriding earlier values.

Each successive level is closer to the user running the software at a specific moment, and so each successive level takes priority over the previous one.

For example, if your software detects conflicting values in the config file and the CLI arguments that the program was launched with, it should prefer the value in the command-line arguments. In other words, the values found closer to the program’s invocation “ shadow ” (in the sense of obscuring or replacing) the values further away from execution. The CLI argument value replaces the configuration file value because the configuration file is further away from the point of invocation than the arguments passed to the program when it’s started. That should make intuitive sense: you can’t depend on software if it ignores your command-line flags in favor of program defaults. ls -l shouldn’t give you the same output as ls.

Most software on Linux follows this hierarchy when there are multiple ways to configure that software. Keep in mind that not all software uses all the configuration paths we’ll show as examples here, and not all software respects this configuration order exactly.

Let’s look at this hierarchy again, but this time, connecting it to practical, specific examples for the nginx web server program. You’ll likely get to work with nginx at some point in your career, since it’s one of the most popular web servers in the world, used to front all kinds of dynamic web applications. Let’s see how each part of the priority hierarchy we just covered maps to practical nginx configuration:

  1. Built-in defaults: The hardcoded nginx default for the user that it executes as after starting up is nobody.
  2. Global configuration files can change this for all nginx processes, so it’s common to find a global nginx configuration file at /etc/nginx/nginx.conf with the value “ user www;” which instructs nginx to run as the www user instead.
  3. User-level configuration files are typically “dot-files” (files named with a leading . character, which excludes them from regular ls listings) in the User’s /home directory. For example, /home/dave/.bashrc is a place for user-specific bash configuration. nginx is a long-running process that doesn’t usually run as a regular Linux user, but it does have something like this: individual sites are often configured in their own, separate configuration files at /etc/nginx/conf.d/yourwebsite.conf. These usually inherit values from the global configuration from the previous level.
  4. Environment variables. nginx gets timezone information from an environment variable named TZ.
  5. Command-line arguments are specified when software is run, either manually or in an automated way (for example via cron, or unit files). Make sure to look at these possible external sources of command-line arguments when debugging a problem – they’re frequent culprits when you see a disparity between program behavior and the configuration files. nginx takes various command-line arguments that modify its behavior: from overriding the configuration files it will use to preventing it from acting as a web server entirely and instead signaling an already-running nginx process to stop or reload.

Now that you’ve seen both the theoretical and practical aspects of how this configuration hierarchy interacts with all the programs you run on Linux, and all the programs you might write for it, let’s go through the configuration hierarchy step by step to take a closer look at each level. We’ll start with the most direct and powerful form of configuration, which overrides everything else: passing command-line arguments at the moment in which you invoke a program.

You’re already familiar with the most common way to configure programs: with command-line arguments. These configure a program at the moment it’s invoked as a shell command.

To find valid command-line arguments for a program, start with the man (manual) page for your command. Except on the most minimal systems, Unix software ships with manual pages that document most programs, explain available flags, and – usually at the end – list other kinds of configuration methods, like configuration files.

Let’s look at the beginning of the man page content for the find command:

man find
FIND(1) General Commands Manual FIND(1)
NAME
find – walk a file hierarchy
SYNOPSIS
find [-H | -L | -P] [-EXdsx] [-f path] path ... [expression]
find [-H | -L | -P] [-EXdsx] -f path [path ...] [expression]
DESCRIPTION
The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the "primaries" and "operands" listed
below) in terms of each file in the tree.
The options are as follows:
-E Interpret regular expressions followed by -regex and -iregex primaries as extended (modern) regular expressions rather than basic regular expressions
(BRE's). The re_format(7) manual page fully describes both formats.
-H Cause the file information and file type (see stat(2)) returned for each symbolic link specified on the command line to be those of the file
referenced by the link, not the link itself. If the referenced file does not exist, the file information and type will be for the link itself. File
information of all symbolic links not on the command line is that of the link itself.

You can see that most of this manual page documents the various command-line arguments that are available when running find. You’ve used plenty of command-line arguments since Chapter 1, so this should all feel familiar.

Let’s look at the next, slightly more distant kind of configuration: environment variables.

While a command-line argument is powerful, it applies only to the single program invocation that it’s a part of. When you type ls -l, only that one ls command will have the long-form output. But what if you want a configuration value to persist over multiple invocations of a command? This is useful if, for example, you’re writing a script that will install packages at a few different points, and you want to set a configuration option once instead of having to add it over and over again as a command-line argument every single time you run the package installation command. That’s where environment variables come in.

As a developer writing any kind of software, you are likely aware of environment variables: shell values that are analogous to variables in any other programming language. These differ from command-line arguments because they operate one level higher. Environment variables give you more leverage: once you set a configuration variable in the shell, it applies to all program invocations made in that shell session. Set it once, and a program that looks for the environment variable will respect it every time it’s run, until the variable changes or you end the shell session.

Note

We’ll dive deeper into environment variables in Chapter 12, Automating Tasks with Shell Scripts, but this section covers the basics.

Most standard Unix environments use environment variables as a means to specify common configurations that are relevant to many different programs, not just one. For example, environment variables keep track of where the User’s /home directory can be found ($HOME), what the current working directory is ($PWD), which shell should be used by default ($SHELL), where to look for the executable files that correspond to commands received via the CLI ($PATH), and so on.

Feel free to inspect them right now; you can see the value of a specific environment variable by printing it out with the echo command:

$ echo $SHELL
/bin/zsh

Or you can use the env command to see all of the environment variables currently set:

$ env
...
# many lines of output, one for each of your environment variables ...

To set an environment variable in your current shell, simply use = for assignment (ensure that there are no spaces around the equals sign):

MYVAR=fruitloops

You’ve set it for your current shell:

$ echo $MYVAR
fruitloops

To persist this variable for any subshells you spawn (for example, when you run a script), use the export builtin:

export MYVAR=fruitloops

You’ll learn more in Chapter 12, Automating Tasks with Shell Scripts, but the above command is the extent of what you’ll need to pass environment variable configuration to most programs you interact with.

Back to the find example: if you scroll down far enough on the find man page, which we looked at in the previous section, you’ll see a section titled ENVIRONMENT:

ENVIRONMENT
The LANG, LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES and LC_TIME environment variables affect the execution of the find utility as described in environ(7).

This is a different level of configuration – instead of being passed as command arguments at runtime, these are the configuration directives that can be read from shell environment variables.

Why should a program treat environment variables differently from arguments? Let’s think it through: the command-line argument –H is incredibly specific because it is defined at the command invocation level. As a result, it applies only to the command being run at that instant.

On the other hand, environment variables are less specific. They’re defined at the shell level and, therefore, are available to all commands run from that shell.

Let’s keep walking up the configuration hierarchy: if a value isn’t set at runtime in a command-line argument, or as an environment variable in the shell session that a program is launched from, where does configuration come from?

The next place a program looks for configuration is in its configuration files. Where a program looks for configuration can vary wildly, but there are a few standard places to look.

First, the /etc/ directory is a good place to start. You’ve seen this directory before, in Chapter 5, Introducing Files. /etc/programname – where programname is a stand-in for the name of the program you’re interested in configuring – is a common choice of directory for software to keep system-wide configuration. For many programs, that’s enough. For example, the nginx web server is a system-level program: different users aren’t commonly running their own instances of web servers on a single machine, so a system-wide configuration is all that’s needed.

That said, configuration for large or complex programs can still be broken up inside of the /etc/programname directory. Nginx is a good example of this; its main configuration file is at /etc/nginx.conf, with additional config files being sourced from additional files in the /etc/nginx/conf.d/ directory.

For programs that have significant per-user configuration – think text editors, development tooling, games, and more – the ~/.config directory inside a user’s home directory is used. Recall from Chapter 1, How the Command Line Works that ~ is a shorthand for “the current user’s home directory,” and that directories whose names start with a period character (“.”) are omitted from ls output unless you pass the -a flag. The ~/.config directory is part of the XDG base directory standard, which you can get an overview of here: https://wiki.archlinux.org/title/XDG_Base_Directory.

As an example, my neovim configuration is meaningfully different from other developers’ configuration, yet a single neovim binary on a system can support hundreds of developers working on the same machine simultaneously because each developer’s invocation of neovim uses their user-specific configuration files kept in ~/.config/nvim/. And that’s good!

You can imagine the pandemonium that would ensue if there was only a single system-wide place to configure this program in /etc/ – either each developer would have to set countless environment variables before running the neovim editor or invoke the editor command with countless command-line flags.

Now that you’ve taken a walk through the classical configuration sources for Unix programs, let’s look at one Linux-specific complication that you should know about: how configuration via environment files and CLI arguments is managed for programs controlled through systemd.

In most Linux distributions – aside from Docker containers – systemd runs the show. We’ve already covered the basics of systemd in this book (see Chapter 3, Service Management with systemd), and in this section, we’ll take a quick look at how systemd manages configuration for programs.

First, a quick review, in case Chapter 3 seems awfully distant: in a systemd-managed Linux environment, services are packaged into systemd unit files, which wrap and control the actual executable binary, its arguments, the commands used to launch, restart, and stop the unit, and much more.

There are many systemd unit types, as we’ve already covered, but we’re interested in the service unit type here.

We’ve already covered the fact that unit files can exist in several different directories, depending on their purpose, but your own custom systemd units will usually live in /etc/systemd/system.

To understand how a systemd unit lets you affect the layers of the configuration hierarchy that we’ve covered in this chapter, let’s create a systemd-managed service by writing our own systemd unit for an imaginary program called yourprogram.

As a developer, you may need to wrap a program you’re writing into a service, which can be more easily managed than a manually (interactively) invoked program. That’s perfectly useful on its own, but in this chapter, we’re digging into the extra control that systemd units give you over how and where your program is configured. Let’s walk through the process of creating a service by wrapping a binary with a systemd unit file.

First, ensure that you have an executable file copied to a place that is in the default $PATH: /usr/local/bin/yourprogram. If you want to get the most out of this, use a manually compiled program like the htop binary you created in the previous Chapter 9, Managing Installed Software, and replace the imaginary yourprogram with htop.

Now, create the following systemd unit file at /etc/systemd/system/yourprogram.service:

[Unit]
Description=Your program description.
After=network-online.target
[Service]
Type=exec
ExecStart=/usr/local/bin/yourprogram -clioption=1 –clioption2
EnvironmentFile=-/etc/yourprogram/prod_defaults
Restart=on-failure
[Install]
WantedBy=multi-user.target

Can you find the two configuration-related lines in this unit file?

You can see that the ExecStart line specifies how the program is invoked when someone starts this systemd service. We’re using the systemd unit file to pass command-line arguments to the program to make sure that anytime someone starts the service, the program is run with exactly the options we want. Anytime someone runs systemctl start yourprogram, we have ensured that yourprogram will be called with -clioption=1 and -clioption2.

Second, the EnvironmentFile line specifies a file path for systemd to check, where it can expect environment variables relevant to this program to be set. This file will be parsed by the shell that systemd uses to run the binary; it should contain shell variable assignments like:

# yourprogram environment variables
ENV=production
DB_HOST=localhost
DB_PORT=5432

Have systemd re-read its config files to make sure it sees the new service Unit you’ve defined:

$ sudo systemd daemon-reload

Now you can manage this like any other systemd service:

systemctl start yourprogram

systemctl status yourprogram

systemctl stop yourprogram

systemctl enable yourprogram

systemctl disable yourprogram

You know that every time you start this service, your environment file at /etc/yourprogram/prod_defaults will be used to source environment variables, and the ExecStart line will pass the CLI options you’ve specified.

We’ve shown you an extremely simple service here, just so you can get your head around how systemd is used to control program configuration, but there are many other configuration directives you can pass here. Spend some time reading the systemd unit documentation (https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html#%5BUnit%5D%20Section%20Options) if you have a more complex service on your hands.

Earlier in this chapter, we mentioned that Docker is often the exception when it comes to configuration. Because Docker containers are a much more minimal environment, they don’t have a lot of the extra binaries, services, and configuration files that you’ll find in a traditional Unix system. But because much of the software that software developers create now runs in containers, as opposed to traditional, full operating system environments, we want to cover some basics here to make sure you’ve got an intuition for how configuration is different in Docker containers. We’ll dig much deeper into Docker containers in general in Chapter 15, Containerizing Applications with Docker.

In a container environment – whether it’s Docker or another container runtime – you’re dealing with a dramatically smaller environment. There are very few installed programs and utilities, a dramatically stripped-down init in place of systemd, and a much smaller filesystem that doesn’t have many of the directories we’ve mentioned here.

The principle of the configuration hierarchy still holds, though. Most containerized applications expect to get their configuration either from:

  • A config file somewhere on the container filesystem, often dynamically created by a container scheduler just before the container is started
  • Environment variables, passed in by the container scheduler or the operator launching it
  • Command-line arguments

Even though this is a simplified version of the configuration hierarchy, you’ll notice that it’s basically identical to the one we explored in full, non-container Linux systems.

We’ll dive a bit deeper into containers in Chapter 15, Containerizing Applications with Docker.

This chapter gave you an overview of the Linux configuration hierarchy and how it applies to the programs you’ll use (and write) every day. You learned about command-line arguments, environment variables, and all the other things that fit into the larger hierarchy that programs pull configuration from.

If you followed along, you even created a systemd service that wraps a program and allows you to manage its configuration in a more uniform way.