AWSでmysqlが止まる。もしくは、phpでOut Of Memoryのエラーが出る場合

AWSにはswap領域がない。

AWSのEC2には、Swap領域がないため仮想メモリを使えずphpでエラーになったり、MySqlが止まってしまったりします。
なので下記のように対策します。

対策

[root@rexius ~]# cat /var/log/mysqld.log
181001 10:48:01 [Note] Plugin 'FEDERATED' is disabled.
181001 10:48:01 InnoDB: The InnoDB memory heap is disabled
181001 10:48:01 InnoDB: Mutexes and rw_locks use GCC atomic builtins
181001 10:48:01 InnoDB: Compressed tables use zlib 1.2.8
181001 10:48:01 InnoDB: Using Linux native AIO
181001 10:48:01 InnoDB: Initializing buffer pool, size = 128.0M
InnoDB: mmap(137363456 bytes) failed; errno 12
181001 10:48:01 InnoDB: Completed initialization of buffer pool
181001 10:48:01 InnoDB: Fatal error: cannot allocate memory for the buffer pool
181001 10:48:01 [ERROR] Plugin 'InnoDB' init function returned error.
181001 10:48:01 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
181001 10:48:01 [ERROR] Unknown/unsupported storage engine: InnoDB
181001 10:48:01 [ERROR] Aborting

181001 10:48:01 [Note] /usr/libexec/mysql55/mysqld: Shutdown complete

[root@rexius lib]# free
total used free shared buffers cached
Mem: 4048016 1698908 2349108 416 25408 165964
-/+ buffers/cache: 1507536 2540480
Swap: 0 0 0

[root@rexius ~]# df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 2.0G 56K 2.0G 1% /dev
tmpfs 2.0G 0 2.0G 0% /dev/shm
/dev/xvda1 40G 30G 11G 75% /

[root@rexius ~]# dd if=/dev/zero of=/swapfile bs=1M count=4096
4096+0 records in
4096+0 records out
4294967296 bytes (4.3 GB) copied, 61.2381 s, 70.1 MB/s

[root@rexius ~]# mkswap /swapfile
Setting up swapspace version 1, size = 4194300 KiB
no label, UUID=0f88c85c-3c01-4e00-821e-39c171b1d344

[root@rexius ~]# swapon /swapfile
swapon: /swapfile: insecure permissions 0644, 0600 suggested.

[root@rexius ~]# free
total used free shared buffers cached
Mem: 4048016 3105976 942040 416 26896 1798824
-/+ buffers/cache: 1280256 2767760
Swap: 4194300 0 4194300

[root@rexius ~]# service mysqld restart
Stopping mysqld: [ OK ]
Starting mysqld: [ OK ]

[root@rexius ~]# vi /etc/fstab
#
LABEL=/ / ext4 defaults,noatime 1 1
tmpfs /dev/shm tmpfs defaults 0 0
devpts /dev/pts devpts gid=5,mode=620 0 0
sysfs /sys sysfs defaults 0 0
proc /proc proc defaults 0 0
/swapfile none swap sw 0 0

mysql> SHOW VARIABLES LIKE 'innodb_buffer_pool_size';
+-------------------------+-----------+
| Variable_name | Value |
+-------------------------+-----------+
| innodb_buffer_pool_size | 134217728 |
+-------------------------+-----------+

vi /etc/my.cnf
innodb_buffer_pool_size=2000M

[root@rexius ~]# /etc/rc.d/init.d/mysqld restart

mysql> SHOW VARIABLES LIKE 'innodb_buffer_pool_size';
+-------------------------+------------+
| Variable_name | Value |
+-------------------------+------------+
| innodb_buffer_pool_size | 2097152000 |
+-------------------------+------------+
1 row in set (0.00 sec)

Follow me!