經常爆內存,導致很多應用沒有辦法一直正常運行,可以通過設置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 -htotal used free shared buff/cache available
Mem: 23Gi 22Gi 203Mi 1.0Mi 777Mi 580Mi
Swap: 0B 0B 0B
root@ubuntu:/#
root@ubuntu:/# sudo dd if=/dev/zero of=/swapfile bs=1G count=8
8+0 records in
8+0 records out
8589934592 bytes (8.6 GB, 8.0 GiB) copied, 8.14848 s, 1.1 GB/s
root@ubuntu:/# sudo chmod 600 /swapfile
root@ubuntu:/# sudo mkswap /swapfile
Setting up swapspace version 1, size = 8 GiB (8589930496 bytes)
no label, UUID=7bab5b72-8602-4094-9211-622de895302d
root@ubuntu:/# sudo swapon /swapfile
root@ubuntu:/# sudo vim /etc/fstab
root@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 0
root@ubuntu:/#
root@ubuntu:/# free -htotal used free shared buff/cache available
Mem: 23Gi 4.5Gi 7.2Gi 1.0Mi 11Gi 18Gi
Swap: 8.0Gi 0B 8.0Gi
root@ubuntu:/#