快速部署Grafana日志监控+Nginx封禁IP

语言: CN / TW / HK

事情的起因还要从某天突然发现服务有明显异常的访问记录说起,虽然我这1核2鸡的小机器没什么攻击的价值,但也有了部署一套监控系统的想法。

↓ 这仅是免费CDN静态加速的记录。 2022/02/1645946288791.png

一番简单的调研之后,我发现主流的日志监控系统为ELK组合(Elasticsearch, Logstash, Kibana),还有Prometheus体系等,但这些相对而言有着较高学习成本与资源占用,适合复杂场景与企业级别使用,不太适合个人使用,于是最终我选择了曾经的老朋友Grafana作为基础快速搭建起轻量可扩展的日志监控系统。

Grafana本身支持多种数据对接,扩展性极高,本文不深入展开,所有监控指标围绕着Nginx,因为我的服务都是通过Nginx来代理端口的,所以日志的数据源由Nginx提供,但Nginx提供的log只是一个文本文件,我们要解析文本内的数据来进行分析,也可以解析转换为其他日志堆栈来获得更好的数据处理能力,这里我使用了Grafana团队自研的Loki来作为数据堆栈,Loki同时提供了一个代理服务,负责将日志进行解析和推送。

部署之后的默认界面展示,什么都没做的情况下这个界面也算有点味了: 2022/03/1647786549140.png

Docker环境

Docker官方自动脚本,运行后自动将Docker的稳定(stable)版本安装在系统中: shell curl -fsSL get.docker.com -o get-docker.sh sudo sh get-docker.sh --mirror Aliyun 配置镜像加速: mkdir -p /etc/docker tee /etc/docker/daemon.json <<-'EOF' { "registry-mirrors": ["http://kfwkfulq.mirror.aliyuncs.com"] } EOF sudo systemctl daemon-reload sudo systemctl start docker

Docker中国区官方 http://registry.docker-cn.com 网易 http://hub-mirror.c.163.com 阿里云 http://kfwkfulq.mirror.aliyuncs.com

Loki安装

找个不会常修改的目录下载所需配置文件,因为后面会映射到容器中 shell wget http://raw.githubusercontent.com/grafana/loki/v2.4.2/cmd/loki/loki-local-config.yaml -O loki-config.yaml Docker安装Loki shell docker run -d --name loki -u root -v $(pwd):/mnt/config -v /data/nginx-home/loki:/tmp/loki -v /etc/localtime:/etc/localtime -p 3002:3100 grafana/loki:2.4.2 -config.file=/mnt/config/loki-config.yaml 等待一会访问 http://xxxxxx:3002/ready 准备就绪

官网链接 - 安装 Grafana Loki

Grafana安装

shell docker run -d -p 3001:3000 -v /etc/localtime:/etc/localtime --name=grafana grafana/grafana 访问http://xxxxxx:3001,默认用户名密码admin,第一次初始化需要较长时间,之后直接点击配置一个数据源,点击Loki,配置好url点击底部的Save&test按钮。

2022/03/1647767452247.png

接着导入模板:12559(Nginx监控模板,更多模板访问官网2022/03/1647769105473.png

但是目前是没有数据的,需要将日志代理到Loki中。

Promtail安装

运行安装promtail

同样是找个目录先下载默认配置 wget http://raw.githubusercontent.com/grafana/loki/v2.4.2/clients/cmd/promtail/promtail-docker-config.yaml -O promtail-config.yaml 下载完后打开编辑修改配置: ``` server: http_listen_port: 0 grpc_listen_port: 0

positions: filename: /tmp/positions.yaml

clients: - url: http://xxxxxxx:3002/loki/api/v1/push # 修改为你的Loki服务推送地址

scrape_configs: - job_name: system static_configs: - targets: - localhost labels: job: nginx_access_log agent: promtail path: /usr/local/nginx/logs/host.access.log **注意`/data/nginx-home/extra/logs`修改你自己的nginx日志映射路径**: docker run -d --name promtail -v $(pwd):/mnt/config -v /etc/localtime:/etc/localtime -v /data/nginx-home/extra/logs:/usr/local/nginx/logs grafana/promtail:2.4.2 -config.file=/mnt/config/promtail-config.yaml ```

修改Nginx配置

``` log_format json_analytics '{' '"msec": "$msec", ' # request unixtime in seconds with a milliseconds resolution '"connection": "$connection", ' # connection serial number '"connection_requests": "$connection_requests", ' # number of requests made in connection '"pid": "$pid", ' # process pid '"request_id": "$request_id", ' # the unique request id '"request_length": "$request_length", ' # request length (including headers and body) '"remote_addr": "$remote_addr", ' # client IP '"remote_user": "$remote_user", ' # client HTTP username '"remote_port": "$remote_port", ' # client port '"time_local": "$time_local", ' '"time_iso8601": "$time_iso8601", ' # local time in the ISO 8601 standard format '"request": "$request", ' # full path no arguments if the request '"request_uri": "$request_uri", ' # full path and arguments if the request '"args": "$args", ' # args '"status": "$status", ' # response status code '"body_bytes_sent": "$body_bytes_sent", ' # the number of body bytes exclude headers sent to a client '"bytes_sent": "$bytes_sent", ' # the number of bytes sent to a client '"http_referer": "$http_referer", ' # HTTP referer '"http_user_agent": "$http_user_agent", ' # user agent '"http_x_forwarded_for": "$http_x_forwarded_for", ' # http_x_forwarded_for '"http_host": "$http_host", ' # the request Host: header '"server_name": "$server_name", ' # the name of the vhost serving the request '"request_time": "$request_time", ' # request processing time in seconds with msec resolution '"upstream": "$upstream_addr", ' # upstream backend server for proxied requests '"upstream_connect_time": "$upstream_connect_time", ' # upstream handshake time incl. TLS '"upstream_header_time": "$upstream_header_time", ' # time spent receiving upstream headers '"upstream_response_time": "$upstream_response_time", ' # time spend receiving upstream body '"upstream_response_length": "$upstream_response_length", ' # upstream response length '"upstream_cache_status": "$upstream_cache_status", ' # cache HIT/MISS where applicable '"ssl_protocol": "$ssl_protocol", ' # TLS protocol '"ssl_cipher": "$ssl_cipher", ' # TLS cipher '"scheme": "$scheme", ' # http or https '"request_method": "$request_method", ' # request method '"server_protocol": "$server_protocol", ' # request protocol, like HTTP/1.1 or HTTP/2.0 '"pipe": "$pipe", ' # "p" if request was pipelined, "." otherwise '"gzip_ratio": "$gzip_ratio", ' '"http_cf_ray": "$http_cf_ray"' '}';

access_log /etc/nginx/extra/logs/host.access.log json_analytics; ```

重启各个服务以应用配置

docker restart nginx docker restart loki docker restart promtail

之后便可以回到grafana中查看仪表盘里的数据了

日志清理

由于过去太久的日志信息并没有太大的价值,所以需要定时清理,否则很容易成为磁盘容量杀手,Loki 的设计目标是降低存储日志的成本,因此我认为保持其默认的删除策略即可(绝对不是因为懒得去看文档嗯),而nginx的日志文件则可以随意删除,避免累积太多。

首先创建一个auto_clear.sh文件: ```

!/bin/bash

rm -rf /data/nginx-home/extra/logs/host.access.log # 换成你的日志路径 docker restart nginx # 重启nginx,简单粗暴 打开计划任务 crontab -e 写入脚本每天凌晨4点自动运行 00 04 * * * /bin/bash /data/nginx-home/extra/logs/auto_clear.sh `wq`退出并刷新应用 service crond restart 查看计划任务: crontab -l ```

Nginx封禁IP

nginx封禁IP非常简单,先创建一个blackips.conf文件: ```

每一行代表一个黑名单IP

deny 1.2.3.4; deny 110.191.215.8; deny 110.191.214.214; 配置文件`nginx.conf`中的http对象中写入文件路径: include /etc/nginx/extra/blockips.conf; ```