How To Create a Swap Space on Ubuntu
Tags: ubuntu
Published: 2022-12-18 22:11:21

## Introduction

In this guide, you will learn how to create a swap space for your operating system (Ubuntu), which your OS can use as temporary RAM to store data.

The original source of this article can be found [here](https://axxellanceblog.com/posts/how-to-create-a-swap-space-on-ubuntu).

### What is Swap?

Well, you might be wondering what exactly is swap space, though the word might not be new to you but have you ever consider to know what it is exactly, well let me explain it in the way I can. Swap is a portion of an operating system's hard drive storage that has been set aside for the operating system to temporarily store data that it can no longer hold in RAM. This thereby lets you increase the amount of information that your server can keep in its working memory. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data.

SWAP is not RAM, so the information written to it will be significantly slower than that of an actual RAM, but the operating system will prefer to keep running application data in memory and use a swap for the older data. Overall, having swap space as a fallback for when your system’s RAM is depleted can be a good safety net against out-of-memory exceptions on systems with non-SSD storage available.

### Step 1: Checking for Swap Information

before you begin creating a swap space it is best you check if your operating system has a swap space already installed, It is possible to have multiple swap files or swap partitions, but generally one should be enough.

Type this command into your terminal to see if your system already has a swap space configured:

```
sudo swapon --show
```

If you do not get back any output, that means your Ubuntu does not have any swap space currently.

You can verify that there is no active swap space using the **free** utility:

```
free -h
```

You will get an output similar to this

```
Output
              total        used        free      shared  buff/cache   available
Mem:          981Mi       122Mi       647Mi       0.0Ki       211Mi       714Mi
Swap:            0B          0B          0B
```

As you can see in the swap row of the output, no swap is active on the system.

### Step 2: Checking Available Space on the Hard Drive

Before we create our swap file, we will have to check our disk usage to know what amount of available storage we have left, type this command to check your available storage:

```
df -h
```

You should get similar output to the one below

```
Output
Filesystem      Size  Used Avail Use% Mounted on
udev            474M     0  474M   0% /dev
tmpfs            99M  932K   98M   1% /run
/dev/vda1        25G  1.4G   23G   7% /
tmpfs           491M     0  491M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           491M     0  491M   0% /sys/fs/cgroup
/dev/vda15      105M  3.9M  101M   4% /boot/efi
/dev/loop0       55M   55M     0 100% /snap/core18/1705
/dev/loop1       69M   69M     0 100% /snap/lxd/14804
/dev/loop2       28M   28M     0 100% /snap/snapd/7264
tmpfs            99M     0   99M   0% /run/user/1000
```

The device with "/" in the "Mounted on" column is our disk in this case. We have plenty of space available in this example (only 1.4G is used). Your usage will probably be different.

Although there are many differing viewpoints regarding the ideal swap space size, it ultimately comes down to your preferences and the needs of your particular application. In general, a quantity that is equal to or twice as much as the RAM on your machine is a decent place to start. Any swap memory greater than 4G is probably not necessary if it is only being used as a backup for RAM, according to another sound rule of thumb.

### Step 3: Creating a Swap File

We can make a swap file on our filesystem now that we are aware of the amount of hard drive space that is available. In our root (/) directory, we will allocate a file called swapfile with the desired size.

The fallocate application is the finest tool to use while making a swap file. With this command, a file of the requested size is immediately created.

In this guide, we will create a 1G file because the server in our example has 1G of RAM. Change this to suit your own server's requirements:

```
sudo fallocate -l 1G /swapfile
```

By typing the below command, we can confirm that the appropriate quantity of space was set aside.

```
ls -lh /swapfile
```

You will see an output similar to this

```
-rw-r--r-- 1 root root 1.0G Apr 25 11:14 /swapfile
```

If you see an output like the one above that means the appropriate quantity of space has been allocated while creating our file.

### Step 4: Activating The Swap File 

We need to actually convert this file into swap space now that we have a file of the right size available.

The file's permissions must first be restricted so that only users with root privileges can see its contents. This limits access to the file for common users, which has important security ramifications.

You can do so by typing this command below

```
sudo chmod 600 /swapfile
```

you should see an output similar to this

```
Output
-rw------- 1 root root 1.0G Apr 25 11:14 /swapfile
```

As you can see, the read and write flags are only enabled for the root user.

We can now mark the file as swap space by typing:

```
sudo mkswap /swapfile
```

The below output should be the expected output

```
Output
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=6e965805-2ab9-450f-aed6-577e74089dbf
```

Once the file has been marked, we can enable the swap file so that our system may start using it:

```
sudo swapon /swapfile
```

Type the following command below to verify if the swap is available:

```
sudo swapon --show
```

You should see an output similar to this:

```
Output
NAME      TYPE  SIZE USED PRIO
/swapfile file 1024M   0B   -2
```

To confirm our conclusions, we can review the output of the `free` utility once more:

```
free -h
```

Your output show be similar to mine below if you have done everything correctly

```
Output
              total        used        free      shared  buff/cache   available
Mem:          981Mi       123Mi       644Mi       0.0Ki       213Mi       714Mi
Swap:         1.0Gi          0B       1.0Gi
```

Now our swap has been successfully configured, and our operating system will start using it as needed.

### Step 5: Making the Swap File Permanent

The swap file is now functional for the current session thanks to our recent adjustments. The server won't automatically keep the swap settings after a reboot though. By including the swap file in our /etc/fstab file, we can change this.

Use the command below to back up the /etc/fstab file in case something goes wrong:

```
sudo cp /etc/fstab /etc/fstab.bak
```

Type the below command to add the information about the swap file to the end of your /etc/fstab file.

```
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
```

After that, we'll explore several settings that can be modified to optimize our swap space.

### Step 6: Adjusting your swap settings

When dealing with swap, there are a few configuration settings that you can make that can affect how quickly your system performs. I will 2 more complete steps you will need to perform before you are good to go

1: **Making changes to the Swappiness Property**

The swappiness option controls how frequently data is moved from RAM to the swap area by your system. This is a percentage represented by a number between 0 and 100.

Values near zero prevent the kernel from swapping data to the disk unless it is absolutely necessary. Remember that interactions with the swap file can significantly lower performance and are "expensive" in the sense that they take much longer than interactions with RAM. Generally speaking, your system will run quicker if you tell it not to rely much on the swap.

In an effort to maintain more free RAM space, values closer to 100 will try to put more data into the swap space. This might be preferable in some circumstances, depending on the memory profile of your apps or the purposes for which you use your server.

Entering the following command below will display the current swappiness value:

```
cat /proc/sys/vm/swappiness
```

The following output should be similar to mine below:

```
Output
60
```

A swappiness level of 60 is not a bad number for a desktop but you might want to move it nearer to 0 for a server. Using the sysctl command, we may change the swappiness's value. For instance, to set the swappiness to 10, we could type:

```
sudo sysctl vm.swappiness=10
```

The output be:

```
Output
vm.swappiness = 10
```

This configuration will stay in place until the next reboot. By including the following line in our /etc/sysctl.conf file, we can set this value automatically upon restart:

```
sudo nano /etc/sysctl.conf
```

At the bottom, you can add:

```
vm.swappiness=10
```

Save and close the file when you are finished.

**2\. Adjusting the Cache Pressure Setting**

The vfs\_cache\_pressure is another relevant setting that you might want to change. The system's preference for caching inode and dentry information over other data is configured by this parameter.

Essentially, this is information regarding filesystem access. This is a great thing for your system to cache because it's typically quite expensive to search up and very frequently requested. By querying the proc filesystem, you may view the current value:

```
cat /proc/sys/vm/vfs_cache_pressure
```

The output should be similar to the one below:

```
Output
100
```

Our system deletes inode data from the cache far too quickly as it stands right now. We can change this to a more conservative value, such as 50, by typing the below command:

```
sudo sysctl vm.vfs_cache_pressure=50
```

Your output should be similar to mine:

```
Output
vm.vfs_cache_pressure = 50
```

Once more, this is only applicable to the current session. In the same way that we did with our swappiness setting, we can modify that by adding it to our configuration file by typing:

```
sudo nano /etc/sysctl.conf
```

At the bottom, add the line that specifies your new value:

```
vm.vfs_cache_pressure=50
```

Save and close the file when you are finished.

### Conclusion

When situations arise that might otherwise result in out-of-memory exceptions, using the procedures in this article will offer you some breathing room. Swap space can be a huge help in avoiding some of these typical issues.

The best option is to optimize your application setups or upgrade your server if you are experiencing OOM (out of memory) errors or find that your system cannot run the applications you require.

If you find this article worth sharing please do comment and share this article, and we will also like to give our thanks to [digitalocean](https://www.digitalocean.com/) for some insight into making this article possible today (please know that we and digital ocean have nothing to do with each other, if you want to find more details or a different view of this, you can gladly check out the article on this topic on digital ocean blog page using this [link](https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-20-04))