ubuntu

ubuntu nginx如何监控与日志分析

小樊
44
2025-07-24 08:22:21
栏目: 智能运维

在Ubuntu上使用Nginx进行监控和日志分析,可以通过以下几个步骤来实现:

1. 日志配置

首先,确保Nginx的日志配置正确。默认情况下,Nginx会在/var/log/nginx/目录下生成访问日志和错误日志。

你可以在/etc/nginx/nginx.conf或相应的虚拟主机配置文件中调整日志格式和级别。

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log debug;
}

2. 日志轮转

为了避免日志文件过大,可以使用logrotate工具来管理日志文件的轮转。

创建或编辑/etc/logrotate.d/nginx文件:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 7
    compress
    notifempty
    create 0640 www-data adm
}

3. 监控Nginx状态

Nginx提供了一个内置的状态模块,可以通过访问http://your_server/nginx_status来获取Nginx的实时状态。

首先,确保在nginx.conf中启用了状态模块:

server {
    listen 80;
    server_name localhost;

    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;  # 限制访问IP
        deny all;
    }
}

然后,你可以使用curl命令来获取状态信息:

curl http://localhost/nginx_status

4. 使用第三方监控工具

为了更方便地进行监控和分析,可以使用一些第三方工具,如Prometheus和Grafana。

安装Prometheus和Grafana

  1. 安装Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
tar xvfz prometheus-2.30.3.linux-amd64.tar.gz
cd prometheus-2.30.3.linux-amd64
./prometheus --config.file=prometheus.yml
  1. 安装Grafana
sudo apt update
sudo apt install -y software-properties-common wget
wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -
sudo add-apt-repository "deb https://packages.grafana.com/oss/deb stable main"
sudo apt update
sudo apt install grafana

配置Prometheus监控Nginx

编辑prometheus.yml文件,添加Nginx的监控配置:

scrape_configs:
  - job_name: 'nginx'
    static_configs:
      - targets: ['localhost:9113']

启动Prometheus并访问http://localhost:9090,你应该能看到Nginx的监控数据。

配置Grafana显示Nginx监控数据

  1. 启动Grafana并访问http://localhost:3000

  2. 添加Prometheus数据源:

    • 点击左侧菜单的齿轮图标,选择“Data Sources”。
    • 点击“Add data source”,选择“Prometheus”。
    • 输入URL:http://localhost:9090,点击“Save & Test”。
  3. 创建一个新的Dashboard并添加Nginx监控面板:

    • 点击左侧菜单的“+”图标,选择“Dashboard”。
    • 点击“Add new panel”。
    • 在查询部分输入Prometheus的查询语句,例如:
      rate(nginx_access_requests_total[5m])
      
    • 点击“Apply”保存面板。

通过以上步骤,你可以在Ubuntu上实现对Nginx的监控和日志分析。

0
看了该问题的人还看了