在使用mysql5.7进行当做网站的数据库时,有时候会莫名死掉,网站也会因此打不开,重新启动mysql也无法正常启动。通过查看mysql的告警日志发现:
cat /etc/my.cnf
...
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
...
cat /var/log/mysqld.log
发现是因为mysql无法分配足够的内存供使用,因此无法正常启动。
2017-08-26T01:13:48.030515Z 0 [ERROR] InnoDB: mmap(137428992 bytes) failed; errno 12
2017-08-26T01:13:48.030540Z 0 [ERROR] InnoDB: Cannot allocate memory for the buffer pool
2017-08-26T01:13:48.030555Z 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2017-08-26T01:13:48.030583Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2017-08-26T01:13:48.030595Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2017-08-26T01:13:48.030606Z 0 [ERROR] Failed to initialize plugins.
2017-08-26T01:13:48.030614Z 0 [ERROR] Aborting
因为是服务器centos7,内存仅有1G,因此需要设置swap空间,使用free命令查看:
free total used fre shared buff/cache available
Mem: 1016380 718408 119792 58364 178180 102636
Swap: 0 0 0
发现没有分配swap空间,于是执行以下命令(创建2G的swap空间)
[root@coolesthacker ~]# dd if=/dev/zero of=/swap_file bs=4096 count=512k
524288+0 records in
524288+0 records out
2147483648 bytes (2.1 GB) copied, 6.18081 s, 347 MB/s
[root@coolesthacker ~]# mkswap /swap_file
Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=*********************************
[root@coolesthacker ~]# chmod 600 /swap_file
[root@coolesthacker ~]# swapon /swap_file
[root@coolesthacker ~]# swapon -s
Filename Type Size Used Priority
/swap_file file 2097148 0 -1
[root@coolesthacker ~]# free
total used free shared buff/cache available
Mem: 1016380 722288 67684 58396 226408 87340
Swap: 2097148 0 2097148
设置完成之后,进入etc/fstab进行设置,这样系统在重新启动时会依照之前的配置自动设置swap空间。
vim /ect/fstab
在文件中加入以下一句保存后就可以了
/swap_file swap swap sw 0 0
然后重新启动mysql,发现启动正常^_^。