I can certainly help you with refining the text based on the suggestions. Here's an updated version:
Guarding against out-of-memory errors is crucial for applications, and one effective method is to add swap space to your server. This guide walks you through the process of adding a swap file to an Ubuntu 22.04 server.
Swap is a dedicated portion of hard drive storage reserved for the operating system to temporarily store data when it exceeds the capacity of RAM. Although writing to swap is slower than RAM, it serves as a safety net when RAM is depleted, preventing out-of-memory errors.
Before starting, check if your system already has swap space:
sudo swapon --show
If there's no output, your system currently lacks swap space.
Verify using the free
utility:
free -h
No active swap is indicated in the output.
Ensure sufficient disk space by checking current usage:
df -h
Look for available space on the device with "/" in the Mounted on column. A rule of thumb is to allocate swap equal to or double the RAM size.
Create a swap file using the efficient fallocate
program. For example, on a server with 1GB RAM:
sudo fallocate -l 1G /swapfile
Verify the reserved space:
ls -lh /swapfile
Secure the swap file permissions so that only root user can modify it:
sudo chmod 600 /swapfile
Verify permissions:
ls -lh /swapfile
Mark the file as swap space:
sudo mkswap /swapfile
Enable the swap file:
sudo swapon /swapfile
Verify availability:
sudo swapon --show
Use free
utility for confirmation:
free -h
Ensure the swap file persists after a reboot by adding it to /etc/fstab
:
sudo cp /etc/fstab /etc/fstab.bak
Add the swap file information:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Next we’ll review some settings we can update to tune our swap space.
View Current parameters:
cat /proc/sys/vm/swappiness
Set swappiness (e.g., 10):
sudo sysctl vm.swappiness=10
Make the change persistent:
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
View Current parameters:
cat /proc/sys/vm/vfs_cache_pressure
Set vfs_cache_pressure to 50:
sudo sysctl vm.vfs_cache_pressure=50
Persist the change:
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
At the bottom, add the line that specifies your new value:
Save and close the file when you are finished.
Adding swap space provides a safety net against out-of-memory issues. Optimize application configurations or consider a server upgrade if encountering frequent OOM errors.
Happy Coding!
Technical Author with a passion for translating the complexities of software, computers, and emerging technologies into accessible and engaging content. Armed with a background in computer science, I blend technical expertise with a flair for effective communication in my writing. Join me on this tech-savvy journey as we explore coding languages, unravel the nuances of software architecture, and stay informed about the latest tech trends. Let's navigate the digital frontier together!