为您的 Linux 服务器创建交换文件

:bulb: For servers with <= 2GB of RAM, running ./discourse-setup will prompt for and automatically create a 2GB swapfile.

Most cloud virtual machine providers do not set up swapfiles as part of their server provisioning.

In particular, upgrading Discourse produces a lot of memory pressure. With a swap file, rather than randomly terminating processes with an out of memory error, things will slow down instead. Having a swap file is a cheap insurance policy that protects you from many other load related failures.

This can be done at any time from the command line on your server.

Set up a 2GB swap file

We recommend a 2GB swap file for Discourse, unless your server has 4GB or more of memory.

In the shell you have opened to your droplet, do the following:

:warning: You will need to be root for much of this, so either be root or sudo -s before running these commands! Don’t forget to exit root afterwards.

  1. Create an empty swapfile

     install -o root -g root -m 0600 /dev/null /swapfile
    
  2. write out a 2GB file named ‘swapfile’

     dd if=/dev/zero of=/swapfile bs=1k count=2048k
    
  3. tell linux this is the swap file:

     mkswap /swapfile
    
  4. Activate it

     swapon /swapfile
    
  5. Add it to the file system table so its there after reboot:

     echo "/swapfile       swap    swap    auto      0       0" | tee -a /etc/fstab
    
  6. Set the swappiness to 10 so its only uses as an emergency buffer

     sysctl -w vm.swappiness=10
     echo vm.swappiness = 10 | tee -a /etc/sysctl.conf
    

The whole thing as a single copy and pastable script:

install -o root -g root -m 0600 /dev/null /swapfile
dd if=/dev/zero of=/swapfile bs=1k count=2048k
mkswap /swapfile
swapon /swapfile
echo "/swapfile       swap    swap    auto      0       0" | tee -a /etc/fstab
sysctl -w vm.swappiness=10
echo vm.swappiness = 10 | tee -a /etc/sysctl.conf

Last edited by @JammyDodger 2022-05-23T18:45:59Z

Check documentPerform check on document:
95 个赞

我一直在尝试设置一个更大的交换文件(4GB 而不是默认的 2GB),但在运行上面的脚本时遇到了这个问题:

rm: cannot remove `swapfile’: Operation not permitted

为了解决这个问题,我不得不先这样做:

  1. 重启服务器(由于交换文件使用量大,它不允许我 swapoff
  2. swapoff -a -v
3 个赞

出于类似的原因,我运行了两个交换文件:

# swapon
名称                       类型  大小  已用  优先级
/var/local/swap/swapfile.0 文件 1024M 44.9M   -3
/var/local/swap/swapfile.1 文件 1024M 1024M   -2

第二个交换文件可能是避免重启的巧妙方法。只需创建一个第二个交换文件,启用它,然后删除第一个。

4 个赞

那么我们就不需要遵循这个指南来创建2GB的交换文件了,因为如果我们的内存少于2GB,安装程序就会自动创建它?

是的——但如果你更改了服务器配置,或者进行了迁移,你可能需要自己处理。 (同时,安装程序不会处理两个重要的内核配置——请参阅 MKJ 的意见化 Discourse 部署配置

10 个帖子被拆分到一个新主题:高重建内存要求:2025 年 4 月版