サーバー設定 · 4 min read · Oct 04, 2025

CentOS 7.6にNginxとPHP、MySQL(LEMPスタック)をインストールする方法

このチュートリアルでは、PHPサポート(PHP-FPMを通じて)とMySQL(MariaDB)サポートを持つCentOS 7サーバーにNginxをインストールする方法を示します。

LEMPとは?

Nginx(「エンジンエックス」と発音)は、無料のオープンソースの高性能HTTPサーバーです。Nginxは、その安定性、豊富な機能セット、シンプルな設定、低リソース消費で知られています。

LEMPの前提条件

このチュートリアルでは、ホスト名server1.example.comとIPアドレス192.168.1.100を使用します。これらの設定はあなたの環境によって異なる場合があるため、適宜置き換えてください。

このチュートリアルでは、設定ファイルを編集するためにnanoエディタを使用します。Nanoは次のようにインストールできます。

yum -y install nano

ファイアウォールをインストールすることをお勧めします。まだfirewalldがインストールされていない場合で、ファイアウォールを使用したい場合は、次のコマンドでインストールしてください。

yum -y install firewalld

ファイアウォールを起動し、ブート時に自動的に起動するように設定します。

systemctl start firewalld.service  
systemctl enable firewalld.service

次に、SSHでサーバーに接続できるようにSSHポートを開きます。

firewall-cmd --permanent --zone=public --add-service=ssh  
firewall-cmd --reload

追加のCentOSリポジトリを有効にする

最新のNginxは公式のCentOSリポジトリからは利用できないため、Nginxプロジェクトのリポジトリを追加してインストールします。

nano /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

MySQL(MariaDB)のインストール

まず、MySQLの代替としてMariaDBをインストールします。MariaDBはMySQLの無料のフォークです。シェルで次のコマンドを実行してMariaDBデータベースサーバーをインストールします。

yum -y install mariadb mariadb-server net-tools

次に、MariaDBのシステム起動リンクを作成し(システムが起動するたびに自動的に起動するように)、MariaDBサーバーを起動します。

systemctl enable mariadb.service  
systemctl start mariadb.service

ネットワークが有効になっていることを確認します。MraiDBサービスは互換性のあるデータベースサーバーであるため、mysqlという名前になっています。次のコマンドを実行します。

netstat -tap | grep mysql

次のような出力が表示されるはずです。

[root@server1 ~]# netstat -tap | grep mysql  
tcp 0 0 0.0.0.0:mysql 0.0.0.0:* LISTEN 19842/mysqld  

次のコマンドを実行します。

mysql_secure_installation

rootユーザーのパスワードを設定します(そうしないと、誰でもあなたのMySQLデータベースにアクセスできてしまいます!):

[root@example ~]# mysql_secure_installation  
/usr/bin/mysql_secure_installation: line 379: find_mysql_client: command not found
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB  
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
MariaDBにログインしてセキュリティを確保するには、現在の  
rootユーザーのパスワードが必要です。MariaDBをインストールしたばかりで、  
まだrootパスワードを設定していない場合、パスワードは空白になりますので、  
ここではそのままEnterを押してください。
Enter current password for root (enter for none):  
OK, successfully used password, moving on...
rootパスワードを設定することで、適切な認証なしに誰もMariaDBの  
rootユーザーにログインできないようにします。
Set root password? [Y/n] <-- ENTER  
New password: <-- yourrootsqlpassword  
Re-enter new password: <-- yourrootsqlpassword  
Password updated successfully!  
Reloading privilege tables..  
... Success!
デフォルトでは、MariaDBのインストールには匿名ユーザーが存在し、誰でも  
ユーザーアカウントを作成せずにMariaDBにログインできるようになっています。  
これはテスト用にのみ意図されており、インストールを少しスムーズにするためのものです。  
本番環境に移行する前に、これらを削除する必要があります。
Remove anonymous users? [Y/n] <-- ENTER  
... Success!
通常、rootは「localhost」からのみ接続できるようにすべきです。  
これにより、誰かがネットワークからrootパスワードを推測できないようにします。
Disallow root login remotely? [Y/n] <-- ENTER  
... Success!
デフォルトでは、MariaDBには誰でもアクセスできる「test」という名前のデータベースが付属しています。  
これもテスト用にのみ意図されており、本番環境に移行する前に削除する必要があります。
Remove test database and access to it? [Y/n] <-- ENTER  
- Dropping test database...  
... Success!  
- Removing privileges on test database...  
... Success!
特権テーブルを再読み込みすることで、これまでに行ったすべての変更が  
即座に適用されることを保証します。
Reload privilege tables now? [Y/n] <-- ENTER  
... Success!
クリーンアップ中...
すべて完了しました!上記のすべての手順を完了した場合、あなたのMariaDB  
インストールは今や安全であるはずです。
MariaDBをご利用いただきありがとうございます!  
[root@example ~]#

[root@server1 ~]# mysql_secure_installation

Nginxのインストール

Nginxはnginx.orgからパッケージとして利用可能で、次のようにインストールできます。

yum -y install nginx

次に、nginxのシステム起動リンクを作成し、起動します。

