I usually go with a swapfile instead of a swap partition. So, during installation I don't create that partition, and instead I add the swapfile later.
So, here's how I do it.
First, I do everything as su
:
~$ su - Password: ~#
Create the directory and the swapfile. I prefer the path /var/vm/
. Others may prefer /var/swap/
. To create the swapfile - you can use dd
, or fallocate
if you prefer that one. I use dd
.
The size of the swapfile may vary on your needs. I usually go with quite a big one, so in case I want to hibernate - there will be enough room. So, on an old laptop with 3G of RAM - I'll go with 4G.
~# mkdir /var/vm && cd /var/vm vm# dd if=/dev/zero of=./swapfile0 bs=1M count=4096 status=progress 4237295616 bytes (4,2 GB, 3,9 GiB) copied, 45 s, 94,2 MB/s 4096+0 records in 4096+0 records out 4294967296 bytes (4,3 GB, 4,0 GiB) copied, 45,6187 s, 94,1 MB/s
And set the permissions to 600:
vm# chmod 600 swapfile0 vm# ls -l swapfile0 total 4194304 -rw-------. 1 root root 4294967296 5 jan 03.14 swapfile0
Then make it an actual swapfile, turn the swap on, and check the status.
vm# mkswap swapfile0 Setting up swapspace version 1, size = 4 GiB (4294963200 bytes) no label, UUID=<unique hash string> vm# swapon swapfile0 vm# swapon -s Filename Type Size Used Priority /var/vm/swapfile0 file 4194300 0 -2
To make it mount on boot, we need to add it to /etc/fstab
. So, with your favorite editor (eg. vim, vi, nano, etc)…
vm# vim /etc/fstab
And add these lines to the end of the file:
# Swapfile0 /var/vm/swapfile0 none swap defaults 0 0
Using the free
command will get you information on how much swap you have and are using.
$ free -h total used free shared buff/cache available Mem: 2,9Gi 1,3Gi 493Mi 140Mi 1,1Gi 1,3Gi Swap: 4,0Gi 132Mi 3,9Gi
SELinux
To make sure it works fine with SELinux, we need to set the correct context to the file: 'swap_t'
.
~# semanage fcontext -a -t swapfile_t '/var/vm/swapfile0' ~# restorecon /var/vm/swapfile0 ~# ls -lZ /var/vm/ total 4194304 -rw-------. 1 root root unconfined_u:object_r:swapfile_t:s0 4294967296 5 jan 03.17 swapfile0
Tuning
To tune the cache so it doesn't swap too much, you can add these settings to sysctl.conf
. In some systems/distros, you can add them directly there. In others you make an xtra file that will be sourced.
On my Rocky Linux system, I use an xtra file, like this:
~# vim /etc/sysctl.d/90-swappiness.conf
Then add this content:
# # /etc/sysctl.d/90-swappiness.conf # # Description: # sysctl.conf settings for swap # vm.swappiness=10 vm.vfs_cache_pressure=40 vm.dirty_background_ratio=10 vm.dirty_ratio=15
Now all is good. :)
// Happy hacking… 👍
· Eric
Top comments (0)