序章

Monitは、さまざまなイベントベースのアクションを実行できる無料のオープンソースサービス監視アプリケーションです。 Monitは、電子メール通知を送信したり、サービスやアプリケーションを再起動したり、その他の応答アクションを実行したりできます。

このチュートリアルは、基本的なLEMPスタック(Linux、Nginx、MySQL、PHP)に基づいて構築されます。 Monitは、スタック内のすべてのサービスを監視し、rootユーザーに悪条件を警告するために組み込まれます。

オプションの外部Monitサーバーは、Webアプリケーションまたはその他のサービスのリモート監視にも使用できます。

前提条件

  • 始める前に、まずUbuntu14.04ドロップレットを設定する必要があります
  • sudo権限を持つ標準ユーザーアカウントが必要になります
  • このチュートリアルでは、Monitを既存のLEMPスタックに追加します。 初期LEMPスタックを作成する方法のチュートリアルについては、 Ubuntu 14.04にLinux、nginx、MySQL、PHP(LEMP)スタックをインストールする方法を参照してください。
  • オプション:リモートのWebサイト、DNS、またはメールサーバーを監視する場合は、そのサーバーに公的にアクセス可能なドメインまたはIPアドレスを設定する必要があります(手順6で詳しく説明します)。

ステップ1—Monit通知の電子メール配信を構成する

システム監視の一部には、通常、アラートの電子メール通知が含まれます。 そのため、Monitが電子メール通知を送信するには、適切な電子メール配信が行われている必要があります。 一般的なMonitアラートメールは次のようになります。

From: [email protected] 
To: [email protected]

Resource limit matched Service example.com

        Date:        Mon, 22 Dec 2014 03:04:06
        Action:      alert
        Host:        example.com
        Description: cpu user usage of 79.8% matches resource limit [cpu user usage>70.0%]

Your faithful employee,
Monit

このチュートリアルでは、アラートがトリガーされるたびにメールを送信するようにMonitを設定します。

注: Monitの通知は、デフォルトでスパムフォルダに送信される可能性があります。 逆引きDNS(PTRレコードと呼ばれる)は、メールが正常に配信される可能性が最も高くなるように適切に構成する必要があります。 ドロップレットのホスト名は完全修飾ドメイン名(FQDN)と一致する必要があるため、たとえば、両方をhostname.example.comにすることができます。 DigitalOceanドロップレットのPTRレコードを編集するには、DigitalOceanコントロールパネルにアクセスします。 設定に移動し、名前の変更タブを選択します。 新しいホスト名を入力し、名前の変更をクリックします。

このガイドでは、既存のメール転送エージェント(MTA)がないことを前提としているため、Postfixをインストールします。 Postfixをローカルにインストールすると、システムはGmailやYahooなどの外部メールプロバイダーに通知メールを送信できます。

MTAとしてPostfixのインストールを開始するには、最初にシステムのリポジトリソースリストを更新します。

sudo apt-get update

次に、UbuntuのリポジトリからPostfixおよびGNUMailutilsパッケージをインストールします。

sudo apt-get install postfix mailutils

インストールの終わり近くに、以下のスクリーンショットに示すように、サーバー構成タイプを選択するように求められます。 インターネットサイトを選択します。

Postfix - select Internet Site

システムメール名の入力を求められたら、ドロップレットの完全修飾ドメイン名(FQDN)を使用します。 注:システムメール名は、後で/etc/mailnameで変更することもできます。

Postfix - set System Mail Name

次に、ファイル / etc /aliasesを開いて編集します。 このガイドではNanoを使用しますが、お好みのテキストエディタを使用できます。

sudo nano /etc/aliases

ここでは、Monitの通知メールを受信する個人のメールアドレスを追加します。 これらのメール通知は、LEMPサーバーのrootユーザーから送信されます。

postmaster: root
root: [email protected]

必要に応じて、複数の宛先を追加することもできます。

root: username, [email protected], [email protected]

変更を保存してNanoを終了します。 次に、以下を実行してエイリアスファイルを更新します。

sudo newaliases

ドロップレットからテストメッセージを送信して、メール配信を確認できます。 テストメッセージが受信トレイに最初に表示されない場合は、スパムフォルダを確認してください。

echo test | mail -s "test message from my VPS" root

ステップ2—Monitをインストールして構成する

Monitは、Ubuntuパッケージリポジトリでも利用できます。 Monitの簡単なリファレンスガイドについては、このチュートリアルを参照してください。

Monitは、次の方法でLEMPサーバーにインストールできます。

sudo apt-get install monit

Ubuntu 14.04では、Monit構成ファイルは / etc / monit / にあり、メインのMonit構成ファイルは/etc/monit/monitrcです。

Nanoでmonitrcを開いて編集するには:

sudo nano /etc/monit/monitrc

次の行のコメントを解除し、以下に示すものと一致するように変更します。

set mailserver localhost	#Use localhost for email alert delivery.

set mail-format {
      from: monit@$HOST
   subject: monit alert --  $EVENT $SERVICE
   message: $EVENT Service $SERVICE
                 Date:        $DATE
                 Action:      $ACTION
                 Host:        $HOST
                 Description: $DESCRIPTION

            Your faithful employee,
            Monit
}

set alert root@localhost not on { instance, action }	#Set email address to receive alerts. This guide uses root mail.

monitrc ファイルで、次の行のコメントを解除し、example.comをサーバーのドメインまたはIPアドレスに一致するように変更します。

check system example.com
    if loadavg (1min) > 4 then alert
    if loadavg (5min) > 2 then alert
    if memory usage > 75% then alert
    if swap usage > 25% then alert
    if cpu usage (user) > 70% then alert
    if cpu usage (system) > 30% then alert
    if cpu usage (wait) > 20% then alert

また、ファイルの最後に次のエントリを追加します。

check filesystem rootfs with path /	#Alert if low on disk space.
    if space usage > 90% then alert

変更を保存してNanoを終了します。

ステップ3—MonitでLEMPサービスのサービス監視を構成する

Ubuntu 14.04では、Monit構成は/etc/monit/monitrcファイルで直接指定することも、/etc/monit/conf.d/の個々のファイルを介して指定することもできます。 このチュートリアルでは、/etc/monit/conf.d/ディレクトリの下に個々のファイルが作成されます。

まず、Monitにサービスを管理する手段を提供します。 このチュートリアルを簡単にするために、すべてのプロセス監視を/etc/monit/conf.d/lemp-servicesにある単一のファイルに配置します。 次のエントリを使用して、MonitはNginx、MySQL、およびPHP-FPMを監視し、何らかの理由でこれらのサービスが異常に停止した場合にこれらのサービスを再起動します。

Nanoを使用して作業ファイルを作成できます。

sudo nano /etc/monit/conf.d/lemp-services

LEMPスタックのサービスに次のエントリを追加します。

check process nginx with pidfile /var/run/nginx.pid
    group www-data
    start program = "/etc/init.d/nginx start"
    stop program = "/etc/init.d/nginx stop"
    
check process mysql with pidfile /var/run/mysqld/mysqld.pid
    start program = "/etc/init.d/mysql start"
    stop program = "/etc/init.d/mysql stop"
        
check process php5-fpm with pidfile /var/run/php5-fpm.pid
    start program = "/etc/init.d/php5-fpm start"
    stop program = "/etc/init.d/php5-fpm stop"

次に、変更を保存します。

ステップ4—異常なLEMPサービスを再起動するためのアクションを追加する

Monitが選択したサービスを管理できるようになったので、必要に応じてサービスを再起動するためのアクションを追加できます。 たとえば、MonitにはTCP接続を監視する機能があります。 サーバーがHTTP接続を提供しなくなった場合、MonitはPHP-FPMまたはNginxを再起動して、問題を自動的に解決できます。

既存の構成に基づいて構築するために、/etc/monit/conf.d/lemp-servicesをさらに編集します。 以下で行う追加はで示され、HTTP接続が使用できなくなった場合はNginxとPHP-FPMを再起動するようにMonitに指示します。 さらに、ソケットが使用できない場合は、MonitがMySQLを再起動します。

注:最初と3番目のエントリにexample.comが表示されているDropletのドメインまたはIPアドレスを使用してください。

check process nginx with pidfile /var/run/nginx.pid
    group www-data
    start program = "/etc/init.d/nginx start"
    stop program = "/etc/init.d/nginx stop"
    if failed host example.com port 80 protocol http then restart
    if 5 restarts within 5 cycles then timeout
    
check process mysql with pidfile /var/run/mysqld/mysqld.pid
    start program = "/etc/init.d/mysql start"
    stop program = "/etc/init.d/mysql stop"
    if failed unixsocket /var/run/mysqld/mysqld.sock then restart
    if 5 restarts within 5 cycles then timeout
    
check process php5-fpm with pidfile /var/run/php5-fpm.pid
    start program = "/etc/init.d/php5-fpm start"
    stop program = "/etc/init.d/php5-fpm stop"
    if failed host example.com port 80 protocol http then restart
    if 5 restarts within 5 cycles then timeout

