Skip to content
ImagineWorld

Monitoring System Resources

node_idnode-book_mastering-ubuntu-server_chapter-08-monitoring-system-resources
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleMonitoring System Resources
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In the last chapter, we learned how we can manage tasks that are running on our server. We now know how to see what’s running in the background, how to enable or disable a unit from starting at boot time, and also how to schedule tasks to run in the future. But in order for us to be able to effectively manage the tasks that our servers carry out, we also need to keep an eye on system resources. If we run out of RAM, fill up our disk, or overload our CPU, then a server that normally processes tasks very efficiently might come to a screeching halt. In this chapter, we’ll take a look at these resources and how to monitor them.

Our discussion on resource management will include:

  • Viewing disk usage
  • Monitoring memory usage
  • Understanding load average
  • Viewing resource usage with htop

One resource that is extremely important on our servers is storage, and keeping track of such things as available disk space is critical – even the most powerful server you can purchase would be unable to function without free disk space. We’ll take a look at some ways to monitor disk usage in the next section.

Keeping an eye on your storage is always important, as no one enjoys getting a call in the middle of the night saying that a server encountered an issue, especially not something that could’ve been easily avoided, such as a filesystem growing too close to being full. Managing storage on Linux systems is simple once you master the related tools, the most useful of which I’ll go over in this section. In particular, we’ll look at tools we can use to answer the question “what’s using up all the disk space?”, which is the most common question that comes up when dealing with disk usage.

First, let’s look at the df command.

The df command is likely always going to be your starting point in situations where you don’t already know which volume or mount point is becoming full. When executed, it gives you a high-level overview, so it’s not necessarily useful when you want to figure out who or what in particular is hogging all your space. However, when you just want to list all your mounted volumes and see how much space is left on each, df fits the bill. By default, it shows you the information in bytes. However, I find it easier to use the -h option with df, which will show output that’s more human-readable, and by doing so you’ll see information that’s a bit easier to read. Go ahead and give it a try:

df -h

This should produce an output that looks something like the following:

Figure 8.1: Output from the df -h command

The output will look different depending on the types of disks and mount points associated with your system. In the screenshot, you’ll see that the root filesystem is located on /dev/mapper/ubuntu--vg-ubuntu--lv. We know this because under the column Mounted on we see that the mount point is set to a single forward slash (/). As we discussed in Chapter 4, Navigating and Essential Commands, this single forward slash refers to the beginning of the filesystem (also referred to as the root filesystem). In my case, this is an LVM volume, which is why we have a device with such a long name, beginning with /dev/mapper. Let’s not worry about LVM at this point – we’ll discuss that later. But for now, just keep in mind that the single forward slash refers to the beginning of the filesystem, and the device name on the left refers to the actual device that’s mounted there.

The actual device name varies from one server to another and also varies depending on whether you chose to utilize LVM during installation. Instead of a long path beginning with /dev/mapper, you may instead see the device name as /dev/sda1, /dev/xvda1, /dev/nvme0n1p1, or other variations. The name of the device is generated by the type of hardware the underlying storage device is, such as the /dev/nvme... naming convention used for NVME hard drives, /dev/sdaN for standard SATA hard drives, and so on.

The actual type of device the underlying storage hardware is doesn’t matter so much; it only really matters that you can identify which device is in the most danger of becoming full. In the example screenshot, the root filesystem is using 35% of its available space. In this case, we aren’t in danger of running out of space when it comes to that.

If you do see that an important storage volume is either full or trending toward becoming full, then you’ll know which one in particular you should focus on, and we’ll explore additional ways that you can obtain more information about what’s using up space very shortly.

However, sometimes a storage volume can be considered full, even when it appears that the volume has plenty of space free. This is due to the fact that on a Linux system, the actual data you’re storing and the size of that data isn’t the only consideration. We also have to take inodes into account as well.

But, what exactly is an inode, and why would such a thing cause a disk to be reported as full when it’s actually not? Think of the concept of an inode as a type of database object, containing metadata for the actual items you’re storing. Information stored in inodes are details such as the owner of the file, permissions, last modified date, and type (whether it is a directory or a file). While metadata is certainly a good thing to have, the problem with inodes is that you can only have a limited number of them on any storage device. If a storage device reaches its inode limit, then the volume is still considered full, and will not be able to accept additional data.

In practice, the symptom of this scenario is that commands such as df will show the volume as having free space, yet when you try to save a new file onto the device, you will see an error that you’re unable to do so because the volume is full. If you weren’t aware of the existence of inodes, then this situation might be a bit confusing.

While it may seem as though having another limit on storage in the form of inodes is a downside, in reality, the inode limit on storage volumes is usually extremely high and very hard to reach. Often, if an inode limit is reached, that usually means that there’s a bigger issue with the server that’s causing it to hit this limit. For example, perhaps there’s an issue on the server where it’s saving a much higher number of files than it should, such as an usual number of log files or queued e-mail message files.

Thankfully, determining whether or not you’re running out of inodes on a particular storage volume is very simple – rather than using the -h option with the df command, use the -i option instead. The -i option will display inode counts instead of standard size-based storage metrics. To help illustrate the difference, I’ll show you some output from one of my servers to give you an idea of what this looks like:

df -i

The output of that command on my system is as follows:

Figure 8.2: Output from the df -i command

In this example, the root filesystem on the example server has a total of 999424 inodes available, of which 84223 are used and 915201 are free. In my case, I have plenty of inodes available. However, I recommend committing the df -h and df -i commands to memory. Whether any space issues with storage you may experience pertain to actual space or inode utilization, you’ll be able to know which is the case between those two commands.

Assuming you have storage that’s on the verge of becoming full (or it already is), how do you pinpoint exactly what in particular is using up all that space? There are additional tools you can use that will help you narrow this down. And that’s exactly what we’ll explore next.

The next step in investigating what’s gobbling up your disk space is finding out which files in particular are using it all up. At this stage, there is a multitude of tools you can use to investigate. The first I’ll mention is the du command, which is able to show you how much space a directory is using. Using du against directories and sub-directories will help you narrow down the problem. Like df, we can also use the -h option with du to make our output easier to read. By default, du will scan the current working directory your shell is attached to and give you a list of each item within the directory, the total space each item consists of, as well as a summary at the end.

The du command is only able to scan directories that its calling user has permission to scan. If you run this as a non-root user, then you may not be getting the full picture. Also, the more files and sub-directories that are within your current working directory, the longer this command will take to execute. If you have an idea where the resource hog might be, try to cd into a directory further in the filesystem tree to narrow your search down and reduce the amount of time the command will take. The output of du -h can often be more verbose than you actually need in order to pinpoint your culprit and can fill several screens. To simplify it, my favorite variation of this command is the following:

du -hsc *

Basically, you would run du -hsc * within a directory that’s as close as possible to where you think the problem is. The -h option, as we know, gives us human-readable output (essentially, giving us output in the form of megabytes, gigabytes, and so on). The -s option gives us a summary and -c provides us with the total amount of space used within our current working directory. The following screenshot shows this output from one of my computers:

Figure 8.3: Example output from du -hsc *

To make that example more interesting, I took the screenshot from my personal desktop, but the resulting command and its syntax won’t differ from one device to the next. As you can see, the information provided by du -hsc * is a nice, concise summary. From the output, we can clearly see how much space each of the directories within our working directory takes currently. For example, I have 2.2 GB used in my projects directory right now, as well as 53 GB worth of ISO images.

At this point, we know which directories at the top level of our current working directories are using the most space. But we still need to narrow this down to what in particular within those directories is responsible for using that space. To dive deeper, we could cd into any of those large directories and run the du command again. After a few runs, we should be able to narrow down the largest files within these directories and make a decision on what we want to do with them. Perhaps we can clean unnecessary files or add another disk. Once we know what is using up our space, we can decide what we’re going to do about it.

At this point in reading this book, you’re probably under the impression that I have some sort of strange fixation on saving the best for last. You’d be right. I’d like to finish off this section by introducing you to one of my favorite applications, the NCurses Disk Usage utility (or more simply, ncdu). The ncdu command is one of those things that administrators who constantly find themselves dealing with disk space issues learn to love and appreciate. In one go, this command gives you not only a summary of what is eating up all your space but also gives you the ability to traverse the results without having to run a command over and over while manually traversing your directory tree. You simply execute it once and then you can navigate the results and drill down as far as you need.

To use ncdu, you will need to install it as it doesn’t come with Ubuntu by default:

sudo apt install ncdu

Once installed, simply execute ncdu in your shell from any starting directory of your choosing. When done, simply press q on your keyboard to quit. Like du, ncdu is only able to scan directories that the calling user has access to. You may need to run it as root to get an accurate portrayal of your disk usage.

You may want to consider using the -x option with ncdu. This option will limit it to the current filesystem, meaning it won’t scan network mounts or additional storage devices; it’ll just focus on the device you started the scan on. This can save you from wasting time scanning areas that aren’t related to your issue.

When executed, ncdu will scan every directory from its starting point onward. When finished, it will give you a menu-driven layout allowing you to browse through your results:

Figure 8.4: ncdu in action

Again, I took this screenshot from my desktop, from within my home directory. What ncdu does is show you your disk usage from your current directory down, and it will order the results by placing the items with the highest usage toward the top. To move around inside of ncdu, you do so by moving your selection (indicated with a long white highlight) with the up and down arrows on your keyboard.

If you press Enter on a directory, ncdu switches to showing you the summary of that directory, and you can continue to drill down as far as you need. In fact, you can actually delete items and entire folders by pressing d. Therefore, ncdu not only allows you to find what is using up your space but allows you to take action as well!

Sometimes, it’s obvious what’s taking up space on a disk, and ncdu may not always be necessary. Generally speaking, you’ll start out your investigation with df -h, to see which storage volume is the one that’s running out of space. Then, you’ll go into that directory and run another command, such as du -hsc *, to see which directory is using up the most space. If you don’t immediately know from the output of du what the underlying issue is, then consider using a tool such as ncdu to dive down even deeper.

Although monitoring storage is critical, we also need to keep an eye on free memory. Next up, we’ll take a look at how to monitor the memory of our server.

I forget things all the time. I regularly forget where my car keys are, even though they’re almost always right there in my pocket the entire time. I even forget to use sudo for commands that normally require it, despite working with Linux for over 20 years. Thankfully, computers have a better memory than I do, but if we don’t manage it effectively, the memory on our servers will be just as useless as I am when I forget to put freshly washed laundry in the dryer.

Understanding how Linux manages memory can actually be a somewhat complex topic, as understanding how much memory is truly free can be a hurdle for newcomers to overcome. You’ll soon see that how Linux manages memory on your server is actually fairly straightforward once explained.

For the purpose of monitoring memory usage on our server, we have the free command at our disposal, which we can use to see how much memory is being consumed at any given time. Giving the free command with no options will result in the output being shown in terms of kilobytes:

Figure 8.5: Output of the free command

My favorite variation of this command is free -m, which shows the amount of memory in use in terms of megabytes. You can also use free g to show the output in terms of gigabytes, but the output won’t be precise enough on most servers. In my opinion, adding the -m option makes the free command much more readable:

Figure 8.6: Output of the free -m command

Since everything is broken down into megabytes, it’s much easier to read, at least for me.

At first glance, it may appear as though this server has only 277 MB free. You’ll see this in the first row and third column under free. In actuality, the number you’ll really want to pay attention to is the number under available, which is 2943 MB in this case. That’s now much memory is actually free. Since this server has 3925 MB of total RAM available (you’ll see this on the first row, under total), this means that most of the RAM is free, and this server is not really working that hard at all.

Some additional explanation is necessary to truly understand these numbers. You could very well stop reading this section right now as long as you take away from it that the available column represents how much memory is free for your applications to use. However, it’s not quite that simple.

Technically, when you look at my output, the server really does have only 277 MB of memory free. The amount of memory listed under available is legitimately being used by the system in the form of a cache but would be freed up in the event that any application needed to use it. If an application starts and needs a decent chunk of memory in order to run, the kernel will provide it with some memory from this cache.

Linux, like most modern systems, subscribes to the belief that “unused RAM is wasted RAM.” RAM that isn’t being used by any process is given to what is known as a filesystem cache, which is utilized to make your server run more efficiently. When data needs to be written to a storage device, it’s not directly written right away. Instead, this data is written to the filesystem cache (a portion of RAM that’s set aside) and then synchronized to the storage device later in the background. The reason this makes your server more efficient is that this data being stored in RAM would be written to and retrieved faster than it would be from disk. Applications and services can synchronize data to the disk in the background without forcing you to wait for it. This cache also works for reading data, as when you first open a file, its contents are cached. The system will then retrieve it from RAM if you read the same file again, which is more efficient than loading it from the storage volume each time. If you just recently saved a new file and retrieve it right away, it’s likely still in the cache and then retrieved from there, rather than from the disk directly.

To understand all of the columns shown in Figure 8.6, I’ll outline the meaning of each in the following table:

ColumnMeaning
totalThe total amount of memory installed on the server.
usedThe memory that is used (from any source). This is calculated as follows: used = total - free - buffers/cache.
freeThe memory not being used by anything, the cache or otherwise.
sharedThe memory used by tmpfs as well as other shared resources.
buff / cacheThe amount of memory being used by the buffers and cache.
availableThe memory that is free for applications to use.

You may have noticed in Figure 8.6 that memory usage is also listed for a resource called swap. Let’s take a look at that as well. We will dedicate the next section entirely to it so that we ensure we understand what it is, and what it does for us.

swap is one of those things we never want to use, but always want to make sure it is available. It’s kind of like car insurance, no one is excited to buy it, but we do want to have it in case something bad happens. There’s even some debate between administrators on whether or not swap is still relevant today. It’s definitely relevant, regardless of what anyone says, as it’s a safety net of sorts. (And disk space is cheaper nowadays, so dedicating some of our storage to this task isn’t really a big deal, so we may as well.)

So what is it? swap is basically a partition or a file that acts as RAM in situations where your server’s memory is saturated. If we manage a server properly, we hope to never need it, as swap is stored on your hard disk, which is orders of magnitude slower than RAM. But if something goes wrong on your server and your memory usage skyrockets, swap may save you from having your server go down. The Out of Memory (OOM) Killer may also activate itself when memory is full, to kill a misbehaving process that’s using the majority of your memory, but as much as possible, we don’t want to rely on that and instead ensure adequate swap in case memory is exhausted.

The way swap is implemented by default in Ubuntu is in the form of a swap file. In previous versions of Ubuntu (specifically, 16.04 and earlier) it was implemented via a swap partition instead. In fact, if you have an existing server that you’ve upgraded to Ubuntu 22.04 and it started on an older Ubuntu version, you may still have a swap partition, even though you’re running the latest release. New installations of Ubuntu performed after 16.04 will have a swap file.

Is having a swap file better than a swap partition? I would say yes, it’s preferred – although you won’t notice any difference when it comes to performance. Whether swap on your server is in the form of a swap file or partition, it doesn’t change the fact that swap uses your disk and is slower than RAM. One benefit of a swap file compared to a swap partition is that it’s easier to grow or shrink a swap file than it is to do the same with a swap partition.

Anyway, considering that swap files are the preferred method (and the new default) going forward, I won’t cover the process of creating swap as a partition, as there’s no reason to do so anymore.

The swap file for your server is declared in the /etc/fstab file (we’ll discuss the /etc/fstab file in more detail in Chapter 9, Managing Storage Volumes). In most cases, you would’ve had a swap file created for you during installation. You could, of course, add a swap file later if for some reason you don’t have one. In the case of some cloud instance providers, you may not get a swap file by default. In that situation, you would create a swap file yourself (we’ll discuss the process later in this section) and then use the swapon command to activate it:

sudo swapon -a

When run, the swapon -a command will find your swap file in /etc/fstab (if one is listed there), mount it, and activate it for use. The inverse of this command is swapoff -a, which deactivates your swap file. It’s rare that you’d need to disable swap, unless, of course, you were planning on deleting your swap file in order to create a larger one. If you find out that your server has inadequate swap, that may be a course of action you would take.

While having swap is generally a good idea, there are actually some applications that prefer that the server doesn’t have it at all. Not having swap isn’t a common requirement, but Kubernetes is a good example of a situation that might lead you to disabling swap altogether. In fact, the installation process for Kubernetes will complain (or possibly fail) if you do have swap enabled. In the case of a Kubernetes cluster, the individual servers within such a cluster would be a special case anyway, each dedicated to the task of running containers (which is what Kubernetes does; more on that in Chapter 18, Container Orchestration).

When you check your free memory (hint: execute free -m), you’ll see swap listed whether you have it or not, but when swap is deactivated, you will see all zeros for the size totals.

So, how do you actually create a swap file if you wish to use it and you don’t already have one? To do so, you’ll first create the actual file to be used as swap. This can be stored anywhere, but /swapfile is typically ideal. You can use the fallocate command to create the actual file. The fallocate command will force a file to be a particular size:

sudo fallocate -l 4G /swapfile

Here, I’m creating a 4 GB swap file, but feel free to make yours whatever size you want in order to fit your needs. Next, we need to prepare this file to be used as swap. First, we’ll need to fix the permissions as we need this file to be a bit more restrictive than most:

sudo chmod 0600 /swapfile

Then, we can use the mkswap command to convert this file into an actual swap file:

sudo mkswap /swapfile

Now, we have a handy-dandy swap file stored on our root filesystem. Next, we’ll need to mount it. As always, it’s recommended that we add this to our /etc/fstab file. What follows is an example entry:

/swapfile none swap sw 0 0

From this point, we can activate our new swap file with the swapon command that I mentioned earlier:

sudo swapon -a

After running that command, the swap file should be active and in use. You can verify this by running free -m and seeing a swap file listed, with a size greater than 0. While I certainly hope you won’t need to resort to using swap, I know from experience that it’s only a matter of time. Knowing how to add and activate swap when you need it is definitely a good practice, but for the most part, you should be fine because, by default on most platforms, you’ll have swap created for you when setting up Ubuntu for the first time during installation. If you do need to create it manually for whatever reason, I always recommend a bare minimum of 2 GB on servers, or higher if that better fits your use-case.

How much swap is being used is something you should definitely keep an eye on. When the memory starts to get full, the server will start to utilize the swap file. It’s normal for a small portion of swap to be utilized even when the majority of the RAM is free. But if a decent chunk of swap is being used, it should be investigated (perhaps a process is using a larger than normal amount of memory).

You can actually control at which point your server will begin to utilize swap. How frequently a Linux server utilizes swap is referred to as its swappiness. By default, the swappiness value on a Linux server is typically set to 60. You can verify this with the following command:

cat /proc/sys/vm/swappiness

The higher the swappiness value, the more likely your server will utilize swap. If the swappiness value is set to 100, your server will use swap more often. If you set it to 0, swap will be used a lot less often. This value correlates roughly to the percentage of RAM being used.

To change this value on the fly, you can execute the following command:

sudo sysctl vm.swappiness=30

Once you execute that command, the change in the swappiness value will take effect immediately. However, once you reboot your server, the value will reset. In order to make the change persist, open the following file with your text editor of choice:

/etc/sysctl.conf

A line in that file corresponding to swappiness will typically not be included by default, but you can add it manually. To do so, add a line such as the following to the end of the file and save it:

vm.swappiness = 30

Changing this value is one of many techniques within the realm of performance tuning. While the default value of 60 is probably fine for most, there may be a situation where you’re running a performance-minded application and can’t afford to have it swap any more than it absolutely has to. In such a situation, you would try different values for swappiness and use whichever one works best during your performance tests.

