Running npm install on a Server with 1GB Memory using Swap
Running npm install
on a server with only 1GB of memory can be challenging due to limited RAM. However, by enabling swap space, you can extend the virtual memory and ensure smooth operation. This blog post will guide you through the process of creating and enabling a swap partition on your server.
What is Swap?
Swap space is a designated area on a hard disk used to temporarily hold inactive memory pages. It acts as a virtual extension of your physical memory (RAM), allowing the system to manage memory more efficiently. When the system runs out of physical memory, it moves inactive pages to the swap space, freeing up RAM for active processes. Although swap is slower than physical memory, it can prevent out-of-memory errors and improve system stability.
Step-by-Step Guide to Enable Swap Space
-
Check Existing Swap Information
Before creating swap space, check if any swap is already configured:
sudo swapon --show
-
Check Disk Partition Availability
Ensure you have enough disk space for the swap file. Use the
df
command:df -h
-
Create a Swap File
Allocate a 1GB swap file in the root directory using the
fallocate
program:sudo fallocate -l 1G /swapfile
-
Enable the Swap File
Secure the swap file by setting appropriate permissions:
sudo chmod 600 /swapfile
Format the file as swap space:
sudo mkswap /swapfile
Enable the swap file:
sudo swapon /swapfile
-
Make the Swap File Permanent
To ensure the swap file is used after a reboot, add it to the
/etc/fstab
file:sudo cp /etc/fstab /etc/fstab.bak
Edit
/etc/fstab
to include the swap file:echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
-
Optimize Swap Settings
Adjust the
swappiness
value to control how often the system uses swap space. A lower value reduces swap usage, enhancing performance. Check the current value:cat /proc/sys/vm/swappiness
Set the
swappiness
to 15:sudo sysctl vm.swappiness=15
Make this change permanent by adding it to
/etc/sysctl.conf
:echo 'vm.swappiness=15' | sudo tee -a /etc/sysctl.conf
Adjust the
vfs_cache_pressure
value to balance cache retention and swap usage. Check the current value:cat /proc/sys/vm/vfs_cache_pressure
Set it to 60:
sudo sysctl vm.vfs_cache_pressure=60
Make this change permanent:
echo 'vm.vfs_cache_pressure=60' | sudo tee -a /etc/sysctl.conf
Conclusion
Creating and enabling swap space allows your server to handle memory-intensive operations, such as npm install
, more efficiently. While swap is not a substitute for physical RAM, it can provide a temporary solution to memory limitations, ensuring smoother performance and preventing out-of-memory errors. By following the steps outlined above, you can optimize your server’s memory management and enhance its overall stability.