添加删除vps中的swap分区

大部分vps都没有swap分区,下面的办法提供了增加一个2G swap分区的方式

创建分区

fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo “/swapfile swap swap defaults 0 0” >> /etc/fstab

删除分区

swapoff -v /swapfile

首先,创建swap的基本步骤是:

创建swap文件:

sudo fallocate -l 4G /swapfile
# 或者用 dd 命令替代
sudo dd if=/dev/zero of=/swapfile bs=1G count=4
  • fallocate 更快但部分文件系统可能不支持
  • dd 命令更通用,bs是块大小,count是块数量

设置权限:

sudo chmod 600 /swapfile
  • 出于安全考虑,只允许root读写

格式化为swap:

sudo mkswap /swapfile
  • 将文件标记为swap格式

启用swap:

sudo swapon /swapfile
  • 激活swap分区

设置开机自动挂载:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
  • 将配置写入fstab文件

这些命令中:

  • 1-4是必须的
  • 第5步是可选的,但建议添加以实现开机自动挂载

删除swap:

首先停用swap:

sudo swapoff /swapfile
  • 这会让系统停止使用该swap
  • 系统会将swap中的数据移回内存

从fstab中删除自动挂载项:

sudo vim /etc/fstab

找到并删除这一行:

/swapfile none swap sw 0 0

或者用sed命令:

sudo sed -i '/swapfile/d' /etc/fstab

删除swap文件:

sudo rm /swapfile

确认swap已被删除:

# 查看当前swap使用情况
free -h

# 或者
swapon --show

@Chatbot Translate this thread to English please!

Certainly! Here’s the translation of the thread:


linuxren said: Most VPS do not have a swap partition. The following method provides a way to add a 2GB swap partition.

Creating the partition:

fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo "/swapfile swap swap defaults 0 0" >> /etc/fstab

Deleting the partition:

swapoff -v /swapfile

Tristan said: First, the basic steps to create a swap file are:

Create a swap file:

sudo fallocate -l 4G /swapfile
# Or use the dd command as an alternative
sudo dd if=/dev/zero of=/swapfile bs=1G count=4
  • fallocate is faster but may not be supported by some file systems.
  • dd is more universal; bs is block size, and count is the number of blocks.

Set permissions:

sudo chmod 600 /swapfile
  • For security reasons, only root is allowed to read and write.

Format as swap:

sudo mkswap /swapfile
  • This marks the file as swap format.

Enable swap:

sudo swapon /swapfile
  • This activates the swap partition.

Set to auto-mount at boot:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
  • This writes the configuration to the fstab file.

These commands:

  • Steps 1-4 are mandatory.
  • Step 5 is optional but recommended to ensure auto-mount at boot.

Tristan said: To delete swap:

First, disable swap:

sudo swapoff /swapfile
  • This will stop the system from using the swap.
  • The system will move data from the swap back to memory.

Remove the auto-mount entry from fstab:

sudo vim /etc/fstab

Find and delete this line:

/swapfile none swap sw 0 0

Or use the sed command:

sudo sed -i '/swapfile/d' /etc/fstab

Delete the swap file:

sudo rm /swapfile

Confirm that the swap has been deleted:

# Check current swap usage
free -h

# Or
swapon --show

Let me know if you need anything else!