百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

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

off999 2025-01-31 14:40 14 浏览 0 评论

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

↓ 这仅是免费CDN静态加速的记录。

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

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

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

Docker环境

Docker官方自动脚本,运行后自动将Docker的稳定(stable)版本安装在系统中:

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": ["https://kfwkfulq.mirror.aliyuncs.com"]
}
EOF
复制代码
sudo systemctl daemon-reload
sudo systemctl start docker
复制代码

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

Loki安装

找个不会常修改的目录下载所需配置文件,因为后面会映射到容器中

wget https://raw.githubusercontent.com/grafana/loki/v2.4.2/cmd/loki/loki-local-config.yaml -O loki-config.yaml
复制代码

Docker安装Loki

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安装

docker run -d -p 3001:3000 -v /etc/localtime:/etc/localtime --name=grafana grafana/grafana
复制代码

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

接着导入模板:12559(Nginx监控模板,更多模板访问官网)

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

Promtail安装

运行安装promtail

同样是找个目录先下载默认配置

wget https://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;

相关推荐

咱村里有个老爷子,居然自学起了Python编程

咱村里有个老爷子,没什么文化,居然自学起了Python编程,还搞出个“智能喂鸡系统”,这事儿可把整个村子都惊到了。要说这老爷子,平时就爱琢磨些新鲜玩意儿。一开始,大家还以为他是瞎折腾,毕竟都一把年纪了...

真上头!清华打造的最全Python教程,通俗易懂,学不会我退出IT圈

前言随着人工智能的发展,Python近两年也是大火,越来越多的人加入到Python学习大军,对于毫无基础的人该如何入门Python呢?小编这里整理了一套python编程零基础自学教程,清华大佬196小...

如何学好Python技术(怎么才能学会python)

现在python发展势头很猛,都想快速学好它,其实学任何一个语言没有太多好的秘诀,一般情况下,还是少不了你努力刻苦的样子。学好一门技术并不容易,很多人推荐学习python,在于比其他语言的约束,或者...

如何高效且系统地自学Python?(自己学python怎么学)

关于这个问题,我也算有些话语权吧!5年多经验的我,今天和大家分享一套系统性学习Python的方法,几周内系统性地学会Python并不是啥难事!首先,学习Python确立明确的学习目标至关重要。要系统性...

使用 Python 监控文件系统(基于python的监控系统)

前言在我们使用服务器的时候,有时候需要监控文件或文件夹的变化。例如,定期扫描文件夹下是否有某一类型的文件生成。今天,我们介绍如何使用Python来监控文件系统。在Python中,主要有两个监控...

Python文件读写最佳实践:关键操作的异常处理

在Python中进行文件操作时,合理的异常处理是保证程序健壮性的关键。以下是针对文件操作异常处理的全面指南。一、为什么需要异常处理?文件操作可能失败的常见原因:文件不存在(FileNotFoundEr...

Python编程笔记(python编程入门与案例详解)

1.Python简介Python是一种解释型、高级和通用的编程语言。它通过显著的缩进使用来强调代码的可读性。#HelloWorldprogramprint("Hello,World...

Python目录与文件操作教程(python word目录)

大家好,我是ICodeWR。今天要记录的是如何使用Python进行常见的目录和文件操作。Python提供了强大的内置模块来处理文件和目录操作。1.基本模块介绍Python中主要使用以下模块进行文件...

自动创建 Python 的 requirements.txt 文件

技术背景在Python开发中,requirements.txt文件用于记录项目所依赖的第三方库及其版本,方便在不同环境中部署项目。然而,当从GitHub下载Python源代码时,有时会缺...

Python文件操作指南(python 操作文件)

一、核心函数open()精解基本语法open(file,mode='r',encoding=None,errors=None,newline=None)关键参数解析1.f...

Python 实现从文本文件提取数据并分析保存

一、引言在日常的数据处理工作中,我们经常会遇到从文本文件中提取特定信息并进行分析的需求。本文将详细介绍如何使用Python编写代码,从一个包含用户网络使用信息的文本文件中提取用户姓名、入站流量和出...

22-3-Python高级特性-上下文管理器

4-上下文管理器4-1-概念上下文管理器是一种实现了`__enter__()`和`__exit__()`方法的对象;用于管理资源的生命周期,如文件的打开和关闭、数据库连接的建立和断开等。使用...

python:最简单爬虫之使用Scrapy框架爬取小说

python爬虫框架中,最简单的就是Scrapy框架。执行几个命令就能生成爬虫所需的项目文件,我们只需要在对应文件中调整代码,就能实现整套的爬虫功能。以下在开发工具PyCharm中用简单的Demo项目...

Python爬取小说技术指南(python爬取文章)

在Python中爬取小说需要遵循法律法规和网站的服务条款,请确保你有权获取目标内容。以下是使用Python爬取小说的通用技术流程安装依赖库pipinstallrequestsbeauti...

python原始套接字socket下载http网页文件到txt

python原始套接字socket下载http网页文件到txtimportsocketdefdownload_webpage(url,output_file):try:...

取消回复欢迎 发表评论: