Sorting the Swap Space on a Raspberry Pi

By default the Raspberry Pi uses a 100MB swap file on the SD card.  I have a 512MB Pi, and I've never actually seen the swap being used... but if it is, it will be horrifically slow and have some impact on the life of the card.  So, since I have hard drives plugged in (I have a 4-drive JBOD USB enclosure) I decided to move the swap.  (Most of the following commands need to be run as root or using sudo).

First I reduced the size of the partition on one of my drives and created a new 2GB partition.  I used the graphical tool GParted, but it's easy enough to do this using command line tools if you prefer.  Find out its device path using "ls /dev/sd*" and make it a swap partition:

mkswap /dev/sd??

Alternatively, you can use a swapfile rather than have a dedicated partition (substitute 2048 for whatever size file you want in MB):

dd if=/dev/zero of=/path/to/swapfile bs=1M count=2048
mkswap /path/to/swapfile
chown root.root /path/to/swapfile
chmod 0600 /path/to/swapfile

Now we want to turn on the new swap:

swapon /dev/sd??

Or:

swapon /path/to/swapfile

And finally turn off the old SD card swapfile:

dphys-swapfile swapoff


We can check that everything has worked by running:

free -h

You should now see a line beginning "Swap:" with whatever size partition/file you created.


Finally, we want this to be permanent... remove the dphys-swapfile package used for the SD card swapfile:

apt-get purge dphys-swapfile

Find the partition's UUID and add an entry to /etc/fstab (if you used a swapfile, skip over the UUID bit):

blkid

This will print a list of devices, e.g.:

/dev/mmcblk0p1: SEC_TYPE="msdos" UUID="1234-abcd" TYPE="vfat" 
/dev/mmcblk0p2: UUID="11111111-aaaa-aa11-11aa-aaaaaa111111" TYPE="ext4" 
/dev/sda1: LABEL="USBDrive" UUID="22222222-bbbb-bb22-22bb-bbbbbb222222" TYPE="ext4" 
/dev/sda2: LABEL="USBSwap" UUID="33333333-cccc-cc33-33cc-cccccc333333" TYPE="swap"

Find the line saying TYPE="swap" and make a note of the UUID.  Now open /etc/fstab for editing:

nano /etc/fstab

Add a line at the end of this file as follows (with the correct UUID):

UUID=33333333-cccc-cc33-33cc-cccccc333333   none   swap   defaults   0   0

Or:

/path/to/swapfile   none   swap   defaults   0   0

Reboot to test!  (Run free -h again to make sure the swap was mounted).