In the next section, we’ll take a look at another important metric to keep an eye on: load average. The load average gives us an idea of how busy the CPU(s) might be, so we can better understand how to tell when our server is overwhelmed and we may need to take action.

Another very important topic to understand when monitoring performance is load average, which is a series of numbers that represents your server’s trend in CPU utilization over a given time. You’ve probably already seen these series of numbers before, as there are several places in which the load average appears. If you run the htop utility, for example, the load average is shown on the screen. In addition, if you execute the uptime command, you can see the load average in the output of that command as well. You can also view your load average by viewing the text file that stores it in the first place:

cat /proc/loadavg

Personally, I habitually use the uptime command in order to view the load average. The primary purpose of the uptime command is to display the amount of time that the server has been in use, and this time resets anytime you power off or reboot the server. But in addition to how long the server has been powered on, the uptime command displays the current load average of your server as well.

Understanding load average might be a bit confusing at first, but you’ll quickly realize it’s not as complicated as it seems. The load average is a set of three numbers, each corresponding to a portion of time. From left to right, these numbers correspond to 1 minute, 5 minutes, and 15 minutes respectively. A typical load average may look something like the following:

0.36, 0.29, 0.31

In this example, we have a load average of 0.36 in the 1-minute section, 0.29 in the 5-minute section, and 0.31 in the 15-minute section. In particular, each number represents how many tasks were waiting for attention from the CPU for that given time period. Therefore, these numbers are really good. The server isn’t that busy, since virtually no task is waiting for the CPU at any one moment (each number is less than 1). This is contrary to something such as overall CPU percentages, which you may have seen in task managers on other platforms or even within such Linux tools as htop. While viewing your CPU usage percentage can be useful, the problem with this is that your CPUs will constantly go back and forth from a high percentage of usage to a low percentage of usage, which you can see for yourself by just running htop for a while. When a task does some sort of processing, you might see your cores shoot up to 100 percent and then right back down to a lower number. That really doesn’t tell you much, though. With load averages, you’re seeing the trend of usage over three given time frames, which is more accurate in determining whether your server’s CPUs are running efficiently or are choking on a workload it just can’t handle.

The main question, though, is at which point you should start to worry, which really depends on what kind of CPUs are installed on your server. Your server will have one or more CPUs, each with one or more cores. To Linux, each of these cores, whether they are physical or virtual, is the same thing (a CPU). In my case, the machine I took the earlier output from has a CPU with four cores.

The more CPUs your server has, the more tasks it’s able to handle at any given time, which also means it can handle a higher load average.

When a load average for a particular time period is equal to the number of CPUs on the system, that means your server is at 100% capacity. It’s handling a consistent number of tasks that are equal to the number of tasks it can handle. For example, if you have an 8-core CPU and the load average is 8 for a given time frame, then the CPU is 100% at its available capacity for that time frame. If your load average is consistently more than the number of cores you have available, that’s when you’d probably want to look into the situation. It’s fine for your server to be at capacity every now and then, but if it always is, that’s a cause for alarm.

I’d hate to use a cliché example in order to fully illustrate this concept, but I can’t resist, so here goes. A load average on a Linux server is equivalent to the check-out area at a supermarket. A supermarket will have several registers open, where customers can pay to finalize their purchases and move along. In my experience at typical stores in my area, you would have something like 20 check-out registers but only two cashiers working at any one time, but for this example, we’ll assume each register has a cashier operating it.

Each cashier is only able to handle one customer at a time. If there are more customers waiting to check out than there are cashiers, the lines will start to back up and customers will get frustrated. In a situation where there are four cashiers and a total of four customers at a particular time, the cashiers would be at capacity, which is not really a big deal since no one else is waiting. What can add to this problem is a customer that is paying by check and/or using a few dozen coupons, which makes the checkout process much longer (similar to a resource-intensive process). If there were four cashiers and six customers waiting, then there would be two more customers than the store is able to handle at the same time. In that case, the checkout area of the store would be above capacity. This is essentially how load average works. Each cashier is a CPU, and each customer is a process that needs CPU time.

