# Swap Allocation

Creating swap memory for your host could prevent system or services from crashing when under heavy loads. To do this, run the following commands.

### Creating Swap Files

```bash
# To createa 512MiB swap file - 
sudo dd if=/dev/zero of=/swapfile bs=1M count=512 status=progress

# To create a 1GiB swap file - 
sudo dd if=/dev/zero of=/swapfile bs=1GB count=1

# To create a 10GiB swap file - 
sudo dd if=/dev/zero of=/swapfile bs=1GB count=10
```

### Enabling Swap

After creating the swap file of the desired size, in the desired directory, we'll need to set some permissions and prepare our file to be used for swap  space - 

```bash
# Set permissions
sudo chmod 600 /swapfile

# Format file to be used for swap allocation
sudo mkswap /swapfile

# Tell our system to mount this file for swap usage
sudo swapon /swapfile
```


#### Adding Default Swap Entry - fstab

In short, an [fstab](https://linux.die.net/man/5/fstab) entry for mounting the swap partition we created above -

```bash
# <device> <dir> <type> <options> <dump> <fsck>
/swapfile none swap defaults 0 0
```

Add this line to your `/etc/fstab` to mount and use this partition for swap automatically on system reboots.

For more information, see [Mounting Default Filesystems](https://www.knoats.com/books/linux-admin/page/mounting-default-filesystems) or [ArchWiki - Fstab](https://wiki.archlinux.org/index.php/Fstab)

### Verifying Swap Configuration

To check available system swap space, run `free -h` to see output similar to the below - 

```bash
root@host:~# free -h
              total        used        free      shared  buff/cache   available
Mem:          983Mi       260Mi        62Mi       0.0Ki       660Mi       560Mi
Swap:         1.0Gi        15Mi       1.0Gi
```

Alternatively, we could run 'sudo swapon --show' to see the below output
```bash
sudo swapon --show
NAME      TYPE  SIZE  USED PRIO
/swapfile file 1024M 15.8M   -2
```
### Swappiness Values

The default swappiness value is set to 60, but to check, change, or verify your system swappiness, see the commands below

```bash
# Check system swappiness setting
cat /proc/sys/vm/swappiness 
60

# Set a new swappiness value
sudo sysctl vm.swappiness=10
# Check the setting was applied
cat /proc/sys/vm/swappiness 
10
```

#### Swappiness Persistance

Upon setting a custom swappiness value and rebooting, your custom configuration will be lost. Edit `/etc/sysctl.conf` to contain the line below to ensure this value is kept between system reboots

```bash
vm.swappiness=10
```

### Removing Swap Files

First, turn off the swap file - 
```bash
sudo swapoff -v /swapfile
```

Remove the swap file entry from your `/etc/fstab` if you previously created one. If present, remove the line similar to the below

```bash
/swapfile swap swap defaults 0 0
```

Last, delete the swap file using `rm` - 
```bash
sudo rm /swapfile
```