Alpine Linux is a lightweight distribution designed for security, simplicity, and resource efficiency. While minimalistic, it may not have swap space enabled by default.
Before You Begin
Swap space is virtual memory on your hard drive used when physical RAM is full. However, it’s slower than RAM and should not replace physical memory.
Swap Space Calculation
Generally, swap space should be:
- 2x physical RAM for up to 2 GB RAM
- Additional 1x physical RAM above 2 GB
- Minimum 32 MB
- For >32 GB RAM, about 1/2 physical RAM
Creating a Swap File
- Create swap file:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152
- Set permissions:
sudo chmod 600 /swapfile
- Set up swap area:
sudo mkswap /swapfile
- Activate swap:
sudo swapon /swapfile
- Add to
/etc/fstab
:
/swapfile swap swap defaults 0 0
Swappiness
Swappiness controls how aggressively the system uses swap:
- Range: 0-100
- 0: Minimize swapping
- 100: Aggressive swapping
To check/modify:
cat /proc/sys/vm/swappiness
sudo sysctl vm.swappiness=60
Make it permanent by adding to /etc/sysctl.conf
:
vm.swappiness=60
Verifying Swap Space
Check swap status:
free -h
swapon --show
Removing Swap File
To remove swap:
sudo swapoff /swapfile
sudo rm /swapfile
Remove the entry from /etc/fstab
.
Conclusion
Adding swap space to Alpine Linux provides extra memory when needed. Remember to balance between performance and resource usage by adjusting swappiness appropriately.