Skip to main content

index

Overview​

Adding swap space on instances that have limited RAM. Helpful when you build react application on the same host that serves your compiled react files.

https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-22-04

Steps​

Check if there is swap. No output means no swap space available.

sudo swapon --show

Verify no swap space

free -h

Output

               total        used        free      shared  buff/cache   available
Mem: 3.7Gi 362Mi 2.4Gi 1.0Mi 1.1Gi 3.4Gi
Swap: 0B 0B 0B

Check available space on harddrive

df -h

Assign same amount of swap space as ram.

sudo fallocate -l 4G /swapfile

Verify that swap space is assigned

ls -lh /swapfile

Output:

-rw-r--r-- 1 root root 4.0G Oct 10 09:53 /swapfile

Enable the swap file​

Lockdown permissions to only users with root can read contents.

sudo chmod 600 /swapfile

Verify permissions

ls -lh /swapfile

Output:

-rw------- 1 root root 4.0G Oct 10 09:53 /swapfile
  • Only root can read and write

Mark the file as swapsapce

sudo mkswap /swapfile

Enable the swap space

sudo swapon /swapfile

Verify swap is available:

sudo swapon --show

Output:

NAME      TYPE SIZE USED PRIO
/swapfile file 4G 0B -2

Check out of free for final verification

free -h

Output:

               total        used        free      shared  buff/cache   available
Mem: 3.7Gi 368Mi 2.4Gi 1.0Mi 1.1Gi 3.4Gi
Swap: 4.0Gi 0B 4.0Gi

Make swap file permenant​

Recent changes only apply to current session.

  • Rebooting the server will not retain swap settings
  • Add swap file to /etc/fstab

Backup the /etc/fstab file in case anything goes wrong

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

Add swap file info to the end of the /etc/fstab

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

Tune Swap Settings​

swappiness configures how often system swaps data out of RAM to the swap space.

  • value between 0 - 100 representing a percentage.
  • Close to 0
    • kernel will not swap data to disk unless absolutely necessary
    • interactions with swap file are "expensive" (writing to disk slower than writing to RAM)
cat /proc/sys/vm/swappiness

Output:

60

Set swappiness value for current session by using sysctlcommand

sudo sysctl vm.swappiness=20
  • Fronend instance: 20
  • Backend instance: 20

Set the cache pressure for current session

sudo sysctl vm.vfs_cache_pressure=50

Set the above two values to load automatically at restart by adding to /etc/sysctl.conf

sudo nano /etc/sysctl.conf

Add the following to /etc/sysctl.conf:

vm.swappiness=10
vm.vfs_cache_pressure=50