Just like the cashiers, each CPU can only handle one task at a time, with some tasks hogging the CPU longer than others. If there are exactly as many tasks as there are CPUs, there’s no cause for concern. But if the lines start to back up, we may want to investigate what is taking so long. To gain control of the situation, we may hire an additional cashier (add a new CPU) or ask a disgruntled customer to leave (kill a process).

Let’s take a look at another example load average:

1.87, 1.53, 1.22

In this situation, we shouldn’t be concerned, because our hypothetical server has 4 CPUs, and none of them have been at capacity within the 1-, 5-, or 15-minute time periods. Even though the load is consistently higher than 1, we have CPU resources to spare, so it’s no big deal. If we had one of those awesome new Threadripper CPUs from AMD (which can contain an impressive number of cores) then those numbers would represent extremely low load. Going back to our supermarket comparison, the load average in the previous example would be equivalent to having four cashiers with an average of almost two customers being assisted during any 1 minute. If this server only had one CPU, we would probably want to figure out what’s causing the line to begin to back up.

While you might logically assume that having a low load average is a good thing, it can actually represent a really big problem depending on the context. When we deploy servers, we do so to get some sort of work done.

Whether that “work” is to host an application or run jobs to process data, our servers need to be doing some sort of work, otherwise, we’re wasting money by having them. If the load average of your server drops to an abnormally low value, that might mean that a service that would normally be running all the time has failed and exited. For example, if you have a database server that constantly has a load within the 1.x range that suddenly drops to 0.x, that might mean that you either have legitimately less traffic or the database server service is no longer running. This is why it’s always a good idea to develop baselines for your server, in order to gauge what is normal and what isn’t. A baseline refers to resource usage, most of the time. If the resource usage is drastically higher or even lower than the baseline, that’s a potential cause for concern either way.

Overall, load averages are something you’ll become very familiar with as a Linux administrator if you haven’t already. As a snapshot in time of how heavily utilized your server is, it will help you to understand when your server is running efficiently and when it’s having trouble. If a server is having trouble keeping up with the workload you’ve given it, it may be time to consider increasing the number of cores (if you can) or scaling out the workload to additional servers. When troubleshooting utilization, planning for upgrades, or designing a cluster, the process always starts with understanding your server’s load average so you can plan your infrastructure to run efficiently for its designated purpose.

Now that we’ve gone over the important resources that we need to monitor to ensure our server remains healthy, let’s take a look at a useful utility we can utilize that will make resource usage even easier to understand.

When wanting to view the overall performance of your server, nothing beats htop. Although not typically installed by default, htop is one of those utilities that I recommend everyone installs as soon as possible, since it’s indispensable when wanting to check on the resource utilization of your server. It’s so useful in fact that I’ve mentioned it several times earlier in this chapter, even before we started an actual discussion about it in this section. It’s a great utility.

If you don’t already have htop installed, all you need to do is install it with apt:

sudo apt install htop

When you run htop at your shell prompt, you will see the htop application in all its glory. In some cases, it may be beneficial to run htop as root, since doing so does give you additional options such as being able to kill processes, though this is not required:

Figure 8.7: Running htop

At the top of the htop display, you’ll see a progress meter for each of your cores (the server used for my screenshot only has one core), as well as a meter for memory as well as swap. In addition, the upper portion will also show your Uptime, Load average, and the number of Tasks you have running. The lower section of htop ‘s display will show you a list of processes running on your server, with fields showing you useful information such as how much memory or CPU is being consumed by each process, as well as the command being run, the user running it, and its Process ID (PID). We discussed PIDs in Chapter 7, Controlling and Managing Processes. To scroll through the list of processes, you can press Page Up or Page Down or use your arrow keys. In addition, htop features mouse support, so you are also able to click on columns at the top in order to sort the list of processes by that criteria. For example, if you click on MEM% or CPU%, the process list will be sorted by memory or CPU usage respectively. The contents of the display will be updated every 2 seconds.

The htop utility is also customizable. If you prefer a different color scheme, for example, you can press F2 to enter Setup mode, navigate to Colors on the left, and then you can switch your color scheme to one of the six that are provided. Other options include the ability to add additional meters, add or remove columns, and more. One tweak I find especially helpful on multicore servers is the ability to add an average CPU bar. Normally, htop shows you a meter for each core on your server, but if you have more than one, you may be interested in the average as well. To do so, enter Setup mode again (F2), then with Meters highlighted, arrow to the right to highlight CPU average, and then press F5 to add it to the left column. There are other meters you can add as well, such as Load average, Battery, and more.

Depending on your environment, function keys may not work correctly in terminal programs such as htop, because those keys may be mapped to something else. For example, F10 is used to exit htop, but that may not work if F10 is mapped to a function within your terminal emulator, and using a virtual machine solution such as VirtualBox may also prevent some of these keys from working normally. You can also navigate htop with your mouse, even via an SSH connection. This also means that you can click on the word Quit in the lower right-hand corner to exit the application.

Here’s an example of htop configured with a meter for the CPU average:

Figure 8.8: htop with a meter for CPU average added

When you open htop, you will see a list of processes for every user on the system. When you have a situation where you don’t already know which user/process is causing extreme load, this is ideal. However, a very useful trick (if you want to watch a specific user) is to press u on your keyboard, which will open up the Show processes of: menu. In this menu, you can highlight a specific user by highlighting it with the up or down arrow keys and then pressing Enter to only show processes for that user. This will greatly narrow down the list of processes.

Another useful view is the tree view, which allows you to see a list of processes organized by their parent/child relationship, rather than just a flat list. In practice, it’s common for a process to be spawned by another process. In fact, all processes in Linux are spawned from at least one other process, and this view shows that relationship directly. In a situation where you are stopping a process only to have it immediately re-spawn, you would need to know what the parent of that process is in order to stop it from resurrecting itself. Pressing F5 will switch htop to tree view mode, and pressing it again will disable the tree view.

With the tree view activated, htop will appear similar to the following:

Figure 8.9: htop with tree view activated

As I’ve mentioned, htop updates its stats every 2 seconds by default. Personally, I find this to be acceptable, but if you want to change how fast it refreshes, you can call htop with the -d option and then apply a different number of seconds (entered in tenths of seconds) for it to refresh. For example, to run htop but have it update every 7 seconds, start htop with the following command:

htop -d 70

To kill a process with htop, use your up and down arrow keys to highlight the process you wish to kill and press F9. A new menu will appear, giving you a list of signals you are able to send to the process with htop. SIGTERM, as we discussed before, will attempt to gracefully terminate the process. SIGKILL will terminate it uncleanly. Once you highlight the signal you wish to send, you can send it by pressing Enter or cancel the process with Esc.

As you can see, htop can be incredibly useful and has (for the most part) replaced the legacy top command that was popular in the past for most administrators. The top command is available by default in Ubuntu Server and is worth a look, if only as a comparison to htop. Like htop, the top command gives you a list of processes running on your server, as well as their resource usage. There are no pretty meters and there is less customization possible, but the top command serves the same purpose. In most cases, though, htop is probably your best bet going forward.

In this chapter, we learned how to monitor our server’s resource usage. We began with a look at the commands we can use to investigate disk usage, and we learned how to monitor memory usage as well. We also discussed swap, including what it is, why you’d want to have it, as well as how to create a swap file manually should the need to do so come up. We then took a look at load average and closed out the chapter by checking out htop, which is my favorite utility for getting an overall look at resource usage on servers.

In Chapter 9, Managing Storage Volumes, we’ll take a closer look at storage. In this chapter, we learned how to see how much is being used, but in the next, we’ll look at more advanced concepts surrounding storage, such as formatting volumes, adding additional volumes, and even LVM. See you there!