Nginxのパフォーマンスを手軽にアップできるPHPキャッシュ OPcacheとAPCuをインストール

nginx-php-cache-img

Photo by Domenico Loia on Unsplash

こんにちは、ITエンジニアの小村(@system_kom)です。

前回の記事ではNginx環境へWordPressを導入するための手順と注意点を紹介しました。
今回はNginx環境を利用してPHPを高速化するためのキャッシュ機能を提供するパッケージである「OPcache」「APCu」を導入する手順を紹介していきます。WordPressやPHPを利用しているサイトの高速化に是非、試して頂きたい設定です。

参考 Nginx環境へWordPressをインストールする手順と注意点を紹介した記事

OPcacheAPCuはPHPアクセラレータと呼ばれるPHPを高速化させるためのソフトウェアです。

OPcacheはコンパイルしたPHPのコードをメモリに保存しておく仕組みで、アクセス毎のスクリプト読み込みを回避します。APCuも同じくキャッシュを行うソフトウェアになり、こちらはコードではなくデータをキャッシュ(共有メモリにデータを保存する)します。

まとめると

  • OPcache ... コンパイルしたコードをキャッシュ
  • APCu ... データのキャッシュ

という機能を提供します。

ApacheとPHPを組み合わせたウェブサーバーにOPcacheとAPCuをインストールした環境では、大幅なパフォーマンス向上が確認できたことから、Nginx環境でも大幅なパフォーマンス向上が期待できます。

参考 Apache+PHPの環境にOPcacheとAPCuを導入した記事

Open Source
opcache-apcu-inst-top2
CentOS Apache環境にOPCacheとAPCuでWordPressの速度を5倍にする

今回は前回の記事で作成したphp-fpmが動作する環境を利用して、更にWordPressを高速化するためのphp用パッケージであるOPcacheとAPCuを導入します。 OPcacheとAPCuはPHPアクセラレータと呼ばれるphpを高速化 ...

1. OPcacheとAPCuを導入する環境

OPcacheとAPCuをインストールする環境はNginx環境へWordPressの導入手順を紹介した記事で紹介しています。

参考 Nginx環境へWordPressをインストールする手順と注意点を紹介した記事

本記事でも確認の意味で再度まとめておきます。基本的な環境は以下の通りです。

OSのバージョン CentOS 7.5.1804. 2016年7月時の最新
ウェブサーバー nginx 1.15.0 2018年7月時の最新
バーチャルホスト www.testdom.com / www.testdom2.com
WordPress インストール済み
PHP PHP/php-fpm 7.2系インストール
SSL Let's EncryptによるHTTPS有効
IPアドレス グローバルIPアドレスを割り当て
Firewall firewalldでHTTP/HTTPSを許可済み

この環境を前提にOPcacheとAPCuのインストールを進めていきます。
インストールするOPcacheとAPCuは以前の記事で導入したphpと同様に7.2系を利用します。(2018年6月時点では7.2.6)

参考 Nginx環境へPHPをインストールする手順と注意点を紹介した記事

2. OPcacheインストール前のPHP情報を確認

パッケージをインストールする前に現状のPHPについて情報を確認します。
OPcacheをインストールすると、PHPの情報を表示するためのコマンド"php -v"の項目「Zend Engine」の部分が変更されます。

まずはインストールを行う前に出力内容を確認しておきます。

 command
$ php -v
PHP 7.2.6 (cli) (built: May 23 2018 09:50:51) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

上記のようにバージョンが表示されれば、PHPの情報確認は完了です。
この時点ではOPcacheに関する情報は表示されていないことを覚えておきます。

3. OPcacheとAPCuパッケージのインストール

インストールするパッケージの情報が確認できましたので、ここからは実際にOPcacheとAPCuの導入について説明を行います。

3-1. OPcacheとAPCuパッケージ情報の確認

OPcacheとAPCuパッケージのインストール前に、パッケージの情報を確認しておきます。
php7.2系のOPcacheとAPCuはremiレポジトリに含まれるため、確認コマンドの実行時にremiレポジトリを参照するように指定します。パッケージ名は

  • OPcache ... php-opcache
  • APCu ... php-pecl-apcu

になります。以下のようにyumを実行します。

 command
$ yum info --enablerepo=remi,remi-php72 php-opcache php-pecl-apcu

