Amazon Linux 2 で Extras Library から nginx をインストールし、systemd を使って立ち上げる

# 環境

- Amazon Linux 2

# まとめ

- Extras Library からインストールする
  - 参照先: https://aws.amazon.com/jp/premiumsupport/knowledge-center/ec2-install-extras-library-software/
- systemd を使って起動、及び自動起動の設定を行う

# 手順

## nginx が Extras Library に存在することを確認

```
$ amazon-linux-extras | grep nginx
 38  nginx1=latest            enabled      [ =stable ]
```

## 詳細を確認

```
$ amazon-linux-extras info nginx1
nginx1 recommends nginx                      # yum install nginx
```

## インストール

```
$ sudo amazon-linux-extras install nginx1
```

## バージョンとコンパイルオプションの確認

```
$ nginx -V
nginx version: nginx/1.18.0
built by gcc 7.3.1 20180712 (Red Hat 7.3.1-8) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-stream_ssl_preread_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-http_auth_request_module --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-google_perftools_module --with-debug --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'
```

以下、`configure arguments` を改行区切りにしたもの。

```
--prefix=/usr/share/nginx
--sbin-path=/usr/sbin/nginx
--modules-path=/usr/lib64/nginx/modules
--conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--http-client-body-temp-path=/var/lib/nginx/tmp/client_body
--http-proxy-temp-path=/var/lib/nginx/tmp/proxy
--http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi
--http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi
--http-scgi-temp-path=/var/lib/nginx/tmp/scgi
--pid-path=/run/nginx.pid
--lock-path=/run/lock/subsys/nginx
--user=nginx
--group=nginx
--with-file-aio
--with-ipv6
--with-http_ssl_module
--with-http_v2_module
--with-http_realip_module
--with-stream_ssl_preread_module
--with-http_addition_module
--with-http_xslt_module=dynamic
--with-http_image_filter_module=dynamic
--with-http_geoip_module=dynamic
--with-http_sub_module
--with-http_dav_module
--with-http_flv_module
--with-http_mp4_module
--with-http_gunzip_module
--with-http_gzip_static_module
--with-http_random_index_module
--with-http_secure_link_module
--with-http_degradation_module
--with-http_slice_module
--with-http_stub_status_module
--with-http_perl_module=dynamic
--with-http_auth_request_module
--with-mail=dynamic
--with-mail_ssl_module
--with-pcre
--with-pcre-jit
--with-stream=dynamic
--with-stream_ssl_module
--with-google_perftools_module
--with-debug
--with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic'
--with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'
```

## 起動ファイルの確認

```
$ ll /usr/lib/systemd/system/nginx.service
-rw-r--r-- 1 root root 616 Aug 30 06:40 /usr/lib/systemd/system/nginx.service

$ cat /usr/lib/systemd/system/nginx.service
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=mixed
PrivateTmp=true

[Install]
WantedBy=multi-user.target
```

※ [参考: CentOS 7 における systemd のファイル・フォルダ構成](https://weblabo.oscasierra.net/centos7-systemd-files/)

## デフォルトのユニットファイルを変更する

※ [参考: 既存のユニットファイルの変更](https://access.redhat.com/documentation/ja-jp/red_hat_enterprise_linux/7/html/system_administrators_guide/sect-Managing_Services_with_systemd-Unit_Files#sect-Managing_Services_with_systemd-Unit_File_Modify)

#### `/usr/lib/systemd/system/`ディレクトリーに保存されるデフォルトのユニットファイルを直接編集出来ないため、以下のいずれかの方法で行います。

- 補助設定ファイルのディレクトリーを `/etc/systemd/system/unit.d/` に作成する。
  - インストール時に `/etc/systemd/system/nginx.service.d/` は既に出来ています。
  - ディレクトリ配下に任意の名前で config ファイルを作成して、それを編集します。
  
  ```
  sudo touch /etc/systemd/system/nginx.service.d/nginx.conf
  ```

- 元のユニットファイル `/usr/lib/systemd/system/` のコピーを `/etc/systemd/system/` に作成し、そこで変更を行う。
  - 例えば、デフォルトの pid ファイル（/run/nginx.pid）を上書きする場合は、以下のようになります。 

```
[Service]
# When you install nginx from the Extras Library, the pid is configured to /run/nginx.pid.
# It's overwritten here.
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/bin/rm -f /var/run/nginx.pid
```

#### 設定変更を反映させる

```
systemctl daemon-reload
systemctl reload nginx.service
```

## 起動

```
$ sudo systemctl start nginx.service
```

## 起動確認

```
$ sudo systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2020-09-01 08:25:29 UTC; 46min ago
 Main PID: 4302 (nginx)
   CGroup: /system.slice/nginx.service
           ├─4302 nginx: master process /usr/sbin/nginx
           └─4303 nginx: worker process


Sep 01 08:25:28 ip-10-0-1-96.ap-northeast-1.compute.internal systemd[1]: Starting The nginx HTTP and reverse proxy server...
Sep 01 08:25:29 ip-10-0-1-96.ap-northeast-1.compute.internal nginx[4295]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Sep 01 08:25:29 ip-10-0-1-96.ap-northeast-1.compute.internal nginx[4295]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Sep 01 08:25:29 ip-10-0-1-96.ap-northeast-1.compute.internal systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument
Sep 01 08:25:29 ip-10-0-1-96.ap-northeast-1.compute.internal systemd[1]: Started The nginx HTTP and reverse proxy server.
```

## 動作確認

```
$ curl -I localhost
HTTP/1.1 200 OK
```

## 自動起動設定

```
$ systemctl is-enabled nginx.service
disabled

$ sudo systemctl enable nginx.service

$ systemctl is-enabled nginx.service
enabled
```

## OS を再起動してみて、nginx が自動起動されることを確認

```
$ sudo reboot
```

## ログ

### accesslog, error.log
 
```
$ sudo ls -al /var/log/nginx/
total 8
drwxrwx--- 2 nginx root   41 Sep  1 08:25 .
drwxr-xr-x 8 root  root 4096 Sep  6 07:53 ..
-rw-r--r-- 1 root  root  298 Sep  6 07:59 access.log
-rw-r--r-- 1 root  root    0 Sep  1 08:25 error.log
```

## 起動ユーザを nginx から変更している場合の対応

デフォルトでは master プロセスは root、worker プロセスは nginx ユーザで起動します。

```
$ ps -ef | grep nginx | grep -v grep
root      9064     1  0 06:26 ?        00:00:00 nginx: master process /usr/sbin/nginx
nginx     9065  9064  0 06:26 ?        00:00:00 nginx: worker process
```
```
$ grep nginx /etc/passwd
nginx:x:996:994:Nginx web server:/var/lib/nginx:/sbin/nologin
```

nginx ユーザでは無く別のユーザを config 等で指定して起動した場合、以下のようなエラーが出ます。

```
2020/09/11 12:39:37 [crit] 3504#0: *1 open() "/var/lib/nginx/tmp/proxy/1/00/0000000001" failed (13: Permission denied) while reading upstream, client: 120.51.41.11, server: localhost, request: "GET ..." 
```

その場合は、`/var/lib/nginx` の owner を再帰的に変更する必要があります。

```
$ sudo chown -R <new_user> /var/lib/nginx
```


### journald

```
$ sudo journalctl -u nginx.service
```

## 備忘録（各種コマンド）

### enable/disable

```
$ sudo systemctl enable nginx.service

$ systemctl is-enabled nginx.service
enabled

$ sudo systemctl disable nginx.service
Removed symlink /etc/systemd/system/multi-user.target.wants/nginx.service.
```

### start/stop/reload/restart

```
$ sudo systemctl start nginx.service

$ sudo systemctl stop nginx.service

$ sudo systemctl reload nginx.service

$ sudo systemctl restart nginx.service
```

### status

```
$ sudo systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2020-09-01 08:25:29 UTC; 46min ago
 Main PID: 4302 (nginx)
   CGroup: /system.slice/nginx.service
           ├─4302 nginx: master process /usr/sbin/nginx
           └─4303 nginx: worker process


Sep 01 08:25:28 ip-10-0-1-96.ap-northeast-1.compute.internal systemd[1]: Starting The nginx HTTP and reverse proxy server...
Sep 01 08:25:29 ip-10-0-1-96.ap-northeast-1.compute.internal nginx[4295]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Sep 01 08:25:29 ip-10-0-1-96.ap-northeast-1.compute.internal nginx[4295]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Sep 01 08:25:29 ip-10-0-1-96.ap-northeast-1.compute.internal systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument
Sep 01 08:25:29 ip-10-0-1-96.ap-northeast-1.compute.internal systemd[1]: Started The nginx HTTP and reverse proxy server.
```

### daemon-reload

```
sudo systemctl daemon-reload
```

### list-unit-files

```
sudo systemctl list-unit-files --type=service

systemd-modules-load.service                  static
systemd-nspawn@.service                       disabled
systemd-poweroff.service                      static
systemd-quotacheck.service                    static
systemd-random-seed.service                   static
systemd-readahead-collect.service             enabled
```

### list-dependencies（起動順の確認）

```
$ systemctl list-dependencies

$ systemctl list-dependencies -a
```

### systemd-analyze verify

```
$ sudo systemd-analyze verify /etc/systemd/system/unicorn.service
```