I need to add a swap file to a running VM, but I do now want to attach a new disk.
I’ll use a file on my VM to use as swapfile.
We are going to use a file as swap, mounting it as a block device (this will allow us, eventually, to use dm-crypt and encrypt the swap partition)
Create a swap file
Create 1Gb file filled with random stuff
dd if=/dev/urandom of=/swapfile.swap bs=1M count=1024
chmod 600 /root/swapfile.swap
mkswap /swapfile.swap
Create systemd service to load swap
vim /etc/systemd/system/fileswap.service
Fill the file with this lines
[Unit]
Description=Mount my swap
[Service]
Type=oneshot
Environment="SWAPFILE=/swapfile.swap"
RemainAfterExit=true
ExecStartPre=/usr/sbin/losetup /dev/loop0 ${SWAPFILE}
ExecStart=/sbin/swapon /dev/loop0
ExecStop=/sbin/swapoff /dev/loop0
ExecStopPost=/usr/sbin/losetup -d /dev/loop0
[Install]
WantedBy=multi-user.target
Enable and test
systemctl daemon-reload
#enable service
systemctl enable fileswap.service
# start service
systemct start fileswap.service
# stop service
systemctl stop fileswap.service
Tips
If your file system is subject to COW it is a good idea to disable cow operations on swap file
lsattr /swapfile.swap
chattr +C /swapfile.swap
lsattr /swapfile.swap
- chattr (C option)
- A file with the ‘C’ attribute set will not be subject to copy-on-write updates. This flag is only supported on file systems which perform copy-on-write. (Note: For btrfs, the ‘C’ flag should be set on new or empty files. If it is set on a file which already has data blocks, it is undefined when the blocks assigned to the file will be fully stable. If the ‘C’ flag is set on a directory, it will have no effect on the directory, but new files created in that directory will have the No_COW attribute set.)
Plain and easy alternative
We can use a file directly and use it as swapfile
dd if=/dev/urandom of=/swapfile.swap bs=1M count=1024
chmod 600 /swapfile.swap
mkswap /swapfile.swap
swapon /swapfile.swap
Add this line in /etc/fstab
/swapfile.swap none swap sw 0 0