Skip to content

Instantly share code, notes, and snippets.

@Chubby-Chocobo
Last active August 17, 2019 02:33
Show Gist options
  • Save Chubby-Chocobo/7995e8e37adb58196431361fd1fe0966 to your computer and use it in GitHub Desktop.
Save Chubby-Chocobo/7995e8e37adb58196431361fd1fe0966 to your computer and use it in GitHub Desktop.
Adjust swapfile

Change swap size in Ubuntu 18.04

Reference: https://askubuntu.com/questions/1075505/how-do-i-increase-swapfile-in-ubuntu-18-04

Check whether the system has any configured swap:

sudo swapon --show

Disable the swap file and delete it (not really needed as you will overwrite it)

sudo swapoff -a
sudo rm  /swapfile

Create a new swapfile with desired size.

# There're a lot of guides use `sudo fallocate -l 1G /swapfile` command, but there's an issue with it: 
# The problem with fallocate(1) is that it uses filesystem ioctls to make the allocation fast and effective, 
# the disadvantage is that it does not physically allocate the space but swapon(2) syscall requires a real space. 
# Reference : https://bugzilla.redhat.com/show_bug.cgi?id=1129205

# We'll use dd command instead
# if = input file
# of = output file
# bs = block size
# count = multiplier of blocks
sudo dd if=/dev/zero of=/swapfile bs=4M count=4096

Assign it read/write permissions for root only (not strictly needed, but it tightens security)

sudo chmod 600 /swapfile

Format the file as swap:

sudo mkswap /swapfile

The file will be activated on the next reboot. If you want to activate it for the current session:

sudo swapon /swapfile

Verify that the swap is available:

sudo swapon --show

Making the swapfile permanent:

# Backup the /etc/fstab file first
sudo cp /etc/fstab /etc/fstab.bak
# Add new swap information to /etc/fstab
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment