Adding a Swap File to Your Linux Server 🐧 (feat. Solving Memory Shortage!)

Hello! Have you ever encountered scary messages like “Memory exhausted” or “Out of Memory” while managing a Linux server, or experienced your server suddenly slowing down? 😨 Most of these issues are due to a RAM (memory) shortage.

Problems arise when the memory required by an application exceeds the actual physical RAM capacity. In such cases, our savior is Swap!

Today, we will learn in detail how to use a portion of your server’s hard disk (or SSD) space as virtual memory, specifically, how to create a swap file and apply it to your system. Shall we begin? πŸš€

πŸ€” Wait, what is Swap?

Simply put, Swap can be easily understood as ‘an extension of RAM’.

  • RAM (Desk πŸ“š): Fast and expensive memory that the CPU uses for current tasks.
  • Swap (Auxiliary Drawer next to the Desk πŸ—„οΈ): A space on the hard disk where data not immediately in use is temporarily moved when RAM is full.

Of course, a hard disk is much slower than RAM, so using too much swap is not ideal. However, it’s much better than a service completely crashing due to insufficient memory, isn’t it? It plays a crucial role in significantly enhancing system stability in emergencies.


βœ… Step 1: Create a Swap File πŸ“‚

First, you need to create a file to be used as swap space. This is the process of reserving a portion of your hard disk, saying, “I’m going to use this much for swap!” Here, we will create a 1024MB (1GB) file named /swfile.

1. Create a file with the dd command

Open your terminal and enter the command below. (You need root privileges, so use sudo!)

sudo dd if=/dev/zero of=/swfile bs=1M count=1024

The command looks a bit complex, doesn’t it? Let’s break it down.

  • sudo: Executes the command with administrator privileges.
  • dd: A powerful command for manipulating disks or files.
  • if=/dev/zero: Uses data filled with zeros as the input source. In other words, it creates an empty file.
  • of=/swfile: Creates a file named swfile in the / (root directory).
  • bs=1M: Transfers data in 1MB blocks at a time.
  • count=1024: Repeats the 1MB block size set above 1024 times.
  • Result: A file of 1MB * 1024 = 1024MB = 1GB is created! πŸŽ‰

2. Security settings are essential! πŸ”

Sensitive information from memory (e.g., passwords, personal data) can be stored in the swap file. Therefore, you must restrict permissions so that only the system (root user) can read and write to this file.

sudo chmod 600 /swfile
  • chmod 600: This command changes file permissions. 600 means ‘only the owner (root) can read and write, and other users can do nothing.’ This is a very important security step, so please make sure to execute it!

✨ Step 2: Transform the file into swap space!

Currently, /swfile is just an ordinary file filled with zeros. We need to format it so that the Linux kernel recognizes it as “Ah, this is swap space!”

sudo mkswap /swfile
  • mkswap: Short for “Make Swap,” this command initializes a specified file or partition as a swap area. Now the system is ready to use /swfile as swap.

πŸš€ Step 3: Activate and Verify Swap Immediately

Preparation is complete! Now it’s time to command the system: “Start using this swap file right now!”

1. Activate Swap

sudo swapon /swfile
  • swapon: This command activates a swap device. As soon as this command is executed, the system begins using /swfile as virtual memory.

2. Let’s check if it’s applied correctly? βœ…

We need to verify if swap has been applied successfully, right? You can check with the command below.

sudo swapon --show

If the result is as shown below, it’s a success!

NAME      TYPE SIZE USED PRIO
/swfile   file 1G     0B   -2

You can also see the overall memory situation at a glance with the free -h command.

free -h
              total        used        free      shared  buff/cache   available
Mem:          3.8Gi       1.1Gi       2.1Gi       2.0Mi       634Mi       2.5Gi
Swap:         1.0Gi          0B       1.0Gi

If you see 1.0Gi in the Swap entry, it has been perfectly applied!


πŸ’Ύ Step 4: It’s Okay to Reboot! Set Up Permanently

Congratulations! The swap file has been activated. However, this setting is temporary, so if you reboot the server, swap will be deactivated. 😱

You need to modify a configuration file so that the system automatically loads the swap file every time it reboots. This setting is handled by the /etc/fstab file.

Add swap information to the /etc/fstab file

Executing the command below will automatically add the swap setting to the very last line of the file.

echo '/swfile swap swap defaults 0 0' | sudo tee -a /etc/fstab
  • This single line means: “System, activate /swfile as a swap type with default options every time you boot!”

Now, even if you reboot the server, the swap file will be automatically activated. It’s really simple, isn’t it?


Conclusion

Today, we learned how to create and apply a swap file, which enhances the stability of your Linux server.

1. Create file with dd πŸ“‚

2. Set security with chmod πŸ”

3. Format swap with mkswap ✨

4. Activate immediately with swapon πŸš€

5. Register in /etc/fstab for permanent application πŸ’Ύ

Now you can worry a little less about sudden service interruptions due to memory shortages. πŸ₯³ We hope this guide has been a great help in your server management!

Tags: Linux, Swap, Virtual Memory, Server Management, Ubuntu, CentOS, Memory Shortage


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *