Longstreet Labs Blog

How to add swap space to your Linux server 

Posted by Daniel Waltzer on Nov 9, 2016 5:37:00 PM

Warning: This post is technical!

Is your website slow or crashing? Is MySQL shutting itself down? More likely than not, your server is running out of memory. The thing is, if you're hosting a basic website that receives reasonable traffic, you shouldn't need too many server resources to keep your site running. A good solution is to set up swap space by creating an area of your hard drive that is reserved for extra memory. While this swap memory may be a little slower, you've probably got a lot of space to spare on your hard drive, so if you're hosting a website, it's always a good idea to set up some swap space as a backup.

First, let's create the swap space:

$ sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024

This will create a 1GB (1024MB) partition. If your disk space and resources warrant more space, you can increase the count=1024 to something like count=2048 if you want to create 2GB of swap space.

Next, let's define this partion as swap space:

$ sudo /sbin/mkswap /var/swap.1

We need to also set the proper file permissions:

$ sudo chmod 600 /var/swap.1

Then, let's turn it on:

$ sudo /sbin/swapon /var/swap.1

That's it...your swap space is up and running. We also recommend setting the swap space to be running by default after a server reboot. To do this...

Edit the fstab file:

$ sudo nano /etc/fstab

And add the following line:

/var/swap.1 swap swap defaults 0 0

Now, exit the editor by pressing ctrl+x, type y to save changes, and press enter

To confirm that your swap space is active, you can run the following command:

$ free -m

And with that, you can rest assured that your web server's memory has a backup plan. Questions? Feel free to drop us a line.

Topics: Tutorials, AWS

The blog for businesses with customers

Subscribe to Email Updates

Recent Posts