変更を保存してNanoを閉じます。 次に、Monitを再起動して、これまでに行った構成変更を適用します。

sudo service monit restart

ステップ5(オプション)—エラーとキーワードのログを監視します

Monitは、特定のキーワードのログを監視してから、アクションを実行したり、アラートを送信したりすることもできます。 これは、Webアプリケーションで問題が発生した場合、またはチームがログから特定のトレースバックまたはイベントの通知を必要とする場合に役立ちます。

以下は、Monitが監視できるタイムアウトエラーとアラートを伴うNginxログの例です。

2014/12/22 11:03:54 [error] 21913#0: *202571 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 2600:3c01::f03c:91ff:fe6e:5a91, server: example.com, request: "GET /wp-admin/admin-ajax.php?action=wordfence_doScan&isFork=1&cronKey=40cb51ccsdfsf322fs35 HTTP/1.0", upstream: "fastcgi://unix:/var/run/example.com.sock", host: "example.com"

既存の構成に基づいて、LEMPサービス構成ファイルをNanoで再度開きます。

sudo nano /etc/monit/conf.d/lemp-services

次のエントリを追加します。 これにより、PHP-FPMと通信するNginxからタイムアウトが発生したときに通知が送信されます。

check file nginx-error with path /var/log/nginx/error.log
    if match "^timed out" then alert

変更を保存してNanoを閉じます。 次に、変更を有効にするためにMonitを再起動します。

sudo service monit restart

ステップ6(オプション)—Monitを使用してリモートWebサイトおよびその他のサービスを監視する

Monitをローカルで使用することに加えて、Monitはさまざまな外部サービスと接続を監視できます。 この例では、すでに設定したMonitのローカルインスタンスを使用し、外部サービスの新しい監視構成をいくつか追加します。

帯域外の目的で、まったく異なるデータセンターに外部Monitシステムを配置することをお勧めします。 Webアプリケーションがニューヨークを拠点としている場合は、サンフランシスコに小さな外部Monitサーバーを配置するのが理想的です。

以下は、Monitを実行している2番目のホストに実装できる外部Monitチェックの例です。 これらの例は、外部サーバーの/etc/monit/conf.d/lemp-externalファイルに配置され、remote-example.comでLEMPスタックをリモートでチェックします。

Nanoを使用して、この構成ファイルを作成します。

sudo nano /etc/monit/conf.d/lemp-external

ICMP応答とHTTPおよびHTTPS接続を監視します。

# ICMP check
check host remote-example.com with address remote-example.com
    if failed icmp type echo
        for 5 times within 5 cycles
        then alert

# HTTP check
    if failed 
          port 80 protocol http 
       for 5 times within 5 cycles
       then alert        

# HTTPS check
    if failed 
          port 443 type tcpSSL protocol http 
       for 5 times within 5 cycles
       then alert

DNSの監視:

check host ns1.example.com with address ns1.example.com
    if failed port 53 type udp protocol dns then alert

SMTPの監視:

check host smtp.example.com with address smtp.example.com
    if failed port 25 type tcp protocol smtp then alert

WebアプリケーションのヘルスチェックURLを監視する

Webアプリケーションの場合、MonitはヘルスチェックURLに対して特定のリクエストを実行することもできます。 以下は、ヘルスチェックURLがhttps://remote-example.com/healthcheckのサイトremote-example.comの例です。

check host remote-example.com with address remote-example.com
    if failed 
          port 443 type tcpSSL protocol http 
       request "/healthcheck"     
       for 5 times within 5 cycles
       then alert

ステップ7—コマンドラインからMonitを管理する

Monitは、コマンドラインユーティリティも提供します。 そこから、簡単なコマンドを使用して、Monitの全体的なステータスを確認し、監視の一時的な開始や停止などの便利なタスクを完了することができます。

コマンドラインからMonitステータスチェックを実行するには、MonitWebサービスを有効にする必要があります。 これを行うには、/etc/monit/monitrcを開いてNanoで編集します。

sudo nano /etc/monit/monitrc

次の行のコメントを解除して、Webサービスをローカルで有効にします。

set httpd port 2812 and
        use address localhost
        allow localhost

変更を保存してNanoを終了します。 次に、Monitを再起動します。

sudo service monit restart

これで、コマンドラインからMonitのステータスを確認できます。

以下は、監視を一時的に無効および有効にするコマンドです。

sudo monit unmonitor all

sudo monit monitor all

ステップ8—レポートを表示する

設定したすべてのチェックのレポートを見てみましょう。

sudo monit status

