I know how to create and use a swap partition but can I also use a file instead?
How can I create a swap file on a Linux system?
Let's start with the basic information, you should inspect what vm.swappiness is set, and if set wisely to a more acceptable value than 60, which is the default, you should have no problem. This command can be run as normal user:
sysctl vm.swappiness For instance, I have 32 GB RAM server with 32 GB swap file with vm.swappiness = 1. Quoting the Wikipedia:
vm.swappiness= 1: Kernel version 3.5 and over, as well as Red Hat kernel version 2.6.32-303 and over: Minimum amount of swapping without disabling it entirely.
In this example, we create a swap file:
32 GiB in size;
Located in / (the root directory).
Change these two things accordingly to your needs.
Open terminal and become root (su); if you have sudo enabled, you may also do for example sudo -i; see man sudo for all options):
sudo -i Allocate space for the swap file, -l is the same as --length on most systems, and -v is --verbose, more importantly the G means GiB, do not write GB, as it would mean 1000*1000 multiples:
fallocate -v -l 32G /swapfile Note: DON'T use dd as I found out for Hibernation a contiguous file is needed. (Unclear if also needed for swapping. May need adding some link to docs.)
dd if=/dev/zero of=/swapfile bs=1G count=8 status=progress
If your dd does not support status=progress, just leave it out.
Note, that the size specified here in G is in GiB (multiples of 1024).
!!! This answer could change my point of view, I'll read it later: https://askubuntu.com/a/1017312/436624
Change permissions of the swap file, so that only root can access it:
chmod 600 /swapfile Make this file a swap file:
mkswap /swapfile Enable the swap file:
swapon /swapfile Verify, whether the swap file is in use:
cat /proc/swaps Open a text editor you are skilled in with this file, e.g. nano if unsure:
nano /etc/fstab To make this swap file available after reboot, add the following line:
/swapfile none swap sw 0 0 $ sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576 $ sudo chmod 600 /swapfile $ sudo mkswap /swapfile $ sudo swapon /swapfile Note: you may sometimes use fallocate instead of dd:
$ sudo fallocate -l 1G /swapfile — but with certain filesystems it may result in a file with holes which is unsuitable to act as a swap file.
Please check the script for creating a SWAP Memory of 16GB:
#!/bin/bash #find Free free -h #Checking availability space df -h #swap Off sudo swapoff /swapfile #Allocate swap sudo fallocate -l 16G /swapfile #correct amount of space was reserved ls -lh /swapfile #file only accessible to root sudo chmod 600 /swapfile #amount of space was reserved for the root ls -lh /swapfile #now mark the file as swap space sudo mkswap /swapfile #Swap On sudo swapon /swapfile #swap Show sudo swapon --show #statment echo -e "\n\n Swap 16Gb done"