在使用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,發現啟動正常^_^。