# 使用 Monit 監控資源

安裝

```
apt install monit
```

設定

```bash
cp /etc/monit/monitrc /etc/monit/monitrc.bak
```

vi /etc/monit/monitrc

```
set httpd port 2812
    use address 0.0.0.0  # 只允全部訪問
    allow localhost      # 允許 localhost 訪問
    allow yourip         # 允許 指定IP 訪問
    allow admin:monit

# NGINX
check process nginx with pidfile /var/run/nginx.pid
  start program = "/bin/systemctl start nginx"
  stop program  = "/bin/systemctl stop nginx"
    if failed port 443 then restart
    if 5 restarts within 5 cycles then timeout

# PHP 7.4-FPM
check process php7.4-fpm with pidfile /run/php/php7.4-fpm.pid
    start program = "/etc/init.d/php7.4-fpm start"
    stop program = "/etc/init.d/php7.4-fpm stop"
    if failed unixsocket /var/run/php/php7.4-fpm.sock then restart
    if 5 restarts within 5 cycles then timeout

# MySQL
check process mysql with pidfile /var/lib/mysql/zfun-server.pid
    start program = "/etc/init.d/mysql start"
    stop program = "/etc/init.d/mysql stop"
    if failed host localhost port 3306 protocol mysql then restart
    if 5 restarts within 5 cycles then timeout
```

[http://yourip:2812](http://yourip:2812) 就能進入監控

如果希望在服務異常時接收電子郵件通知 vi /etc/monit/monitrc

```bash
set mailserver smtp.your-email-provider.com port 587
    username "your-email@example.com" password "your-password"
    using tlsv1
    with timeout 30 seconds

set alert your-email@example.com
```

<p class="callout danger">由於此功能的權限很大，可以做到關閉及啟用的功能，使用時務必要把防火牆等限制建置好</p>