Saturday, December 6, 2014

Creating Swap File in CoreOS


     If you are using CoreOS, sometimes such situations arise when one or more docker containers do not have enough RAM. Especially if you are using vps with minimal configuration. In this case instead of changing your vps it's appropriate to use swap.
 


Firstly, switch to sudo and create swap file:

 sudo -i  
 touch /2GiB.swap  
 chattr +C /2GiB.swap  
 fallocate -l 2048m /2GiB.swap  
 chmod 600 /2GiB.swap  
 mkswap /2GiB.swap  

Congrats! That's done. Now we have to make swap start after boot using system ( /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  

Then add service and start:

 systemctl enable /etc/systemd/system/swap.service  
 systemctl start swap  

That's all! You can inspect swap service after rebooting:

 cat /proc/sys/vm/swappiness  
 sysctl vm.swappiness=10  
 sysctl vm.vfs_cache_pressure=50  
 

1 comment: