【CentOS7】Rails5 + Nginx + Unicorn+SES(AWS)の環境にMonitを導入する記事です。
この記事で紹介すること
- Monitのインストール
- Nginx / Unicornのプロセスが異常終了してしまった場合に、復旧させる設定を行う
- 監視プロセスの異常終了・起動を検知した際に、SES経由でメール通知を行う
1. Monitのインストール
$ sudo yum install monit
2. Monitの起動・自動起動と確認
$ sudo systemctl start monit
$ sudo systemctl enable monit.service
$ sudo systemctl is-enabled monit
3. Nginxの設定ファイルを作成
check process nginx with pidfile /run/nginx.pid
group nginx
start program = "/bin/systemctl start nginx"
stop program = "/bin/systemctl stop nginx"
if 5 restarts within 5 cycles then unmonitor
pidfile /run/nginx.pid
のパスは /etc/nginx/nginx.conf
のpid と合わせる必要がある。
systemctlからNginxが起動できないや、起動するがtimeoutしてエラーになる場合はここを確認する。
group nginx
任意のGroupを指定できる。これを指定するとGroup単位での監視・停止・起動が可能になる。
if 5 restarts within 5 cycles then unmonitor
5回起動を試みて失敗した場合、監視の対象から外れる
4. UnicornをServiceから起動させる
下記のURLを参考に/etc/init.d/unicorn start|stop
で起動・停止できるように設定する
参考URL: https://engineer.blog.lancers.jp/2017/12/unicorn_restart/
5. Unicornの設定ファイルを作成
check process unicorn with pidfile /var/run/unicorn/unicorn.pid
group unicorn
start program = "/bin/sh -l -c '/etc/init.d/unicorn start'"
stop program = "/bin/sh -l -c '/etc/init.d/unicorn stop'"
if 5 restarts within 5 cycles then unmonitor
pidfile /var/run/unicorn/unicorn.pid
のパスはunicorn.rb
のpidと合わせる。
6. SES Mail通知の設定
set mailserver email-smtp.us-west.amazonaws.com port *** username "********" password "******************" using tlsv1 with timeout 30 seconds
set mail-format {
from: **********@***.com
reply-to: **********@***.com
subject: $HOST: $SERVICE $EVENT at $DATE
message:
$SERVICE $EVENT at $DAT
Monit $ACTION $SERVICE at $DATE on $HOST: $DESCRIPTION.
Yours sincerely,
monit
}
set alert **********@***.com # receive all alerts
リージョン部分や***の部分は適時変更してください。
7. syntax check
$ sudo monit -t
Control file syntax OK
8. 設定したファイルを読み込ませる
$ sudo monit reload
9. テスト
試しにNginxを止めて、アラート通知と自動でNginxが立ち上がれば完了です。
$ sudo pkill -kill -f nginx
$sudo monit status
Process 'nginx'
status OK
monitoring status Monitored
monitoring mode active
on reboot start
pid 15470
parent pid 1
uid 0
effective uid 0
gid 0
uptime 2h 24m
threads 1
children 3
cpu 0.0%
cpu total 0.0%
memory 0.1% [1.2 MB]
memory total 0.5% [8.8 MB]
security attribute (null)
data collected Wed, 31 Oct 2018 17:32:54
10. コマンドまとめ
$ sudo monit start unicorn # 監視の開始
$ sudo monit status # ステータス
$ sudo monit -t # 文法チェック
$ sudo monit reload # 再読み込み
$ sudo systemctl start monit # monit起動
$ sudo systemctl enable monit.service # monit自動起動
$ sudo systemctl is-enabled monit # monit自動起動確認
11. 参考記事
https://freelance-start.com/jobs/skill-130
https://qiita.com/mobius01/items/6e7567509bd893be0e3e
https://qiita.com/ma7ma7pipipi/items/ff8f6624e763d2e31948