実行結果は以下の通りです。
各パッケージの役割などを確認しておくと、インストールするパッケージの意味合いをイメージしやすいと思います。

 log
読み込んだプラグイン:fastestmirror
Loading mirror speeds from cached hostfile
* base: ftp.jaist.ac.jp
* epel: mirror.dmmlabs.jp
* extras: ftp.jaist.ac.jp
* remi: mirror.bebout.net
* remi-php72: mirror.bebout.net
* remi-safe: mirror.bebout.net
* updates: ftp.jaist.ac.jp
利用可能なパッケージ
名前 : php-opcache
アーキテクチャー : x86_64
バージョン : 7.2.6
リリース : 1.el7.remi
容量 : 279 k
リポジトリー : remi-php72
要約 : The Zend OPcache
URL : http://www.php.net/
ライセンス : PHP
説明 : The Zend OPcache provides faster PHP execution through opcode caching and
: optimization. It improves PHP performance by storing precompiled script
: bytecode in the shared memory. This eliminates the stages of reading code from
: the disk and compiling it on future access. In addition, it applies a few
: bytecode optimization patterns that make code execution faster.
 
名前 : php-pecl-apcu
アーキテクチャー : x86_64
バージョン : 5.1.11
リリース : 1.el7.remi.7.2
容量 : 75 k
リポジトリー : remi-php72
要約 : APC User Cache
URL : http://pecl.php.net/package/APCu
ライセンス : PHP
説明 : APCu is userland caching: APC stripped of opcode caching.
:
: APCu only supports userland caching of variables.
:
: The php-pecl-apcu-bc package provides a drop
: in replacement for APC.
:
: Package built for PHP 7.2.

上記のように7.2系のOPcacheとAPCuが表示されることが確認できました。この2パッケージをインストールのターゲットとします。

3-2. OPcacheとAPCuパッケージのインストール

パッケージは"yum"コマンドにinstallオプションを付けることでインストールすることができます。
項目3-1. で必要なパッケージの情報が確認できましたので、以下のコマンドでインストールします。

 command
# yum -y install --enablerepo=remi,remi-php72 php-opcache php-pecl-apcu

上記ではyumコマンドに"-y"オプションを付けることでインストール時の確認応答を省いています。
コマンドを実行すると、以下のようにインストールが開始されます。

 log
読み込んだプラグイン:fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.cat.net
* epel: mirror.dmmlabs.jp
* extras: mirrors.cat.net
* remi: mirror.bebout.net
* remi-php72: mirror.bebout.net
* remi-safe: mirror.bebout.net
* updates: mirrors.cat.net
依存性の解決をしています
--> トランザクションの確認を実行しています。
---> パッケージ php-opcache.x86_64 0:7.2.6-1.el7.remi を インストール
---> パッケージ php-pecl-apcu.x86_64 0:5.1.11-1.el7.remi.7.2 を インストール
--> 依存性解決を終了しました。
 
依存性を解決しました
 
インストール中:
php-opcache x86_64 7.2.6-1.el7.remi remi-php72 279 k
php-pecl-apcu x86_64 5.1.11-1.el7.remi.7.2 remi-php72 75 k
 
トランザクションの要約
インストール 2 パッケージ
 
総ダウンロード容量: 355 k
インストール容量: 1.1 M
Downloading packages:
(1/2): php-pecl-apcu-5.1.11-1.el7.remi.7.2.x86_64.rpm | 75 kB 00:00:01
(2/2): php-opcache-7.2.6-1.el7.remi.x86_64.rpm | 279 kB 00:00:02
合計 168 kB/s | 355 kB 00:00:02
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
インストール中 : php-pecl-apcu-5.1.11-1.el7.remi.7.2.x86_64 1/2
インストール中 : php-opcache-7.2.6-1.el7.remi.x86_64 2/2
検証中 : php-opcache-7.2.6-1.el7.remi.x86_64 1/2
検証中 : php-pecl-apcu-5.1.11-1.el7.remi.7.2.x86_64 2/2
 
インストール:
php-opcache.x86_64 0:7.2.6-1.el7.remi php-pecl-apcu.x86_64 0:5.1.11-1.el7.remi.7.2
 
完了しました!

エラーがなく「完了しました!」と表示されればOPcacheとAPCuパッケージのインストールは完了です。

3-3. インストールしたパッケージの確認

OPcacheがインストールされたことを確認します。
インストールされているパッケージはyumコマンドで確認できます。以下のように"yum"コマンドを実行することで、OPcacheパッケージがインストールされていることを確認します。

 command
$ yum list installed | grep php-opcache
php-opcache.x86_64 7.2.6-1.el7.remi @remi-php72

出力結果にOPcacheパッケージが表示されることを確認します。
次にAPCuパッケージがインストールされたことを確認します。同じくyumで確認を行います。

 command
$ yum list installed | grep php-pecl-apcu
php-pecl-apcu.x86_64 5.1.11-1.el7.remi.7.2 @remi-php72

出力結果に、APCuパッケージが表示されることを確認します。
これでインストールしたパッケージの確認は完了です。

4. phpコマンドによるOPcacheとAPCuの確認

パッケージのインストールと確認まで完了しましたので、ここからは"php"コマンド利用してOPCacheとAPCuが有効になっていることを確認します。

4-1. OPcacheの確認

OPcacheが動作しているかの確認は"php"コマンドに"-v"オプションを付けて実行します。以下のような結果になります。

 command
$ php -v
PHP 7.2.6 (cli) (built: May 23 2018 09:50:51) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.6, Copyright (c) 1999-2018, by Zend Technologies

項目2. では Zend Engineと表示されていた部分が”Zend OPcache”に変更されていることが確認できます。

4-2. APCuとOPcacheの設定確認

続いて、APCuとOPcacheの設定を確認します。phpコマンドに”-i”を付与して実行します。
"-i"を付与することでphpの情報を出力することができます。ここでは設定確認として、出力された情報に含まれる文字列「apc」と「opcache」のみを抽出します。

以下のように実行します。

 command
$ php -i | egrep 'apc|opcache'
Additional .ini files parsed => /etc/php.d/10-opcache.ini,
/etc/php.d/40-apcu.ini,
apcu
MMAP File Mask => /tmp/apc.XXXXXX
apc.coredump_unmap => Off => Off
apc.enable_cli => Off => Off
apc.enabled => On => On
apc.entries_hint => 4096 => 4096
apc.gc_ttl => 3600 => 3600
apc.mmap_file_mask => /tmp/apc.XXXXXX => /tmp/apc.XXXXXX
apc.preload_path => no value => no value
apc.serializer => php => php
apc.shm_segments => 1 => 1
apc.shm_size => 32M => 32M
apc.slam_defense => On => On
apc.smart => 0 => 0
apc.ttl => 0 => 0
apc.use_request_time => On => On
apc.writable => /tmp => /tmp
opcache.blacklist_filename => /etc/php.d/opcache*.blacklist => /etc/php.d/opcache*.blacklist
opcache.consistency_checks => 0 => 0
opcache.dups_fix => Off => Off
opcache.enable => On => On
opcache.enable_cli => Off => Off
opcache.enable_file_override => Off => Off
opcache.error_log => no value => no value
opcache.file_cache => no value => no value
opcache.file_cache_consistency_checks => 1 => 1
opcache.file_cache_only => 0 => 0
opcache.file_update_protection => 2 => 2
opcache.force_restart_timeout => 180 => 180
opcache.huge_code_pages => On => On
opcache.inherited_hack => On => On
opcache.interned_strings_buffer => 8 => 8
opcache.lockfile_path => /tmp => /tmp
opcache.log_verbosity_level => 1 => 1
opcache.max_accelerated_files => 4000 => 4000
opcache.max_file_size => 0 => 0
opcache.max_wasted_percentage => 5 => 5
opcache.memory_consumption => 128 => 128
opcache.opt_debug_level => 0 => 0
opcache.optimization_level => 0x7FFFBFFF => 0x7FFFBFFF
opcache.preferred_memory_model => no value => no value
opcache.protect_memory => 0 => 0
opcache.restrict_api => no value => no value
opcache.revalidate_freq => 2 => 2
opcache.revalidate_path => Off => Off
opcache.save_comments => 1 => 1
opcache.use_cwd => On => On
opcache.validate_permission => Off => Off
opcache.validate_root => Off => Off
opcache.validate_timestamps => On => On

