经常爆内存,导致很多应用没有办法一直正常运行,可以通过设置swap来缓解一下,虽然和内存的速度无法媲美,但是能一定程度缓解一下问题。
一、查看当前分区
查看当前系统的swap大小
free -m
二、关闭现有的swap分区
将/etc/fstab文件中所有设置为swap的设备关闭,然后才能创建swap
sudo swapoff -a
三、创建新的swap文件
bs×count=最后生成的swap大小,这里设置8G
sudo dd if=/dev/zero of=/swapfile bs=1G count=8
四、设置权限
出于安全原因,交换文件应该只能被root用户读写
sudo chmod 600 /swapfile
五、设置swap
sudo mkswap /swapfile
六、启用swap
sudo swapon /swapfile
七、设置swap永久有效
编辑 sudo vim /etc/fstab 将下面内容添加到最后一行
/swapfile swap swap sw 0 0
全程操作记录
root@ubuntu:/# free -h total used free shared buff/cache availableMem: 23Gi 22Gi 203Mi 1.0Mi 777Mi 580MiSwap: 0B 0B 0Broot@ubuntu:/#root@ubuntu:/# sudo dd if=/dev/zero of=/swapfile bs=1G count=88+0 records in8+0 records out8589934592 bytes (8.6 GB, 8.0 GiB) copied, 8.14848 s, 1.1 GB/sroot@ubuntu:/# sudo chmod 600 /swapfileroot@ubuntu:/# sudo mkswap /swapfileSetting up swapspace version 1, size = 8 GiB (8589930496 bytes)no label, UUID=7bab5b72-8602-4094-9211-622de895302droot@ubuntu:/# sudo swapon /swapfileroot@ubuntu:/# sudo vim /etc/fstabroot@ubuntu:/# root@ubuntu:/# cat /etc/fstab # /etc/fstab: static file system information.## Use 'blkid' to print the universally unique identifier for a# device; this may be used with UUID= as a more robust way to name devices# that works even if disks are added and removed. See fstab(5).## <file system> <mount point> <type> <options> <dump> <pass># / was on /dev/ubuntu-vg/ubuntu-lv during curtin installation/dev/disk/by-id/dm-uuid-LVM-L8iEhDkz0j7XOkZNxq1vqTybkF7AD0mbDMftF69chzey1qdN3t7jrCDJ1egzu2BE / ext4 defaults 0 1# /boot was on /dev/sda2 during curtin installation/dev/disk/by-uuid/ff68fd53-d03e-4dbe-91e1-414c0776da12 /boot ext4 defaults 0 1/dev/mapper/ubuntu--vg2-database /database ext4 defaults 0 0# swap/swapfile swap swap sw 0 0root@ubuntu:/# root@ubuntu:/# free -h total used free shared buff/cache availableMem: 23Gi 4.5Gi 7.2Gi 1.0Mi 11Gi 18GiSwap: 8.0Gi 0B 8.0Giroot@ubuntu:/#