これで、ローカルLEMPサービスや外部チェックなど、Monitがチェックするように構成したすべての出力が表示されます。

sudo monit status
The Monit daemon 5.6 uptime: 0m 

System 'example.com'
  status                            Running
  monitoring status                 Monitored
  load average                      [0.00] [0.01] [0.05]
  cpu                               0.5%us 0.4%sy 0.0%wa
  memory usage                      115132 kB [22.9%]
  swap usage                        0 kB [0.0%]
  data collected                    Mon, 22 Dec 2014 16:50:42

Filesystem 'rootfs'
  status                            Accessible
  monitoring status                 Monitored
  permission                        755
  uid                               0
  gid                               0
  filesystem flags                  0x1000
  block size                        4096 B
  blocks total                      5127839 [20030.6 MB]
  blocks free for non superuser     4315564 [16857.7 MB] [84.2%]
  blocks free total                 4581803 [17897.7 MB] [89.4%]
  inodes total                      1310720
  inodes free                       1184340 [90.4%]
  data collected                    Mon, 22 Dec 2014 16:50:42

Process 'nginx'
  status                            Running
  monitoring status                 Monitored
  pid                               14373
  parent pid                        1
  uptime                            28m 
  children                          4
  memory kilobytes                  1364
  memory kilobytes total            9228
  memory percent                    0.2%
  memory percent total              1.8%
  cpu percent                       0.0%
  cpu percent total                 0.0%
  port response time                0.018s to example.com:80 [HTTP via TCP]
  data collected                    Mon, 22 Dec 2014 16:50:42

Process 'mysql'
  status                            Running
  monitoring status                 Monitored
  pid                               12882
  parent pid                        1
  uptime                            32m 
  children                          0
  memory kilobytes                  44464
  memory kilobytes total            44464
  memory percent                    8.8%
  memory percent total              8.8%
  cpu percent                       0.0%
  cpu percent total                 0.0%
  unix socket response time         0.000s to /var/run/mysqld/mysqld.sock [DEFAULT]
  data collected                    Mon, 22 Dec 2014 16:50:42

Process 'php5-fpm'
  status                            Running
  monitoring status                 Monitored
  pid                               17033
  parent pid                        1
  uptime                            0m 
  children                          2
  memory kilobytes                  13836
  memory kilobytes total            22772
  memory percent                    2.7%
  memory percent total              4.5%
  cpu percent                       0.0%
  cpu percent total                 0.0%
  port response time                0.018s to example.com:80 [HTTP via TCP]
  data collected                    Mon, 22 Dec 2014 16:50:42

File 'nginx-error'
  status                            Accessible
  monitoring status                 Monitored
  permission                        644
  uid                               0
  gid                               0
  timestamp                         Mon, 22 Dec 2014 16:18:21
  size                              0 B
  data collected                    Mon, 22 Dec 2014 16:50:42

Remote Host 'example.com'
  status                            Online with all services
  monitoring status                 Monitored
  icmp response time                0.021s [Echo Request]
  port response time                0.107s to example.com:443 [HTTP via TCPSSL]
  port response time                0.062s to example.com:80 [HTTP via TCP]
  data collected                    Mon, 22 Dec 2014 16:50:42
  

このデータを使用して、サービスの状態を確認し、有用な統計を確認してください。

トラブルシューティング

問題が発生した場合は、まず/var/log/monit.logにあるMonitのログを確認してください。 これにより、問題の性質に関する詳細情報が得られます。

エラーログエントリの例:

[UTC Dec 22 13:59:54] error    : ICMP echo response for example.com 1/3 timed out -- no response within 5 seconds
[UTC Dec 22 14:10:16] error    : ICMP echo response for example.com 1/3 timed out -- no response within 5 seconds
[UTC Dec 22 15:24:19] error    : 'example.com' failed protocol test [HTTP] at INET[example.com:80] via TCP -- HTTP: Error receiving data -- Resource temporarily unavailable
[UTC Dec 22 15:57:15] error    : ICMP echo response for example.com 1/3 timed out -- no response within 5 seconds
[UTC Dec 22 17:00:57] error    : ICMP echo response for example.com 1/3 timed out -- no response within 5 seconds
[UTC Dec 22 17:49:00] error    : 'example.com' failed, cannot open a connection to INET[example.com:443/API] via TCPSSL

結論

このガイドを完了すると、Ubuntu14.04でLEMPスタックを監視するようにMonitが構成されているはずです。 Monitは非常に拡張性が高く、小規模および大規模ネットワークのあらゆる種類のサービスを監視するために簡単にカスタマイズまたは拡張できます。

以下は、Monitの追加リンクです。