初めに
はじめまして。Qiita初投稿なのでお手柔らかにお願いしますね
本記事はCentOS 7に最新パッケージを入れWeb環境を構築する手順です。
主に以下のような方を対象としています
- NginxやMariaDBで構築してみたいが入れ方や設定がわからない
- 初期やそのまま入るパッケージは古いので最新のものを入れたい
- 低スペックでもそれなりに動くWordPress用サーバが欲しい
※注意点
本記事は初心者向けです。そのため設定は基本的なものです
細かなチューニングや高度なセキュリティ設定を望む方はバックしましょう
前提
本記事では以下が前提となります
- CentOS 7が入ったサーバを用意できている
- sudoが利用できるユーザが存在する
- 初期で入っているMariaDBを削除しても構わない
構築する環境
今回構築する環境は以下です。ビルドではなくリポジトリから入れます
管理が楽なのに越したことはないですからね
パッケージ | リポジトリ | |
---|---|---|
PHP | PHP 7.1 + PHP-FPM | remi-php71 |
Web | Nginx Mainline | nginx.org |
DB | MariaDB Stable | mariadb.org |
確認に使用した環境
確認にはさくらインターネットさんのVPS 2Gプランを使用しました
コンパネも扱いやすいため、初めてのVPSにもおすすめですよ
さくらのVPS 2G | |
---|---|
料金 | 月額 1,706円 + 初期費用 2,160円 |
CPU | 仮想3コア(Intel Xeon E5-2650 v2) |
メモリ | 2GB |
SSD | 50GB |
OS | CentOS 7.4(1708)Minimal |
- さくらのVPS:https://vps.sakura.ad.jp/
- CentOS ISO:https://centos.org/download/
Nginx
最近注目されているWebサーバです。Apacheに似ているためよく比較されますね
Apacheが機能豊富なのに対し、Nginxは軽量で高速です。
それぞれの良さがあるので用途で使い分けると良いでしょう
Nginxの追加
そのまま入るNginxは古かったりするので、repoを作成して入れましょう
NginxはMainlineが安定しており公式でも推奨されているため、こちらを入れます
☆nginx.repoの作成
$ sudo vim /etc/yum.repos.d/nginx.repo
+ [nginx]
+ name=nginx repo
+ baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/
+ enabled=0
+ gpgcheck=0
☆nginxの追加
$ sudo yum -y --enablerepo=nginx install nginx
☆バージョン確認
$ nginx -v
nginx version: nginx/1.13.7
Nginxの設定
Nginxの設定はnginx.confとdefault.conf内の.confファイルによって決まります。
今回は基本的なセキュリティ設定とgzipの有効化をしておきましょう
NginxではProxyも便利なのですが、説明が長くなるため今回は使用しません。
興味がある方は、少し詳しく調べると良いかもしれませんね
☆/etc/nginx/nginx.confのバックアップ
$ sudo mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.org
☆/etc/nginx/nginx.confの作成
$ sudo vim /etc/nginx/nginx.conf
+ user nginx;
+ worker_processes auto;
+ worker_cpu_affinity auto;
+ worker_rlimit_nofile 4096;
+ error_log /var/log/nginx/error.log warn;
+ pid /var/run/nginx.pid;
+
+ events {
+ worker_connections 1024;
+ }
+
+ http {
+ include /etc/nginx/mime.types;
+ default_type application/octet-stream;
+ index index.html index.php;
+ server_tokens off;
+ access_log off;
+ charset UTF-8;
+
+ add_header X-Content-Type-Options nosniff;
+ add_header X-XSS-Protection "1; mode=block";
+
+ sendfile on;
+ tcp_nopush on;
+ keepalive_timeout 60;
+
+ gzip on;
+ gzip_disable "msie6";
+ gzip_min_length 1024;
+ gzip_types text/css
+ image/gif
+ image/png
+ image/jpeg
+ application/javascript;
+
+ server {
+ listen 80 default_server;
+ return 444;
+ log_not_found off;
+ }
+
+ include /etc/nginx/conf.d/*.conf;
+ }
default.confの設定
nginx.confで大まかな設定をしたところで、外部confで細かな設定をしましょう。
例として「example.com」で「/usr/share/nginx/html/example」内を公開する設定です
※default.confの注意
3行目「example.com」は使用するドメインにしましょう
4行目「/usr/share/nginx/html/example」は以下で作成するディレクトリにしましょう
複数ドメイン使用の場合は、設定とディレクトリをドメインごとに作りましょう
☆ドメインで公開するディレクトリの作成
☆exampleは好きなディレクトリ名にしてください、使用するドメイン名などがおすすめです
☆以降出てくる「/usr/share/nginx/html/example」は以下で作成したディレクトリに変えてください
$ sudo mkdir /usr/share/nginx/html/example
☆公開するディレクトリに確認用のindex.htmlをコピー
☆ディレクトリは先程のものに変更してくださいね
$ sudo cp /usr/share/nginx/html/index.html /usr/share/nginx/html/example/index.html
☆/etc/nginx/conf.d/default.confのバックアップ
$ sudo mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.org
☆/etc/nginx/conf.d/default.confの作成
$ sudo vim /etc/nginx/conf.d/default.conf
+ server {
+ listen 80;
+ server_name example.com; #使用するドメイン
+ root /usr/share/nginx/html/example; #ドメインで公開するWebディレクトリ
+ index index.html index.php;
+
+ location ~ \.php$ {
+ try_files $uri $uri/ =404;
+ fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
+ fastcgi_index index.php;
+ fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
+ include fastcgi_params;
+ }
+ }
Webディレクトリの所有者変更
作業ユーザでWebディレクトリ内を編集できるように所有者を変更しましょう
※ユーザ名はFTP接続などの作業に使用する、ユーザにしましょう
☆/usr/share/nginxの所有者変更
$ sudo chown -R ユーザ名:ユーザ名 /usr/share/nginx
起動とfirewalldの設定
サーバを起動した際の自動起動の設定と起動をしましょう。
また、起動してもそのままではfirewalldにブロックされるのでhttpを許可します
☆自動起動の設定と起動
$ sudo systemctl enable nginx && sudo systemctl start nginx
☆firewalldでhttpの許可
$ sudo firewall-cmd --add-service=http --zone=public --permanent
☆firewalldのリロード
$ sudo firewall-cmd --reload
ブラウザから確認
ブラウザでドメインを開き「Welcome to nginx!」と表示されれば完了です
表示されているのはWebディレクトリ内のindex.htmlです
PHP
パッケージはRemiリポジトリから最新安定版のPHP 7.1を入れます
現在RCですが7.2も入れられます、yumの際「remi-php72」としましょう
EPELとRemiリポジトリの追加
PHPを入れるために、前提となるEPELとRemiを入れましょう
関係ないパッケージに影響が出ないように、EPELはデフォルトで無効にします
☆EPELリポジトリの追加と更新
$ sudo yum -y install epel-release && sudo yum -y upgrade epel-release
☆Rimeリポジトリの追加
$ sudo rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
☆EPELリポジトリをデフォルトで無効(EPELを使用する際は--enablerepo=epelを付けましょう
$ sudo vim /etc/yum.repos.d/epel.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
- enabled=1
+ enabled=0
PHPとモジュールの追加
RimeリポジトリからPHPと必要なモジュールを入れましょう
今回入れるモジュールは以下です。必要に応じて変更してくださいね
キャッシュ更新が面倒で今回は入れませんがAPCuとOPcacheもおすすめですよ
- php-mbstring:日本語などのマルチバイト文字を扱うために必要
- php-fpm:PHPをFastCGIから動かすために必要
- php-pdo:MariaDBをPDOから操作するために必要
- php-mysqlnd:MariaDBをPHPから操作するために必要
☆PHPとモジュールの追加
☆7.2を入れたい方は「remi-php71」の部分を「remi-php72」としてくださいね
$ sudo yum -y --enablerepo=remi-php71 install php php-mbstring php-fpm php-pdo php-mysqlnd
☆バージョン確認
$ php -v
PHP 7.1.12 (cli) (built: Nov 28 2017 19:02:01) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
PHPの設定
そのままでも問題ありませんが、少しだけ弄ります
☆セッションディレクトリの所有者をNginxに変更
$ sudo chown nginx:nginx /var/lib/php/session
☆php.iniのバックアップ
$ sudo cp /etc/php.ini /etc/php.ini.org
☆php.iniの編集
$ sudo vim /etc/php.ini
; 374行目くらい
- expose_php = On
+ expose_php = Off
; 902行目くらい
- ;date.timezone =
+ date.timezone = Asia/Tokyo
; 1384行目くらい
- session.sid_length = 26
+ session.sid_length = 32
; 1513行目くらい
- ;mbstring.language = Japanese
+ mbstring.language = Japanese
PHP-FPMの設定
NginxからFastCGIでPHPを動かすのに必要なのでPHP-FPMの設定をしましょう。
設定はNginxに合わせるのと、通信を高速なUNIXドメインソケットに変えます
☆www.confのバックアップ
$ sudo cp /etc/php-fpm.d/www.conf /etc/php-fpm.d/www.conf.org
☆www.confの編集
$ sudo vim /etc/php-fpm.d/www.conf
; 24行目くらい
- user = apache
+ user = nginx
; 26行目くらい
- group = apache
+ group = nginx
; 38行目くらい
- listen = 127.0.0.1:9000
+ listen = /var/run/php-fpm/php-fpm.sock
; 48,49行目くらい
- ;listen.owner = nobody
- ;listen.group = nobody
+ listen.owner = nginx
+ listen.group = nginx
☆PHP-FPM自動起動の設定と起動
$ sudo systemctl enable php-fpm && sudo systemctl start php-fpm
ブラウザから確認
一通り設定したのでPHPの情報を確認しましょう
☆確認のためのPHPファイル作成
☆ディレクトリは先程のものに変更してくださいね
$ vim /usr/share/nginx/html/example/info.php
+ <?php phpinfo();
ブラウザでhttp://ドメイン/info.phpを開き、PHPの情報が表示されれば完了です
このままでは情報が丸見えなので、先程のindex.htmlと合わせて削除しましょう
☆Webディレクトリ内のindex.htmlとinfo.phpの削除
☆もちろん「/usr/share/nginx/html/example」は変更してください
$ rm -f /usr/share/nginx/html/example/index.html /usr/share/nginx/html/example/info.php
MariaDB
最近はWordPressが流行ってるらしいのでMariaDBも最新のものを入れましょう。
CentOS 7にはMariaDBが入っていますが、古いのでrepoを作成して入れます
MariaDBの追加
☆最初から入ってるMariaDBを削除
$ sudo yum remove -y mariadb-libs
☆repoファイル作成
$ sudo vim /etc/yum.repos.d/MariaDB.repo
+ [mariadb]
+ name = MariaDB
+ baseurl = http://yum.mariadb.org/10.2/centos7-amd64
+ gpgkey = https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
+ enabled = 0
+ gpgcheck = 1
☆MariaDB関連を追加
$ sudo yum -y --enablerepo=mariadb install MariaDB-server MariaDB-client
☆バージョン確認
$ mysql --version
mysql Ver 15.1 Distrib 10.2.11-MariaDB, for Linux (x86_64) using readline 5.1
MariaDBの設定
MariaDBはスペックに合わせてチューニングをすると良いのですが、長くなるので今回は省略します。
気になる方は少し調べてみると良いかもしれませんね
☆server.cnfのバックアップ
$ sudo cp /etc/my.cnf.d/server.cnf /etc/my.cnf.d/server.cnf.org
☆server.cnfの編集
$ sudo vim /etc/my.cnf.d/server.cnf
[mysqld]
# 文字コードの設定
+ character-set-server=utf8
# InnoDBのバッファサイズ(DBメインならメモリの8割、基本はメモリの半分でも良いです
+ innodb_buffer_pool_size=1G
☆自動起動の設定と起動
$ sudo systemctl enable mariadb && sudo systemctl start mariadb
MariaDBの初期設定
mysql_secure_installationを利用して、MariaDBの初期設定をしましょう
☆MariaDBの初期設定
$ mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
Enter current password for root (enter for none): 空Enter
☆今のrootパスワードを入力してください(空Enter
OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.
Set root password? [Y/n] y
☆rootのパスワードを設定しますか?(y
New password: rootに設定するパスワードを入力
☆新しいrootのパスワードを入力してください(設定するパスワードを入力
Re-enter new password: もう一度パスワードを入力
☆確認のためもう一度入力してください(もう一度パスワードを入力
Password updated successfully!
Reloading privilege tables..
... Success!
By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] y
☆匿名ユーザを削除しますか?(y
... Success!
Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] y
☆リモートからのrootログインを禁止しますか?(y
... Success!
By default, MariaDB comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] y
☆testデータベースとそのデータベースへのアクセスを削除しますか?(y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n] y
☆今すぐ権限テーブルを再読み込みしますか?(y
... Success!
Cleaning up...
All done! If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!
☆MariaDBのご利用ありがとうございます!
MariaDBユーザの作成
これは好みの問題もありますが、rootでの接続は少し不安ではないですか?
そこでグローバルレベル全権限を付与した作業ユーザを作成します
☆rootでMariaDBに接続
$ mysql -u root -p
Enter password: 先程設定したMariaDBのrootパスワードを入力
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.2.11-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
☆権限付与以外のグローバルレベル全権限を付与したMariaDBユーザの作成
☆ユーザ名とパスワードは使用するものに変更しましょう(パスワードのアポストロフィは必須です)
> grant all on *.* to ユーザ名@localhost identified by 'パスワード';
Query OK, 0 rows affected (0.00 sec)
☆ユーザの確認(userは作成したユーザ名となります
> select user,host from mysql.user;
+------+-----------+
| user | host |
+------+-----------+
| root | 127.0.0.1 |
| root | ::1 |
| root | localhost |
| user | localhost |
+------+-----------+
4 rows in set (0.00 sec)
☆MariaDBへの接続を終了
> exit
Bye
構築後の管理
少しは役に立つかもしれない、コマンドや説明を書いておきましょう
構築後の管理
基本的に設定ファイルを変更した際は、再起動しない限り反映されません
アップデートは互換性がなくなる可能性があるので気をつけましょう
☆Nginxの再起動(設定反映に必要です)
$ sudo systemctl restart nginx
☆Nginxのアップデート(互換性に気をつけてください)
$ sudo yum -y --enablerepo=nginx upgrade nginx
☆PHP-FPMの再起動(設定反映に必要です)
$ sudo systemctl restart php-fpm
☆PHPのアップデート(互換性に気をつけてください)
$ sudo yum -y --enablerepo=remi-php71 upgrade php php-mbstring php-fpm php-pdo php-mysqlnd
☆MariaDBの再起動(設定反映に必要です)
$ sudo systemctl restart mariadb
☆MariaDBのアップデート(互換性に気をつけてください)
$ sudo yum -y --enablerepo=mariadb upgrade mariadb
☆MariaDBに接続
$ mysql -u ユーザ -p
Enter password: パスワードを入力
☆MariaDBにwordpressというデータベースを作成
> create database wordpress
☆MariaDBの接続を終了
> exit
あるかもしれない質問
もしかしたら聞かれないかもしれない
-
Q. 構築したサイトでHTMLやPHPファイルを公開したいです
A. FTPなどでNginxで設定したWebディレクトリにファイルを置きましょう -
Q. ドメインでWordPressを使用したい
A. Nginxの設定で使用ドメインにWordPressディレクトリを割り当てましょう -
Q. SSL接続をしたい
A. 私も後日書くと思いますが、別の方が書いたこちらが参考になります
終わりに
最後までお読みいただき、ありがとうございます
ここまでで基本的な設定となります
スペックに合わせたチューニングや、用途に合わせた設定も説明したいのですが
初心者向けということもあり長くならないように、今回は省略しました
後日SSL化や詳しい設定を書くかもしれません。私は結構気まぐれですが
ご意見や質問があれば、コメントか呟いていないTwitterに送ってあげてください