Matt Howlett

Matt Howlett

Software Development and Mathematics Blog

Enabling Swap on CoreOS


If you're a penny-pinching hack like me, you'll likely want to turn on swap to try and cram as many services as you can onto your bargain basement 512mb VM.

This is how I'm enabling swap memory on my CoreOS 752.1.0-alpha machine hosted at Digital Ocean. Adapted from notes by others found on github.

Put the following in /etc/systemd/system/swapon.service

Description=Turn on swap

ExecStartPre=/usr/bin/touch ${SWAPFILE}
ExecStartPre=/usr/bin/chattr +C ${SWAPFILE}
ExecStartPre=/usr/bin/fallocate -l 1024m ${SWAPFILE}
ExecStartPre=/usr/bin/chmod 600 ${SWAPFILE}
ExecStartPre=/usr/sbin/mkswap ${SWAPFILE}
ExecStartPre=/usr/sbin/losetup -f ${SWAPFILE}
ExecStart=/usr/bin/sh -c "/sbin/swapon $(/usr/sbin/losetup -j ${SWAPFILE} | /usr/bin/cut -d : -f 1)"
ExecStop=/usr/bin/sh -c "/sbin/swapoff $(/usr/sbin/losetup -j ${SWAPFILE} | /usr/bin/cut -d : -f 1)"
ExecStopPost=/usr/bin/sh -c "/usr/sbin/losetup -d $(/usr/sbin/losetup -j ${SWAPFILE} | /usr/bin/cut -d : -f 1)"


note that copy on write is turned off to boost performance and that it is evidently important that this is done before writing anything to the file (hence the ordering of the commands).

with the service file created, enable it thus:

sudo systemctl enable swapon.service

now you can reboot (to verify that swap is in fact enabled on reboot):

sudo reboot

or without rebooting:

sudo systemctl start swapon

you can see if it worked by looking at what is reported by free: