Nginx監控安裝:Filebeat+ES+Grafana(全)

求關注

前言

本章將介紹Nginx監控安裝 javascript

Nginx監控安裝:Filebeat+ES+Grafana(全)

1. 安裝Nginx / OpenResty

1.1 安裝 OpenResty

VeryNginx 基於 OpenResty,因此你須要先安裝它:css

OpenResty安裝前準備html

  • Centos:yum install -y readline-devel pcre-devel openssl-devel gcc GeoIP-devel
  • Debian|Ubuntu:apt-get install libreadline-dev libncurses5-dev libpcre3-dev libssl-dev perl make build-essential libgeoip-dev
  • geoip-devel 爲geoip模塊所須要的基礎庫
●wget  https://openresty.org/download/openresty-1.11.2.1.tar.gz
●tar -zxvf openresty-1.11.2.1.tar.gz
●cd openresty-1.11.2.1
●./configure --with-luajit --with-pcre --with-http_gzip_static_module --with-http_realip_module --with-http_geoip_module --with-http_ssl_module --with-http_stub_status_module --prefix=/app/openresty
●make && make install
複製代碼

VeryNginx 實際使用到了 OpenResty 中的這些模塊java

  • lua-nginx-module
  • http_stub_status_module
  • lua-cjson library

若是你不想安裝 OpenResty,或者你已經有了一個正在工做的 Nginx,你也能夠本身手動爲 Nginx 編譯安裝這些模塊node

1.2 安裝部署 VeryNginx

克隆 VeryNginx 倉庫到本地, 複製 nginx.conf 和 VeryNginx 文件夾到 Nginx 的工做目錄.linux

cd ~
git clone https://github.com/alexazhou/VeryNginx.git
rm -f /app/openresty/nginx/conf/nginx.conf
cp ~/VeryNginx/nginx.conf /app/openresty/nginx/conf/nginx.conf
# 建立 /app/openresty/nginx/waf/verynginx 目錄
mkdir -p /app/openresty/nginx/waf/verynginx
# 把 /VeryNginx/verynginx 拷貝到 /app/openresty/nginx/waf/verynginx
cp -r ~/VeryNginx/verynginx /app/openresty/nginx/waf/verynginx

複製代碼

1.3 編輯 Nginx 配置文件

VeryNginx 項目提供了一個配置模版 /app/openresty/nginx/conf。你須要把本身站點的 Nginx 配置加到這個模版裏面。 可是記得不要修改配置 VeryNginx 的那部分代碼(除非你知道本身在幹啥 :smiling_imp: )。nginx

接下來,說明配置文件有三點比較重要:git

include /app/openresty/nginx/waf/verynginx/verynginx/nginx_conf/in_external.conf;
include /app/openresty/nginx/waf/verynginx/verynginx/nginx_conf/in_http_block.conf;

include /app/openresty/nginx/waf/verynginx/verynginx/nginx_conf/in_server_block.conf;
複製代碼

in_http_block.conf z合格配置文件須要修改github

upstream vn_upstream{
    server 127.0.0.1;
    balancer_by_lua_file /app/openresty/nginx/waf/verynginx/verynginx/lua_script/on_banlance.lua;
        keepalive 1024; #Connection pool
}

lua_package_path '/app/openresty/nginx/waf/verynginx/verynginx/lua_script/?.lua;;/app/openresty/nginx/waf/verynginx/verynginx/lua_script/module/?.lua;;';
lua_package_cpath '/app/openresty/nginx/waf/verynginx/verynginx/lua_script/?.so;;';
lua_code_cache on;

lua_shared_dict status 1m;
lua_shared_dict frequency_limit 10m;
lua_shared_dict summary_long 10m;
lua_shared_dict summary_short 10m;

init_by_lua_file /app/openresty/nginx/waf/verynginx/verynginx/lua_script/on_init.lua;
rewrite_by_lua_file /app/openresty/nginx/waf/verynginx/verynginx/lua_script/on_rewrite.lua;
access_by_lua_file /app/openresty/nginx/waf/verynginx/verynginx/lua_script/on_access.lua;
log_by_lua_file /app/openresty/nginx/waf/verynginx/verynginx/lua_script/on_log.lua;

複製代碼

其餘2個文件不要改變面試

配置 VeryNginx 的代碼是下面這部分:

#-----------------VeryNginx config code------------------
 #user nginx;
worker_processes  auto;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;


events {
    worker_connections  1024;
}

include /app/openresty/nginx/waf/verynginx/verynginx/nginx_conf/in_external.conf;
#include /app/openresty/nginx/waf/verynginx/nginx_conf/in_http_block.conf;
http {
    charset utf-8;
    sendfile     on;
    tcp_nopush   on;
    tcp_nodelay  on;
    server_tokens off;
    types_hash_max_size 2048;
    server_names_hash_bucket_size 128;
    large_client_header_buffers 4 32k;
    fastcgi_intercept_errors on;
    proxy_intercept_errors on;
    underscores_in_headers on;

    client_header_timeout      15s;
    client_body_timeout        15s;
    client_max_body_size      100m;
    client_body_buffer_size   2m;
    client_header_buffer_size 256k;

    #keepalive_timeout 0;
    keepalive_timeout  90s;
    keepalive_requests 2000;

    # MIME
    include       mime.types;
    default_type  application/octet-stream;
    #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 logs/access.log main;
    #tcp_nopush on;

    #keepalive_timeout 0;

    # gzip
    gzip               on;
    gzip_min_length    1k;
    gzip_buffers       4 16k;
    gzip_http_version  1.1;
    gzip_comp_level    6;
    gzip_types         text/plain text/css application/javascript application/x-javascript application/xml application/json;
    gzip_vary          on;

    proxy_connect_timeout    5s;
    proxy_read_timeout       1800s;
    proxy_send_timeout       1800s;
    proxy_buffer_size        128k;
    proxy_buffers            100 128k;
    #proxy_busy_buffers_size 1m;
    #proxy_temp_file_write_size 512k;

        #this line shoud be include in every http block
    include /app/openresty/nginx/waf/verynginx/verynginx/nginx_conf/in_http_block.conf;

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

    access_log  logs/access.log  main;


    upstream gateway_pool {
# 網關的地址
        server 106.12.129.14:9200;

    }



    server {
        listen       80;

        #this line shoud be include in every server block
        include /app/openresty/nginx/waf/verynginx/verynginx/nginx_conf/in_server_block.conf;
        #include /app/openresty/nginx/waf/verynginx/nginx_conf/in_http_block.conf;
        location / {
           proxy_http_version 1.1;
           proxy_set_header Connection "";
           proxy_redirect      off;
           proxy_set_header    X-Real-IP $remote_addr;
           proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header    X-Forwarded-Host $host;
           proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
           proxy_set_header    Host $host;
           proxy_pass http://gateway_pool;
        }
    }

}

#---------------VeryNginx config code end-----------------
複製代碼

若是不使用 VeryNginx 提供的配置模版,你也能夠手動把這部分加入到本身的 Nginx 配置文件中. (若是安裝路徑不是/app/openresty ,須要對 lua_package_cpath 和 lua_package_path 的值進行修改)

1.4 啓/停服務

啓動服務: /app/openresty/nginx/sbin/nginx

中止服務:/app/openresty/nginx/sbin/nginx -s stop

1.5 配置VeryNginx

打開瀏覽器訪問 http://127.0.0.1/VeryNginx/dashboard/index.html

默認用戶名和密碼:verynginx / verynginx 。

登陸以後就能夠查看狀態,並對配置進行修改了。修改配置後,記獲得 「配置 > 系統 > 所有配置」去保存.

提示

  • 經過 VeryNginx 控制面板保存新配置以後,會馬上生效,並不須要 restart/reload Nginx。

  • VeryNginx 把配置保存在 /app/openresty/nginx/waf/verynginx/configs/config.json 裏面。

  • 若是由於配錯了什麼選項,致使沒法登陸,能夠手動刪除 config.json 來清空配置。

已安裝成功openresty 能夠用網盤的覆蓋/app/openresty/nginx/waf目錄

連接:pan.baidu.com/s/1nt2SfrDt… 提取碼:g5hs

2. 安裝elasticsearch

wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.5.4.tar.gz
tar -zxvf  elasticsearch-6.5.4.tar.gz -C /usr/local/


useradd es
chown -R es:es /usr/local/elasticsearch-6.5.4/
cd /usr/local/elasticsearch-6.5.4
修改config/jvm.options爲內存的一半大小
vi config/jvm.options  
-Xms512m 
-Xmx512m
修改 max file 和 max virtual memory 參數
用root 或 sudo 用戶
vi /etc/sysctl.conf
添加下面配置:
vm.max_map_count=655360
並執行命令:
sysctl -p

配置端口 跨域
vi /usr/local/elasticsearch-6.5.4/config/elasticsearch.yml
cluster.name: elasticsearch
node.name: node-1
network.host: 0.0.0.0
http.port: 9200
node.max_local_storage_nodes: 2
http.cors.enabled: true
http.cors.allow-origin: "*"

切換es用戶
su - es
在Elasticsearch主目錄下運行下列命令來安裝這些插件:
bin/elasticsearch-plugin install ingest-geoip
bin/elasticsearch-plugin install ingest-user-agent

es用戶啓動
/usr/local/elasticsearch-6.5.4/bin/elasticsearch -d
root用戶啓動
su - es -c '/usr/local/elasticsearch-6.5.4/bin/elasticsearch -d'

複製代碼

2.1 windows 安裝elasticseach-head

  • 訪問 github.com/mobz/elasti… 下載 head 插件(選擇 zip 壓縮包下載方式)。

    下載 head 插件

  • 修改 ~\elasticsearch-6.6.2\elasticsearch-head-master\Gruntfile.js,在對應的位置加上 hostname:'*' 配置項。

    配置項

  • 在 ~\elasticsearch-6.6.2\elasticsearch-head-master 下執行 npm install 開始安裝,完成後可執行 grunt server 或者 npm run start 運行 head 插件。

    運行 head 插件

  • 安裝成功,訪問 http://localhost:9100/。

    訪問

2.2 注意事項

  • 在 head 中鏈接 ES 失敗。
    鏈接 ES 失敗

對於 Access-Control-Allow-Origin 的問題,能夠在 ElasticSearch 6.x 的 ~\config\elasticsearch.yml 文件的末尾加入如下代碼:

http.cors.enabled: true 
http.cors.allow-origin: "\*" 
node.master: true node.data: true
複製代碼

配置更新後,重啓 ES 便可鏈接成功。

3. 安裝Filebeat

推薦博客:www.cnblogs.com/cjsblog/p/9…

wget https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.5.4-linux-x86_64.tar.gz
tar -zxvf  filebeat-6.5.4-linux-x86_64.tar.gz  -C /usr/local/
cd /usr/local/
mv filebeat-6.5.4-linux-x86_64 filebeat-6.5.4
cd /usr/local/filebeat-6.5.4
vi filebeat.yml
複製代碼
filebeat.inputs:


- type: log

  enabled: false

  paths:
    - /app/openresty/nginx/logs/access.log


#============================= Filebeat modules ===============================

filebeat.config.modules:
  path: ${path.config}/modules.d/*.yml

  reload.enabled: false


setup.template.settings:
  index.number_of_shards: 3

setup.template.name: "nginx-log-"
setup.template.pattern: "nginx-log-*"
setup.template.overwrite: true





output.elasticsearch:
  enabled: true
  hosts: ["106.13.3.200:9200"]
  index: "nginx-log-%{+yyyy-MM-dd}"


#================================ Processors =====================================

# Configure processors to enhance or manipulate events generated by the beat.

processors:
  #- add_host_metadata: ~
  #- add_cloud_metadata: ~
  - drop_fields:
        fields: ["beat.name", "beat.version", "host.architecture","host.architecture","host.name","beat.hostname","log.file.path"]
複製代碼

3.1 啓用模塊nginx

cd /usr/local/filebeat-6.5.4/modules.d
vi  nginx.yml 

複製代碼

執行如下配置

- module: nginx
  # Access logs
  access:
    enabled: true

    # Set custom paths for the log files. If left empty,
    # Filebeat will choose the paths depending on your OS.
    var.paths: ["/app/openresty/nginx/logs/access.log"]

  # Error logs
  error:
    enabled: true

    # Set custom paths for the log files. If left empty,
    # Filebeat will choose the paths depending on your OS.
    var.paths: ["/app/openresty/nginx/logs/error.log"]
複製代碼

3.2 配置 default.json

cd /usr/local/filebeat-6.5.4/module/nginx/access/ingest vi default.json

{
  "description": "Pipeline for parsing Nginx access logs. Requires the geoip and user_agent plugins.",
  "processors": [{
    "grok": {
      "field": "message",
      "patterns":[
        "\"?%{IP_LIST:nginx.access.remote_ip_list} - %{DATA:nginx.access.user_name} \\[%{HTTPDATE:nginx.access.time}\\] \"%{GREEDYDATA:nginx.access.info}\" %{NUMBER:nginx.access.response_code} %{NUMBER:nginx.access.body_sent.bytes} \"%{DATA:nginx.access.referrer}\" \"%{DATA:nginx.access.agent}\" \"%{GREEDYDATA:nginx.access.xforwardedfor}\" %{GREEDYDATA:nginx.access.upstream_response_time} %{GREEDYDATA:nginx.access.upstream_addr}"
        ],
      "pattern_definitions": {
        "IP_LIST": "%{IP}(\"?,?\\s*%{IP})*"
      },
      "ignore_missing": true
    }
  }, {
    "grok": {
      "field": "nginx.access.info",
      "patterns": [
          "%{WORD:nginx.access.method} %{DATA:nginx.access.url} HTTP/%{NUMBER:nginx.access.http_version}",
          ""
      ],
      "ignore_missing": true
    }
  }, {
    "remove": {
      "field": "nginx.access.info"
    }
  }, {
    "split": {
      "field": "nginx.access.remote_ip_list",
      "separator": "\"?,?\\s+"
    }
  }, {
    "script": {
      "lang": "painless",
      "inline": "boolean isPrivate(def ip) { try { StringTokenizer tok = new StringTokenizer(ip, '.'); int firstByte = Integer.parseInt(tok.nextToken()); int secondByte = Integer.parseInt(tok.nextToken()); if (firstByte == 10) { return true; } if (firstByte == 192 && secondByte == 168) { return true; } if (firstByte == 172 && secondByte >= 16 && secondByte <= 31) { return true; } if (firstByte == 127) { return true; } return false; } catch (Exception e) { return false; } } def found = false; for (def item : ctx.nginx.access.remote_ip_list) { if (!isPrivate(item)) { ctx.nginx.access.remote_ip = item; found = true; break; } } if (!found) { ctx.nginx.access.remote_ip = ctx.nginx.access.remote_ip_list[0]; }"
      }
  }, {
    "remove":{
      "field": "message"
    }
  }, {
    "rename": {
      "field": "@timestamp",
      "target_field": "read_timestamp"
    }
  }, {
    "date": {
      "field": "nginx.access.time",
      "target_field": "@timestamp",
      "formats": ["dd/MMM/YYYY:H:m:s Z"]
    }
  },{
    "remove": {
      "field": "nginx.access.time"
    }
  }, {
    "user_agent": {
      "field": "nginx.access.agent",
      "target_field": "nginx.access.user_agent"
    }
  }, {
    "rename": {
      "field": "nginx.access.agent",
      "target_field": "nginx.access.user_agent.original"
    }
  }, {
    "geoip": {
      "field": "nginx.access.remote_ip",
      "target_field": "nginx.access.geoip"
    }
  }, {
    "script": {
      "lang": "painless",
      "inline": "String tmp=ctx.nginx.access.upstream_response_time; if (tmp=='-'){ctx.nginx.access.upstream_response_time=-1.0}else{ctx.nginx.access.upstream_response_time=Float.parseFloat(tmp)}"
      }
  }],
  "on_failure" : [{
    "set" : {
      "field" : "error.message",
      "value" : "{{ _ingest.on_failure_message }}"
    }
  }]
}
複製代碼

cd /usr/local/filebeat-6.5.4 nohup ./filebeat -e -c filebeat.yml >&/dev/null &

4. 安裝Grafana

4.1 安裝步驟

wget https://dl.grafana.com/oss/release/grafana-6.1.6.linux-amd64.tar.gz
tar -zxvf grafana-6.1.6.linux-amd64.tar.gz
cd /app/grafana-6.1.6/bin
grafana-cli plugins install grafana-piechart-panel
grafana-cli plugins install grafana-piechart-panel
grafana-cli plugins install grafana-worldmap-panel
grafana-cli plugins install grafana-piechart-panel
grafana-cli plugins install grafana-piechart-panel

./grafana-server 
複製代碼

4.1.1 Grafana配置

默認安裝3000端口,這裏地址爲:106.13.3.200:3000 默認用戶名/密碼 admin/admin

4.1.1 配置數據源

配置數據源

4.1.2 json模板

因爲Json模板過長,另存入百度網盤中。歡迎關注我的公衆號Coder編程,後臺回覆:Grafana導入Json模板。便可獲取。 若有失效,麻煩私信公衆號。看到後,我會及時回覆。

4.1.3 導入nginx dashboard

導入jsonFile
Json模板

查看結果

劃重點

以上來自開源項目OCP: gitee.com/owenwangwen…

項目演示地址 http://59.110.164.254:8066/login.html 用戶名/密碼:admin/admin

項目監控 http://106.13.3.200:3000 用戶名/密碼:admin/1q2w3e4r

項目代碼地址 gitee.com/owenwangwen…

羣號:483725710(備註:Coder編程)歡迎你們加入~

文末

歡迎關注我的微信公衆號:Coder編程 獲取最新原創技術文章和免費學習資料,更有大量精品思惟導圖、面試資料、PMP備考資料等你來領,方便你隨時隨地學習技術知識!

歡迎關注並star~

微信公衆號
相關文章
相關標籤/搜索