上記からphpにOPcacheとAPCuが組み込まれていることが確認できました。
本パラメータは運用環境に合わせて変更することで、よりパフォーマンスを引き出すことが出来ますが、デフォルトでも十分にパフォーマンスは向上しますので、変更は行わない前提です。

これでphpコマンドによるOPcacheとAPCuの確認は完了です。

5. OPcacheとAPCuの有効化

項目4. までの設定でOPcacheとAPCuの導入が完了しましたので、本章では導入したキャッシュ機能を有効にする手順を説明します。

5-1. php-fpmの再起動

OPcacheとAPCuのキャッシュ機能を有効にするためにphp-fpmを再起動します。"systemctl"コマンドを以下のように実行します。

 command
# systemctl restart php-fpm

再起動後にphp-fpmのステータスを確認します。

 command
$ systemctl status php-fpm
● php-fpm.service - The PHP FastCGI Process Manager
Loaded: loaded (/usr/lib/systemd/system/php-fpm.service; enabled; vendor preset: disabled)
Active: active (running) since 火 2018-06-12 11:21:36 JST; 5s ago
Main PID: 10383 (php-fpm)
Status: "Ready to handle connections"
CGroup: /system.slice/php-fpm.service
tq10383 php-fpm: master process (/etc/php-fpm.conf)
tq10384 php-fpm: pool www
tq10385 php-fpm: pool www
tq10386 php-fpm: pool www
tq10387 php-fpm: pool www
tq10388 php-fpm: pool www
tq10389 php-fpm: pool www
tq10390 php-fpm: pool www
tq10391 php-fpm: pool www
tq10392 php-fpm: pool www
mq10393 php-fpm: pool www
 
6月 12 11:21:35 www systemd[1]: Starting The PHP FastCGI Process Manager...
6月 12 11:21:36 www systemd[1]: Started The PHP FastCGI Process Manager.

php-fpmが正常に再起動していることが上記から確認できます。

5-2. nginxの再起動

php-fpmと合わせて、念のためにNginxも再起動を行います。

 command
# systemctl restart nginx

エラーが出力なければ、Nginxは正常に再起動しています。念のためステータスを確認します。

 command
