現在很多入門的 VPS 只有 1GB Ram, 如果在 1GB RAM 的 VPS 安裝 Apache, PHP 及 MySQL / MariaDB, 為僻免出現 out of memory 的情況, 可以使用以下方法進行優化。
Apache
建議對 Apache MPM worker 進行設定:
RHEL / CentOS:
開啟 /etc/httpd/conf.conf
# vi /etc/httpd/httpd.conf
最檔案最後加入以下內容:
1 2 3 4 5 6 7 8 9 |
KeepAlive Off <ifmodule prefork.c=""> StartServers 6 MinSpareServers 5 MaxSpareServers 15 ServerLimit 256 MaxClients 256 MaxRequestsPerChild 3000 </ifmodule> |
儲存檔案後,重新啟動 Apache:
# systemctl restart httpd
Ubuntu :
開啟 /etc/apache2/apache2.conf
# vi /etc/apache2/apache2.conf
找到 ifmodule mpm_prefork_module 的段落,改成這樣:
1 2 3 4 5 6 7 8 |
<ifmodule mpm_prefork_module=""> StartServers 3 MinSpareServers 5 MaxSpareServers 15 ServerLimit 256 MaxClients 256 MaxRequestsPerChild 3000 </ifmodule> |
儲存檔案後,重新啟動 Apache:
$ sudo systemctl restart apache2
MySQL / MariaDB
1GB Ram 的 VPS,建議修改 MySQL / MariaDB 的設定,開啟 my.cnf (一般在 /etc/my.cnf 及 /etc/mysql/my.cnf),在 [mysqld] 加入以下內容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
[mysqld] symbolic-links=0 skip-external-locking key_buffer_size = 32K max_allowed_packet = 4M table_open_cache = 8 sort_buffer_size = 128K read_buffer_size = 512K read_rnd_buffer_size = 512K net_buffer_length = 4K thread_stack = 480K innodb_file_per_table max_connections=100 max_user_connections=50 wait_timeout=50 interactive_timeout=50 long_query_time=5 |
PHP
PHP 的優化可以限制使用記憶體上限,開啟 php.ini:
# vi /etc/php.ini
找到 memory_limit,改成 128MB:
memory_limit = 128M
儲存後需要重新啟動 Apache.
另外,也可以用裝 PHP memcached, 可參考本站另一篇文章:RHEL / CentOS 7 安裝 PHP Memcached 緩存