systemctl enable nginx.service  
systemctl start nginx.service

ポート80がすでに使用中であるというエラーが発生する可能性があります。エラーメッセージは次のようになります。

[root@server1 ~]# service nginx start  
Starting nginx: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)  
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)  
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)  
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)  
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)  
nginx: [emerg] still could not bind()  
                                               [FAILED]  
[root@server1 ~]#

これは、別のWebサーバー(おそらくApache)がこのサーバーで既に実行されていることを意味します。Apacheサービスを停止し、その後NGINXサービスを開始します。

systemctl stop httpd.service  
yum remove httpd  
systemctl disable httpd.service

その後、再度Nginxを起動してみてください。

systemctl start nginx.service

HTTPおよびHTTPSポートをファイアウォールで開きます。

firewall-cmd --permanent --zone=public --add-service=http  
firewall-cmd --permanent --zone=public --add-service=https  
firewall-cmd --reload

シェルの出力は次のようになります。

[root@example ~]# firewall-cmd --permanent --zone=public --add-service=http  
success  
[root@example ~]# firewall-cmd --permanent --zone=public --add-service=https  
success  
[root@example ~]# firewall-cmd --reload  
success  
[root@example ~]#

ブラウザにWebサーバーのIPアドレスまたはホスト名を入力します(例:http://192.168.1.100)。Nginxのウェルカムページが表示されるはずです。

Nginxのウェルカムページ

PHPのインストール

PHP 5をNginxでPHP-FPM(FastCGIプロセスマネージャー)を通じて動作させることができます。PHP-FPMは、どのサイズのサイトでも特に忙しいサイトに役立つ追加機能を持つPHPの代替FastCGI実装です。次のように、php-fpm、php-cli、およびMySQLをPHPスクリプトから使用するために必要なphp-mysqlなどのいくつかのPHP5モジュールを一緒にインストールできます。

yum -y install php-fpm php-cli php-mysql php-gd php-ldap php-odbc php-pdo php-pecl-memcache php-pear php-mbstring php-xml php-xmlrpc php-mbstring php-snmp php-soap

APCは、PHP中間コードをキャッシュおよび最適化するための無料のオープンPHPオペコードキャッシャーです。他のPHPオペコードキャッシャー(eAcceleratorやXcacheなど)と似ています。PHPページの速度を上げるために、これらのいずれかをインストールすることを強くお勧めします。

私はPHP peclリポジトリからAPCをインストールします。PECLはAPCパッケージをコンパイルするためにCentos開発ツールがインストールされている必要があります。

yum -y install php-devel  
yum -y groupinstall 'Development Tools'

そしてAPCをインストールします。

pecl install apc
[root@example ~]# pecl install apc  
downloading APC-3.1.13.tgz ...  
Starting to download APC-3.1.13.tgz (171,591 bytes)  
.................done: 171,591 bytes  
55 source files, building  
running: phpize  
Configuring for:  
PHP Api Version: 20100412  
Zend Module Api No: 20100525  
Zend Extension Api No: 220100525  
Enable internal debugging in APC [no] : <-- ENTER  
Enable per request file info about files used from the APC cache [no] : <-- ENTER  
Enable spin locks (EXPERIMENTAL) [no] : <-- ENTER  
Enable memory protection (EXPERIMENTAL) [no] : <-- ENTER  
Enable pthread mutexes (default) [no] : <-- ENTER  
Enable pthread read/write locks (EXPERIMENTAL) [yes] : <-- ENTER  
building in /var/tmp/pear-build-rootVrjsuq/APC-3.1.13  
......

次に、/etc/php.iniを開いてcgi.fix_pathinfo=0を設定します。

nano /etc/php.ini
[...]
; cgi.fix_pathinfoはCGIのための*実際の* PATH_INFO/PATH_TRANSLATEDサポートを提供します。PHPの
; 以前の動作は、PATH_TRANSLATEDをSCRIPT_FILENAMEに設定し、PATH_INFOが何であるかを理解しませんでした。PATH_INFOについての詳細は、cgi仕様を参照してください。これを1に設定すると、PHP CGIはそのパスを仕様に従って修正します。0に設定すると、PHPは以前のように動作します。デフォルトは1です。SCRIPT_FILENAMEを使用するようにスクリプトを修正する必要があります。
; http://www.php.net/manual/en/ini.core.php#ini.cgi.fix-pathinfo
cgi.fix_pathinfo=0
[...]

(なぜこれを行うべきかについては、http://wiki.nginx.org/Pitfallsをお読みください。)

そして、次の行を追加します。

[...]
extension=apc.so

/etc/php.iniファイルの最後に追加します。

さらに、次のようなタイムゾーンエラーを回避するために、

[28-June-2016 14:21:01] PHP Warning: phpinfo(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead in /usr/share/nginx/html/info.php on line 2

… /var/log/php-fpm/www-error.logでPHPスクリプトをブラウザで呼び出すときに、/etc/php.iniでdate.timezoneを設定する必要があります。

[...]
[Date]
; 日付関数で使用されるデフォルトのタイムゾーンを定義します
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = "Europe/Berlin"
[...]

システムの正しいタイムゾーンは、次のコマンドを実行することで確認できます。

cat /etc/sysconfig/clock

[root@server1 nginx]# cat /etc/sysconfig/clock
ZONE=”Europe/Berlin”
[root@server1 nginx]#

次に、php-fpmのシステム起動リンクを作成し、起動します。

systemctl enable php-fpm.service  
systemctl start php-fpm.service

PHP-FPMは、ポート9000でFastCGIサーバーを実行するデーモンプロセスです。

Nginxの設定

nginxの設定は/etc/nginx/nginx.confにあり、今開きます。

nano /etc/nginx/nginx.conf

最初に(これはオプションです)、ワーカープロセスの数を増やし、keepalive_timeoutを適切な値に設定できます。

[...]
worker_processes  4;
[...]
    keepalive_timeout  2;
[...]

仮想ホストは/etc/nginx/conf.dディレクトリ内のserver {}コンテナで定義されています。デフォルトのvhost(/etc/nginx/conf.d/default.conf)を次のように変更しましょう。

nano /etc/nginx/conf.d/default.conf
[...]
server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm index.php;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #

    location ~ \.php$ {
        root           /usr/share/nginx/html;
        try_files $uri =404;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
    
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny  all;
    }
}

servername ;はこれをデフォルトのキャッチオールvhostにします(もちろん、ここにwww.example.comのようなホスト名を指定することもできます)。

location /の部分では、index.phpをインデックス行に追加しました。root /usr/share/nginx/html;は、ドキュメントルートが/usr/share/nginx/htmlディレクトリであることを意味します。

PHPにとって重要な部分は、location ~ .php$ {}のスタンザです。これを有効にするためにコメントを外してください。root行をWebサイトのドキュメントルート(例:root /usr/share/nginx/html;)に変更してください。try_files $uri =404;の行を追加して、ゼロデイ攻撃を防ぐようにしてください(http://wiki.nginx.org/Pitfalls#Passing_Uncontrolled_Requests_to_PHPおよびhttp://forum.nginx.org/read.php?2,88845,page=3を参照してください)。fastcgi_param行をfastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;に変更してください。そうしないと、PHPインタープリターはブラウザで呼び出すPHPスクリプトを見つけることができません($document_rootは/usr/share/nginx/htmlに変換されます。これは私たちがドキュメントルートとして設定したものです)。

デフォルトでは、PHP-FPMは127.0.0.1のポート9000でリッスンしているため、Nginxに127.0.0.1:9000に接続するように指示します。fastcgi_pass 127.0.0.1:9000;の行です。また、PHP-FPMをUnixソケットを使用するように設定することも可能です。これについては第7章で説明します。

ファイルを保存してNginxを再読み込みします。

systemctl restart nginx.service

次に、ドキュメントルート/usr/share/nginx/htmlに次のPHPファイルを作成します…

nano /usr/share/nginx/html/info.php

次に、ブラウザでそのファイルを呼び出します(例:http://192.168.1.100/info.php):

私たちのnginxサーバーからのPHP情報

ご覧の通り、PHP 5が動作しており、Server API行に示されているようにFPM/FastCGIを通じて動作しています。さらに下にスクロールすると、MySQLモジュールを含むPHP5で既に有効になっているすべてのモジュールが表示されます。

PHPでMySQLドライバーが有効になっています。

PHP-FPMをUnixソケットで使用するように設定する

デフォルトでは、PHP-FPMは127.0.0.1のポート9000でリッスンしています。また、TCPオーバーヘッドを回避するために、PHP-FPMをUnixソケットで使用することも可能です。これを行うには、/etc/php-fpm.d/www.confを開きます…

nano /etc/php-fpm.d/www.conf

…そしてlisten行を次のように変更します。

[...]
;listen = 127.0.0.1:9000
listen = /var/run/php-fpm/php5-fpm.sock
[...]

次に、PHP-FPMを再読み込みします。

systemctl restart php-fpm.service

次に、Nginxの設定とすべてのvhostを確認し、fastcgi_pass 127.0.0.1:9000;の行をfastcgi_pass unix:/tmp/php5-fpm.sock;に変更します。例えば、次のようにします。

vi /etc/nginx/conf.d/default.conf
[...]
    location ~ \.php$ {
        root           /usr/share/nginx/html;
        try_files $uri =404;
        fastcgi_pass   unix:/var/run/php-fpm/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
[...]

最後に、Nginxを再読み込みします。

systemctl restart nginx.service

このCentOS 7サーバーを仮想マシンとしてダウンロードする

このセットアップは、howtoforgeのサブスクライバー向けにova/ovf形式の仮想マシンダウンロードとして利用可能です。

VMのログイン詳細

  • rootパスワードは:howtoforge
  • 「administrator」ユーザーのパスワードは:howtoforge

最初のログイン時に両方のパスワードを変更してください。

  • VMのIPアドレスは192.168.1.100です。

リンク

Share: X/Twitter LinkedIn

新しい投稿を受信箱で受け取る

スパムはありません。いつでも購読を解除できます。