$ systemctl status nginx
● nginx.service - nginx - high performance web server
   Loaded: loaded (/etc/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since 金 2020-04-24 03:07:44 JST; 3 weeks 1 days ago
     Docs: http://nginx.org/en/docs/
  Process: 5667 ExecStop=/bin/kill -s TERM $MAINPID (code=exited, status=0/SUCCESS)
  Process: 5670 ExecStart=/usr/local/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 5671 (nginx)
   CGroup: /system.slice/nginx.service
           tq5671 nginx: master process /usr/local/sbin/nginx -c /etc/nginx/nginx.conf
           tq5672 nginx: worker process
           mq5673 nginx: cache manager process
Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.

上記の結果からnginxは正常に再起動していることが確認できました。これでOPcacheとAPCuの有効化は完了です。

6. パフォーマンスの比較

ここまででOPcacheとAPCuの導入と機能の有効化が完了しました。
キャッシュ機能を有効にすることでどの程度、パフォーマンスが向上したかをApacheに付属しているApache Benchコマンドの"ab"(Apache Bench)で測定してみます。

"ab"コマンドはApacheを導入すると同時にインストールされます。ここでは環境として別のサーバーからOPcacheとAPCu(+ php-fpm)を導入したサーバーを測定するようにしています。

6-1. Nginx OPcacheとAPCu導入前のテスト

まずはOPcacheとAPCuが有効ではない状態でのテストを行います。

abコマンドにはオプションとして"-n"と"-c"を指定します。
"-n"オプションはリクエスト総数を指定します。"-c"は同時接続数になります。本記事では100リクエストを同時接続10ユーザーを前提としてテストを実行します。

結果は以下のようになりました。

OPcache APCu 導入前のabテスト

 command
$ ab -n 100 -c 10 https://www.testdom.com/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
 
Benchmarking www.testdom.com (be patient).....done
 
Server Software: nginx
Server Hostname: www.testdom.com
Server Port: 443
SSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256
 
Document Path: /
Document Length: 15156 bytes
 
Concurrency Level: 10
Time taken for tests: 19.797 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Total transferred: 1535600 bytes
HTML transferred: 1515600 bytes
Requests per second: 5.05 [#/sec] (mean)
Time per request: 1979.657 [ms] (mean)
Time per request: 197.966 [ms] (mean, across all concurrent requests)
Transfer rate: 75.75 [Kbytes/sec] received
 
Connection Times (ms)
min mean[+/-sd] median max
Connect: 4 26 39.9 15 264
Processing: 211 1906 505.6 1836 5244
Waiting: 209 1906 505.7 1836 5244
Total: 226 1933 518.7 1843 5295
 
Percentage of the requests served within a certain time (ms)
50% 1843
66% 2027
75% 2133
80% 2154
90% 2318
95% 2715
98% 3088
99% 5295
100% 5295 (longest request)

本テストでは以下の項目に注目しました。

  • Time taken for tests: 19.797 seconds
  • Requests per second: 5.05 [#/sec] (mean)

「Time taken for tests」はテストの所要時間、「Requests per second」は秒間でどれだけのリクエストを処理できたかを示す項目になります。上記からキャッシュを利用しない環境では、テストの所要時間は約19.8秒で、1秒間に処理できたリクエストは約5になります。

6-2. Nginx OPcacheとAPCu導入後のテスト

続いて同じ条件でOPcacheとAPCu導入後の環境についてテストを行います。今回のテストではキャッシュが利用されますので導入前よりパフォーマンスが出ることが期待できます。結果は以下のようになりました。

OPcache APCu 導入後のabテスト

 command
$ ab -n 100 -c 10 https://www.testdom.com/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
 
Benchmarking www.testdom.com (be patient).....done
 
Server Software: nginx
Server Hostname: www.testdom.com
Server Port: 443
SSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256
 
Document Path: /
Document Length: 15156 bytes
 
Concurrency Level: 10
Time taken for tests: 4.210 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Total transferred: 1535600 bytes
HTML transferred: 1515600 bytes
Requests per second: 23.75 [#/sec] (mean)
Time per request: 421.040 [ms] (mean)
Time per request: 42.104 [ms] (mean, across all concurrent requests)
Transfer rate: 356.17 [Kbytes/sec] received
 
Connection Times (ms)
min mean[+/-sd] median max
Connect: 4 55 64.0 33 357
Processing: 49 353 146.3 357 1283
Waiting: 47 352 145.9 357 1277
Total: 55 407 159.2 401 1291
 
Percentage of the requests served within a certain time (ms)
50% 401
66% 434
75% 443
80% 471
90% 585
95% 677
98% 773
99% 1291
100% 1291 (longest request)

本テストでは以下の項目に注目しました。

  • Time taken for tests: 4.210 seconds
  • Requests per second: 23.75 [#/sec] (mean)

「Time taken for tests」はテストの所要時間、「Requests per second」は秒間でどれだけのリクエストを処理できたかを示す項目になります。キャッシュを有効した環境では、テストの所要時間は約4.2秒で、1秒間に処理できたリクエストは約24になります。

上記のテスト環境ではキャッシュが有効になっているため、php-fpmのみの場合と比較してテストの所要時間で約5倍、リクエスト数は約4倍と大きなパフォーマンス向上が確認できました。

このことからOPcacheとAPCuについては、Nginx環境でもウェブサーバーの速度向上に大きな効果があると思われます。

7. まとめ

Nginx環境でのWordPressのパフォーマンスを向上するために、PHPアクセラレータの導入を紹介しました。

速度と処理できるリクエスト数は大きく向上しましたが、思ったほど向上しないと感じた人も多いと思います。実はNginxにはさらに強力なキャッシュ機能が用意されています。
FastCGIキャッシュやプロキシキャッシュなどウェブサーバーの処理速度を大きく向上できる強力な機能です。
OPcacheとAPCuと同時の利用もできますので、まずは本記事で紹介したPHPアクセラレータを導入してみて下さい。これだけでも体感でわかる程に、パフォーマンスが向上します。

次の記事では、そのNginxの強力なキャッシュ機能の1つ「FastCGIキャッシュ」の導入と設定について紹介していきます。お楽しみにして下さい。

  • この記事を書いた人
rem-profile-photo

レムシステム

レムシステムはPC・サーバー・ネットワークでの業務効率化を主な業務としている会社です。全国に対応しています。

-CentOS, Nginx, PHP