swap-file-linux.md (1682B)
1 --- 2 title: "Creating a Swap file on Linux" 3 date: 2019-06-10T10:03:00 4 lastmod: 2020-08-27T01:15:00 5 tags: ["Formats", "Guides", "Linux", "Servers", "Snippets", "Software"] 6 --- 7 8 I've recently moved from a server with more than enough RAM, to a lower spec (and significantly cheaper!) VPS that still does 99% of what I want it to. 9 10 The issue however is that with the reduced RAM there's a very real possibility of running out and locking up the system. The easy (and cheap) solution is to add a swap file instead of repartitioning my disk space. 11 12 The notes here work with a 1GB swap file, but feel free to change these if need be. 13 14 Firstly we're going to create the file, set permissions and enable the swap file: 15 ``` 16 sudo dd if=/dev/zero of=/swap bs=1M count=1024 status=progress 17 sudo chmod 600 /swap 18 sudo mkswap /swap 19 sudo swapon /swap 20 ``` 21 22 This can then be mounted on boot by editing your `/etc/fstab` file and adding the following line: 23 ``` 24 /swap swap swap defaults 0 0 25 ``` 26 27 Now you can check this swap space is working by: 28 ``` 29 sudo swapon --show 30 ``` 31 32 Now the swap file is up and running, you can decide if you want to alter the *[swappiness](https://en.wikipedia.org/wiki/Paging#Swappiness)* value on your system which dictates how the file should be used. The default value on my system was `60`, but I've altered it to `10` using the below commands: 33 ``` 34 cat /proc/sys/vm/swappiness 35 sudo sysctl vm.swappiness=10 36 ``` 37 To make this change permanent, you'll need to write the value to your `sysctl.conf` file via: 38 ``` 39 echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf 40 ``` 41 42 * **Edit 2020-08-27:** Replaced `fallocate` instructions with `dd`, caused issues when trying to `swapon`.