Ubuntu 18.04下修改原系统swap的大小

因为mysql服务老是无故挂掉,检查syslog日志提示:Out of memory: Kill process 20867 (mysqld)
系统是阿里云的ECS,都不记得是默认系统就有swap了还是之前dd的系统原本就有swap,不记得了,但1G的内存才设置了1G的swap明显是不够的,于是打算重新设置swap的大小。

Step 1).禁用原swap
[email protected]:~# swapoff /swapfile

运行了几次以上命令都被Killed了,然后停掉nginx、php7.4-fpm、mysql服务后重新运行swapoff /swapfile

Step 2).删除原swap文件
[email protected]:~# rm -rf /swapfile

Step 3).制作2G的swapfile文件
[email protected]:~# dd if=/dev/zero of=/swapfile count=2048 bs=1M

Step 4).设置swapfile文件权限
[email protected]:~# chmod 600 /swapfile

Step 5).设置交换文件
[email protected]:~# mkswap /swapfile

Step 6).启用swap file
[email protected]:~# swapon /swapfile

Step 7).设置系统重新启动后也生效

[email protected]:~# vi /etc/fstab

增加以下行到文件最尾既可:
/swapfile none swap sw 0 0
:wq!
保存退出完成linux下swap的设置。

另,设置memory overcommit,在/etc/sysctl.conf文件加入参数:
vm.overcommit_memory = 1
[email protected]:~# sysctl -p

0 – Heuristic overcommit handling. 这是缺省值,它允许overcommit,但过于明目张胆的overcommit会被拒绝,比如sshd一次性申请的内存大小就超过了系统总内存。Heuristic的意思是“试探式的”,内核利用某种算法猜测你的内存申请是否合理,它认为不合理就会拒绝overcommit。

1 – Always overcommit. 允许overcommit,对内存申请来者不拒。内核执行无内存过量使用处理。使用这个设置会增大内存超载的可能性,但也可以增强大量使用内存任务的性能。

2 – Don’t overcommit. 禁止overcommit。 内存拒绝等于或者大于总可用 swap 大小以及 overcommit_ratio 指定的物理 RAM 比例的内存请求。如果您希望减小内存过度使用的风险,这个设置就是最好的。

参考相关文章:Linux下增加swap file