Loopback swap files

Setting up a loopback swap file is something I do fairly commonly on my virtual servers - RAM costs extra money - whereas SSD storage is common and included! Repartitioning’s too much messing around on DigitalOcean, so I set up a loopback file and it just works.

Here’s the commands to make a 2GB file (change count for different sizes):

yaleman@server:~# sudo dd if=/dev/zero of=/swap.img bs=1024 count=2097152
2097152+0 records in
2097152+0 records out
2147483648 bytes (2.1 GB) copied, 9.69851 s, 221 MB/s
yaleman@server:~# sudo chmod 0600 /swap.img
yaleman@server:~# sudo mkswap /swap.img
Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=a78f6315-aba5-4d88-bb67-211f1a0c5e56

Edit the filesystem table:

yaleman@server:~# sudo vi /etc/fstab

Add the following line:

/swap.img none swap sw 0 1

Enable the swap now!

yaleman@server:~# sudo swapon /swap.img

Check what swap’s enabled:

yaleman@server:~# cat /proc/swaps .
Filename   Type  Size     Used  Priority
/swap.img  file  2097148  52    -1

There ’tis!



#ssd #swap #HOWTO #linux