Part2までは
- 1EC2インスタンスを起動
- 2Elastic IPの関連付け
- 3SSH接続とは
- 4EC2へのSSH接続はとても簡単
- 5Open SSHが入っているか確認
- 6Configファイルについて
- 7EC2インスタンスにSSH接続する
Part3では
Part3ではEC2インスタンスに以下のソフトウェアをインストールしサイトを表示できるようにしていきます。
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
nginx と PHP のインストール
Amazon Linux Extras というコマンドを使ってnginxとphpをインストールします。
以下のコマンドを実行します。
sudo amazon-linux-extras install -y nginx1 php7.4
実行結果
Installing nginx, php-pdo, php-mysqlnd, php-cli, php-json, php-fpm
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Cleaning repos: amzn2-core amzn2extra-docker amzn2extra-kernel-5.10 amzn2extra-nginx1 amzn2extra-php7.4
・・・省略・・・
Dependency Installed:
gperftools-libs.x86_64 0:2.6.1-1.amzn2 libzip.x86_64 0:1.3.2-1.amzn2.0.1
nginx-filesystem.noarch 1:1.20.0-2.amzn2.0.4 openssl11-libs.x86_64 1:1.1.1g-12.amzn2.0.4
openssl11-pkcs11.x86_64 0:0.4.10-6.amzn2.0.1 php-common.x86_64 0:7.4.21-1.amzn2
Complete!
・・・省略・・・
インストールされているか確認します。
amazon-linux-extras | egrep 'nginx|php7.4'
実行結果
38 nginx1=latest enabled [ =stable ]
42 php7.4=latest enabled [ =stable ]
PHP関連のパッケージをインストール
まずはパッケージのアップデート。(おまじない)
sudo yum update
実行結果
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core | 3.7 kB 00:00:00
No packages marked for update
以下のコマンドでPHP関連パッケージのインストール。
sudo yum install -y php-gd php-mbstring php-xml
実行結果
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Resolving Dependencies
--> Running transaction check
---> Package php-gd.x86_64 0:7.4.21-1.amzn2 will be installed
・・・省略・・・
Installed:
php-gd.x86_64 0:7.4.21-1.amzn2 php-mbstring.x86_64 0:7.4.21-1.amzn2 php-xml.x86_64 0:7.4.21-1.amzn2
Dependency Installed:
libxslt.x86_64 0:1.1.28-6.amzn2 oniguruma.x86_64 0:5.9.6-1.amzn2.0.4
Complete!
インストールされているか確認します。
yum list installed | grep ^php- | sort
実行結果
php-cli.x86_64 7.4.21-1.amzn2 @amzn2extra-php7.4
php-common.x86_64 7.4.21-1.amzn2 @amzn2extra-php7.4
php-fpm.x86_64 7.4.21-1.amzn2 @amzn2extra-php7.4
php-gd.x86_64 7.4.21-1.amzn2 @amzn2extra-php7.4
php-json.x86_64 7.4.21-1.amzn2 @amzn2extra-php7.4
php-mbstring.x86_64 7.4.21-1.amzn2 @amzn2extra-php7.4
php-mysqlnd.x86_64 7.4.21-1.amzn2 @amzn2extra-php7.4
php-pdo.x86_64 7.4.21-1.amzn2 @amzn2extra-php7.4
php-xml.x86_64 7.4.21-1.amzn2 @amzn2extra-php7.4
MySQL 8.0 のインストール
まずパッケージ管理ライブラリにデフォルトで入っているMaria DBのイメージを削除します。
sudo yum remove mariadb-libs
実行結果
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Resolving Dependencies
--> Running transaction check
---> Package mariadb-libs.x86_64 1:5.5.68-1.amzn2 will be erased
--> Processing Dependency: libmysqlclient.so.18()(64bit) for package: 2:postfix-2.10.1-6.amzn2.0.3.x86_64
・・・省略・・・
Is this ok [y/N]:y
>>> yを返す
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
・・・省略・・・
Removed:
mariadb-libs.x86_64 1:5.5.68-1.amzn2
Dependency Removed:
postfix.x86_64 2:2.10.1-6.amzn2.0.3
Complete!
MySQL8.0のパッケージを追加します。
sudo yum -y install https://dev.mysql.com/get/mysql80-community-release-el7-1.noarch.rpm
実行結果
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
mysql80-community-release-el7-1.noarch.rpm | 25 kB 00:00:00
・・・省略・・・
Installed:
mysql80-community-release.noarch 0:el7-1
Complete!
追加したパッケージを有効化。
sudo yum-config-manager –enable mysql80-community
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
/usr/lib/python2.7/site-packages/yum/misc.py:146: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
return lambda s: s.lower() == pat
=============================================== repo: mysql80-community ================================================
[mysql80-community]
・・・省略・・・
enabled = True
>>> 有効化されている
・・・省略・・・
MySQLのインストール
sudo yum install mysql-community-server
実行結果
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
47 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package mysql-community-server.x86_64 0:8.0.27-1.el7 will be installed
--> Processing Dependency: mysql-community-common(x86-64) = 8.0.27-1.el7 for package:
・・・省略・・・
Is this ok [y/d/N]: y
>>> yを返す
Downloading packages:
warning: /var/cache/yum/x86_64/2/mysql80-community/packages/mysql-community-client-plugins-8.0.27-1.el7.x86_64.rpm: Header V3 DSA/SHA256 Signature, key ID 5072e1f5: NOKEY
Public key for mysql-community-client-plugins-8.0.27-1.el7.x86_64.rpm is not installed
・・・省略・・・
Importing GPG key 0x5072E1F5:
Userid : "MySQL Release Engineering <mysql-build@oss.oracle.com>"
Fingerprint: a4a9 4068 76fc bd3c 4567 70c8 8c71 8d3b 5072 e1f5
Package : mysql80-community-release-el7-1.noarch (installed)
From : /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
・・・省略・・・
Is this ok [y/N]: y
>>> yを返す
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
・・・省略・・・
Installed:
mysql-community-server.x86_64 0:8.0.27-1.el7
Dependency Installed:
mysql-community-client.x86_64 0:8.0.27-1.el7 mysql-community-client-plugins.x86_64 0:8.0.27-1.el7
mysql-community-common.x86_64 0:8.0.27-1.el7 mysql-community-libs.x86_64 0:8.0.27-1.el7
ncurses-compat-libs.x86_64 0:6.0-8.20170212.amzn2.1.3
Complete!
インストール確認
mysqld --version
実行結果
/usr/sbin/mysqld Ver 8.0.27 for Linux on x86_64 (MySQL Community Server - GPL)
MySQLの初期設定&セキュリティ強化
インストールしたMySQLにデータベースを作成します。
MySQLの起動
sudo systemctl start mysqld.service
状態の確認
sudo systemctl status mysqld.service
実行結果
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2022-01-12 03:08:25 UTC; 43s ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Main PID: xxxxx (mysqld)
Status: "Server is operational"
CGroup: /system.slice/mysqld.service
└─xxxxx /usr/sbin/mysqld
Jan 12 03:08:19 ip-xxx-xx-xx-xxx.ap-northeast-1.compute.internal systemd[1]: Starting MySQL Server...
Jan 12 03:08:25 ip-xxx-xx-xx-xxx.ap-northeast-1.compute.internal systemd[1]: Started MySQL Server.
初期ログインパスワードの確認。
sudo nano /var/log/mysqld.log
実行結果
・・・省略・・・
2022-01-12T03:08:21.559986Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: xxxxxxxxxxxxx <<< 初期パスワード
・・・省略・・・
初期設定 & セキュリティ強化
sudo mysql_secure_installation
New passwordは英語大文字小文字、数字、記号を組み合わせた8文字以上である必要があります。
8桁はセキュアな長さではないので、可能な限り長めに設定しましょう。
実行結果
Securing the MySQL server deployment.
Enter password for user root:
>>> 先ほど確認した初期パスワードを入力
The existing password for the user account root has expired. Please set a new password.
New password:
>>> 新しいパスワードを入力
Re-enter new password:
... Failed! Error: Your password does not satisfy the current policy requirements
>>> パスワードの条件を満たしていないとErrorが出ます
New password:
>>> 気を取り直して新しいパスワードを入力
Re-enter new password:
>>> 同じパスワードを入力
The 'validate_password' component is installed on the server.
The subsequent steps will run with the existing configuration
of the component.
Using existing password for root.
Estimated strength of the password: 100
Change the password for root ? ((Press y|Y for Yes, any other key for No) :Y
>>> パスワードの強度が数値で表されています。100はとてもセキュアな状態です
>>> 大文字のYを返します
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL 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? (Press y|Y for Yes, any other key for No) :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? (Press y|Y for Yes, any other key for No) :Y
>>> リモートからのrootユーザーログインを拒否するか
>>> 予定がなければ拒否 Y を返します
Success.
By default, MySQL 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? (Press y|Y for Yes, any other key for No) :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? (Press y|Y for Yes, any other key for No) :Y
>>> 変更を有効化するか
>>> 有効化 Y を返します
Success.
All done!
データベースの作成
MySQLにログインします。
sudo mysql -u root -p
Enter password:
>>> 設定したパスワードを入力
実行結果
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 31
Server version: 8.0.27 MySQL Community Server - GPL
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
WordPressで使うデータベースを作成します。
CREATE DATABASE `wordpress-db`;
実行結果
Query OK, 1 row affected (0.00 sec)
作成できたか確認
show databases;
実行結果
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| wordpress-db | <<< 作成されている
+--------------------+
5 rows in set (0.00 sec)
データベースを操作できるユーザーを作成します。
create user 'wordpress-user'@'localhost' identified with mysql_native_password by 'ここに任意のパスワードを入力';
実行結果
Query OK, 0 rows affected (0.01 sec)
作成したユーザーに権限を付与します。
GRANT ALL PRIVILEGES ON `wordpress-db`.* TO 'wordpress-user'@'localhost';
実行結果
Query OK, 0 rows affected (0.00 sec)
権限付与の反映
FLUSH PRIVILEGES;
実行結果
Query OK, 0 rows affected (0.00 sec)
ユーザーが作成されているか確認
SELECT Host, User, Plugin FROM mysql.user;
実行結果
+-----------+------------------+-----------------------+
| Host | User | Plugin |
+-----------+------------------+-----------------------+
| localhost | mysql.infoschema | caching_sha2_password |
| localhost | mysql.session | caching_sha2_password |
| localhost | mysql.sys | caching_sha2_password |
| localhost | root | caching_sha2_password |
| localhost | wordpress-user | mysql_native_password | <<< 作成されている
+-----------+------------------+-----------------------+
5 rows in set (0.01 sec)
MySQLから抜ける
exit
php-fpm Configファイルの編集
php-fpmの設定ファイルを修正します。
以下のコマンドでファイルを開き修正します。
sudo nano /etc/php-fpm.d/www.conf
user = apache と group = apache となっているところを = nginx に変更します。
; Start a new pool named 'www'.
; the variable $pool can we used in any directive and will be replaced by the
; pool name ('www' here)
[www]
; Per pool prefix
; It only applies on the following directives:
; - 'access.log'
; - 'slowlog'
; - 'listen' (unixsocket)
; - 'chroot'
; - 'chdir'
; - 'php_values'
; - 'php_admin_values'
; When not set, the global prefix (or @php_fpm_prefix@) applies instead.
; Note: This directive can also be relative to the global prefix.
; Default Value: none
;prefix = /path/to/pools/$pool
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
; will be used.
; RPM: apache user chosen to provide access to the same directories as httpd
user = apach
>>> user = nginx に変更
; RPM: Keep a group allowed to write in log dir.
group = apache
>>> group = nginx に変更
; The address on which to accept FastCGI requests.
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
; a specific port;
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
; a specific port;
; 'port' - to listen on a TCP socket to all addresses
; (IPv6 and IPv4-mapped) on a specific port;
; '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = /run/php-fpm/www.sock
; Set listen(2) backlog.
; Default Value: 511
;listen.backlog = 511
; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server.
; Default Values: user and group are set as the running user
; mode is set to 0660
;listen.owner = nobody
;listen.group = nobody
;listen.mode = 0660
; When POSIX Access Control Lists are supported you can set them using
; these options, value is a comma separated list of user/group names.
; When set, listen.owner and listen.group are ignored
listen.acl_users = apache,nginx
;listen.acl_groups =
; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
listen.allowed_clients = 127.0.0.1
; Specify the nice(2) priority to apply to the pool processes (only if set)
修正が終わったら、F2 キーを押し yキーで保存します。
設定を反映させるためにphp-fpmを再起動します。
sudo systemctl restart php-fpm
Webサイトが公開できるかテスト
WordPressをインストールする前に、今の状態でWebサイトが公開できるかテストをします。
以下のコマンドでテストページ用のindexファイルを作成します。
sudo sh -c "echo '<?php phpinfo(); ?>' > /usr/share/nginx/html/index_test.php"
次にEC2のセキュリティグループにhttpアクセスを許可するための設定を追加します。
EC2のコンソール画面にアクセスし、セキュリティグループの設定画面に入ります。

インバウンドルールの追加をクリック。

ルールの追加をクリックし、タイプはHTTPを選択、CIDRは0.0.0.0/0を入力します。
※他者のアクセスを禁止したい場合は自分のIPアドレス/32と指定してください。

テストの準備が整いましたので、以下のアドレスからアクセスしてみます。
http://EC2のグローバルIPアドレス
問題がなければ以下のページが表示されます。

表示されない場合はnginxかphp、EC2のセキュリティグループが原因の可能性が高いです。
設定を見直してみてください。
ソフトウェアの自動起動
インストールしたソフトウェアがインスタンスの再起動時に自動起動するよう設定します。
sudo systemctl enable nginx php-fpm mysqld
実行結果
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
Created symlink from /etc/systemd/system/multi-user.target.wants/php-fpm.service to /usr/lib/systemd/system/php-fpm.service.
Created symlink from /etc/systemd/system/multi-user.target.wants/mysqld.service to /usr/lib/systemd/system/mysqld.service.
自動起動設定の反映を確認します。
systemctl is-enabled nginx php-fpm mysqld
実行結果
enabled
enabled
enabled
WordPress のインストール
2022年1月時点の最新版パッケージをダウンロードします。
sudo wget https://ja.wordpress.org/wordpress-5.9-ja.tar.gz
実行結果
--2022-01-29 04:03:33-- https://ja.wordpress.org/wordpress-5.9-ja.tar.gz
Resolving ja.wordpress.org (ja.wordpress.org)... xxx.xxx.xxx.xxx
Connecting to ja.wordpress.org (ja.wordpress.org)|xxx.xxx.xxx.xxx|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 15815954 (15M) [application/octet-stream]
Saving to: ‘wordpress-5.9-ja.tar.gz’
100%[===========================================================================================>] 15,815,954 6.11MB/s in 2.5s
2022-01-29 04:03:36 (6.11 MB/s) - ‘wordpress-5.9-ja.tar.gz’ saved [15815954/15815954]
ダウンロードしたパッケージを解凍します。
sudo tar zxvf wordpress-5.9-ja.tar.gz
実行結果
wordpress/
wordpress/wp-login.php
wordpress/wp-cron.php
wordpress/xmlrpc.php
wordpress/wp-load.php
wordpress/wp-admin/
wordpress/wp-admin/credits.php
wordpress/wp-admin/admin-functions.php
wordpress/wp-admin/options-reading.php
wordpress/wp-admin/edit-tags.php
wordpress/wp-admin/link-manager.php
wordpress/wp-admin/options-writing.php
wordpress/wp-admin/network.php
wordpress/wp-admin/includes/
・・・省略・・・
解凍が無事終わりましたら、インストールしたパッケージを削除します。
sudo rm wordpress-5.9-ja.tar.gz
解凍したフォルダをnginxのドキュメントルートにコピーします。
sudo cp -r wordpress/* /usr/share/nginx/html
WordPressの設定
設定ファイルのディレクトリに移動します。
cd /usr/share/nginx/html/
サンプルの設定ファイルをコピーします。
sudo cp wp-config-sample.php wp-config.php
設定ファイルの修正を行います。
sudo nano wp-config.php
以下の箇所を変更します。
// ** MySQL 設定 - この情報はホスティング先から入手してください。 ** //
/** WordPress のためのデータベース名 */
define( 'DB_NAME', 'wordpress-db' );
/** MySQL データベースのユーザー名 */
define( 'DB_USER', 'wordpress-user' );
/** MySQL データベースのパスワード */
define( 'DB_PASSWORD', '設定したパスワード' );
/** MySQL のホスト名 */
define( 'DB_HOST', 'localhost' );
/** データベースのテーブルを作成する際のデータベースの文字セット */
define( 'DB_CHARSET', 'utf8' );
/** データベースの照合順序 (ほとんどの場合変更する必要はありません) */
define( 'DB_COLLATE', '' );
以下についてはhttps://api.wordpress.org/secret-key/1.1/salt/から取得した値を貼り付けします。
define( 'AUTH_KEY', 'put your unique phrase here' );
define( 'SECURE_AUTH_KEY', 'put your unique phrase here' );
define( 'LOGGED_IN_KEY', 'put your unique phrase here' );
define( 'NONCE_KEY', 'put your unique phrase here' );
define( 'AUTH_SALT', 'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT', 'put your unique phrase here' );
define( 'NONCE_SALT', 'put your unique phrase here' );
修正が終わったら、F2 キーを押し yキーで保存します。
念のため各種サービスを再起動します。
sudo systemctl restart nginx php-fpm mysqld
WordPress 構築確認
http://EC2のグローバルIPアドレス からWordpressの設定画面にアクセスできるか確認します。
各種項目を入力しWordPressをインストールをクリック。


もう一度 http://EC2のグローバルIPアドレス にアクセスするとトップページが表示されます。

無事にページは表示できましたか?
上手くいかない場合は展開したWordpress関連のフォルダがnginxのルートに配置されているか、configファイルの設定に誤りはないか確認してみてください。
実運用に向けて
大変長らくお疲れさまでした。
本記事は分かりやすかったでしょうか?画像や解説を入れるように心がけましたが、もし分かりづらい点がありましたらコメントください!
さて実際にページが表示できるところまでいきましたが、実際の運用にあたっては以下を考慮する必要があります。
- ドメインの作成
- SSL通信 (https化)
- マシンのメモリ容量が少ない場合はスワップ設定
- S3やCloudFront等のサービスを使いコスパの良い構成にする
上記関連の記事は気が向いたら書こうかなと!