Skip to content

Instantly share code, notes, and snippets.

@kacinskas
Last active February 17, 2019 16:57
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save kacinskas/8d58ebce2e4cf6c9a09b to your computer and use it in GitHub Desktop.
Save kacinskas/8d58ebce2e4cf6c9a09b to your computer and use it in GitHub Desktop.
# swith to sudo
sudo -i
# create swap
touch /2GiB.swap
chattr +C /2GiB.swap
fallocate -l 2048m /2GiB.swap
chmod 600 /2GiB.swap
mkswap /2GiB.swap
# create service unit to start swap [/etc/systemd/system/swap.service]
[Unit]
Description=Turn on swap
[Service]
Type=oneshot
Environment="SWAPFILE=/2GiB.swap"
RemainAfterExit=true
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)"
[Install]
WantedBy=multi-user.target
# add service and start
systemctl enable /etc/systemd/system/swap.service
systemctl start swap
# reboot
reboot
# Options
cat /proc/sys/vm/swappiness
sysctl vm.swappiness=10
sysctl vm.vfs_cache_pressure=50
https://github.com/coreos/docs/issues/52
@lordelph
Copy link

lordelph commented Dec 5, 2016

As this gist ranks highly for "coreos swap" I wanted to add this caveat:

Using losetup on the swap file was recommended for btrfs (see coreos/docs#52) but causes problems if used on ext4. Here's a report similar to what I've experienced coreos/bugs#429

CoreOS fairly recently added some documentation on swap creation which does not use losetup either https://coreos.com/os/docs/latest/adding-swap.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment