banner
李大仁博客

李大仁博客

天地虽大,但有一念向善,心存良知,虽凡夫俗子,皆可为圣贤。

[Linux] Creating and Enabling Swap Partition

If your server is constantly reporting insufficient memory and frequently causing services to be forcibly killed, enabling a swap partition as virtual memory is a good choice without increasing physical memory. The DigitalOcean VPS I purchased with 512MB of memory is basically not enough, but fortunately, the VPS's host uses SSD, and the normal read and write speeds are above 300MB/s. After enabling swap, the performance has improved a lot, especially in handling memory-consuming scripts.

Principles for creating a swap partition:

  1. The size of the created swap partition should be larger than the actual physical memory capacity, but not too large to avoid wasting disk space.
  2. If memory IO requests are frequent and the IO queue waiting time for a single swap partition is too long, you can create multiple swap partitions.
  3. In principle, it is preferred to create on the device with the fastest IO speed.

Steps to create a swap partition:

  1. Create a blank file for swap partition storage.

Create a 1GB blank file for SWAP partition#

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

Usually, a file with a size 2 to 2.5 times the physical memory is created as the swap partition.

  1. Use mkswap to format the file as a swap file system.

mkswap -f /swap

-f: Use the file as the swap partition#

  1. Enable the swap file that was just created.

swapon /swap

  1. If necessary, you can set the swap file to be automatically enabled at startup by modifying /etc/fstab and adding a line.

/swap swap swap defaults 0 0 # Enable swap at startup

  1. If you don't need to enable swap or need to adjust the swap size, you can use the swapoff command to disable swap.

swapoff /swap

After disabling swap, you can delete the corresponding swap file to remove the swap partition. If you need to adjust the swap partition size, start from the first step to recreate it.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.