How To Add Swap on Ubuntu

×

Error message

Deprecated function: The each() function is deprecated. This message will be suppressed on further calls in _menu_load_objects() (line 569 of /homepages/46/d762693627/htdocs/dc/includes/menu.inc).
How To Add Swap on Ubuntu

When you run some composer commands, you may see an error message like "The following exception is caused by a lack of memory or swap, or not having swap configured". So how to config swap? Here is a few steps you can follow to config and switch on swap.

step1: there are commands to check if any swap exists.

sudo swapon -s
free -m

             total       used       free     shared    buffers     cached
Mem:          3953        154       3799          0          8         83
-/+ buffers/cache:         62       3890
Swap:            0          0          0

We can see if nothing returns with the first command, that means no swap configed. Similarly if all values for swap are 0 in the result of the second command. This shows no swap set up.

step2: Create a Swap File. It's the same with creating any other files.

sudo touch /swapfile

After file created, we need to run the following command to config the size of the file. For this case the size is 4GB.

sudo fallocate -l 4G /swapfile

We can check it by the command:

ls -lh /swapfile

-rw-r--r-- 1 root root 4.0G Apr 28 17:19 /swapfile

Step3: Enabling the Swap File. Before we do that though, we need to adjust the permissions on our file so that it isn't readable by anyone besides root.

sudo chmod 600 /swapfile

Now that our file is more secure, we can tell our system to set up the swap space by typing:

sudo mkswap /swapfile

Our file is now ready to be used as a swap space. We can enable this by typing:

sudo swapon /swapfile

 You can switch it off by the command:

sudo swapoff /swapfile

Step4: Make the Swap File Permanent. We have our swap file enabled, but when we reboot, the server will not automatically enable the file. We can change that though by modifying the fstab file.

sudo vi /etc/fstab

At the bottom of the file, you need to add a line that will tell the operating system to automatically use the file you created:

/swapfile   none    swap    sw    0   0

After all above configed, you ran the composer command again. You may find the problem has already been solved.

blog tag: