> For the complete documentation index, see [llms.txt](https://tech.keeganturner.co.za/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tech.keeganturner.co.za/how-to-guides/linux-basics-swap-file.md).

# Linux basics: SWAP file

19-05-2024

Swap  is a portion of the servers hard drive which is allocated to temporarily hold data that is not currently used by the server RAM. It acts as additional virtual memory for when the physical RAM is full.

I will be adding 4GB swap to my Ubuntu instance with 8GB RAM.

1. Check if any swap space is currently enabled on the server&#x20;

```
sudo swapon --show
```

If there's no output on your terminal, it means no swap space is active on the server.

2. Decide on the size of the swap file you want to create

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

3. Secure the swap file

```
sudo chmod 600 /swapfile
```

4. **Set the swap area**

```
sudo mkswap /swapfile
```

5. **Enable the swap file**

```
sudo swapon /swapfile
```

6. **Verify that the swap is active**

```
sudo swapon --show
```

<figure><img src="https://2936064210-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fzc9EJH2DN7SST3iCGmM2%2Fuploads%2FOkucfCRHjAIou860MwWP%2Fimage.png?alt=media&amp;token=8a111232-248a-40f6-9bed-1c563dcd1f28" alt=""><figcaption></figcaption></figure>

To ensure the swap file is used on boot, you need to add it to `/etc/fstab`.

1. Backup the current file

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

2. **Add the swap file to the `/etc/fstab` file:**

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

3. Set the swappiness value (Optional)

*Swappiness controls how much your server makes use of the allocated swap space. Lower values results in the server using swap less often, which can make it faster. Higher values make the system use swap more often, which can keep more RAM free.*&#x20;

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

```
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
```

Check the server RAM and SWAP

```
free -h
```

<figure><img src="https://2936064210-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fzc9EJH2DN7SST3iCGmM2%2Fuploads%2FDFo3XU6VhxNpJ3vC3aJI%2Fimage.png?alt=media&amp;token=0d212487-5599-4312-8673-a3f3521cdfff" alt=""><figcaption></figcaption></figure>

Enabling swap allows you to fine-tune how your system balances performance and processes that require memory in either form of RAM or Swap. Having swap space is a practical strategy for maintaining smooth and efficient operations on your Linux server.
