Prometheus 是一個開源的監控系統,Nginx 是一款開源的高性能 Web 服務器。此篇文章將詳細介紹如何使用 Prometheus 監控 Nginx 的運行狀態,主要包括以下幾個方面。
一、安裝 Prometheus
首先需要安裝並啟動 Prometheus,可參考以下代碼:
cd /opt/
wget https://github.com/prometheus/prometheus/releases/download/v2.22.0/prometheus-2.22.0.linux-amd64.tar.gz
tar -zxvf prometheus-2.22.0.linux-amd64.tar.gz
cd prometheus-2.22.0.linux-amd64/
./prometheus --config.file=prometheus.yml
其中 prometheus.yml 文件是配置文件,用來定義哪些服務和指標需要被監控。這裡只需要關注 Nginx,因此只需要在 prometheus.yml 中添加以下內容:
- job_name: 'nginx'
scrape_interval: 5s
metrics_path: /nginx_status
static_configs:
- targets: ['localhost:80']
上述代碼定義了監控 Nginx,其中 job_name 是一個自定義的名稱,scrape_interval 是採集數據的時間間隔,metrics_path 是 Nginx 的狀態數據地址,static_configs 是 Nginx 的 IP 和端口。
二、配置 Nginx
為了能夠監控 Nginx,需要在 Nginx 的配置文件中增加以下代碼:
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
這段代碼主要是定義了狀態數據的接口地址為 /nginx_status,每次訪問該地址都會返回一份包含當前狀態信息的文本內容。
三、安裝 Nginx Exporter
Nginx Exporter 是一個 Prometheus 的擴展,用於採集 Nginx 的基本指標信息。可以通過以下命令進行安裝:
wget https://github.com/nginxinc/nginx-prometheus-exporter/releases/download/v0.8.0/nginx-prometheus-exporter-0.8.0-linux-amd64.tar.gz
tar -zxvf nginx-prometheus-exporter-0.8.0-linux-amd64.tar.gz
cd nginx-prometheus-exporter-0.8.0-linux-amd64/
./nginx-prometheus-exporter
啟動 Nginx Exporter 後,可以通過 http://localhost:9113/metrics 訪問其提供的監控信息。
四、配置 Prometheus
為了將 Nginx Exporter 的監控信息集成到 Prometheus 中,需要在 prometheus.yml 中添加以下內容:
- job_name: nginx-exporter
scrape_interval: 5s
static_configs:
- targets: ['localhost:9113']
上述代碼定義了一個名為 nginx-exporter 的 job,每 5 秒鐘採集一次 Nginx Exporter 的數據。
五、查詢指標
通過 Prometheus 提供的 Web 界面,可以輕鬆地查詢 Nginx 的各項指標信息。例如,可以查詢 Nginx 的請求數、響應時間等信息,以便及時發現和解決問題。
查詢 Nginx 的請求數,可以使用以下 PromQL 表達式:
nginx_http_requests_total
查詢 Nginx 的響應時間,可以使用以下 PromQL 表達式:
nginx_http_request_duration_seconds
六、總結
通過上述步驟,我們已經學習了如何使用 Prometheus 監控 Nginx 的運行狀態。通過監控 Nginx 的各項指標信息,可以及時發現和解決問題,保障系統的穩定性和可靠性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/197960.html