在 access_log 中记录 IPv6 地址,并解决 Elasticsearch 字段拆分问题
解读
国内生产环境已普遍开启 IPv6,但 Nginx 默认日志格式里 $remote_addr 在双栈监听时可能拿到的是 IPv4-mapped IPv6(如 ::ffff:192.0.2.1),直接落到 Elasticsearch 后会被默认分词器拆成 8 段,导致源 IP 检索、聚合、安全审计全部失真。面试官真正想看的是:
- 你能否让 Nginx 把“真实、干净、可检索”的 IPv6 写进日志;
- 你能否在日志链路上(Nginx → Filebeat/Logstash → Elasticsearch)用最少性能损耗解决字段拆分、IP 类型映射与检索精度问题;
- 你能否给出灰度、回滚、监控方案,保证线上流量入口“零中断”。
知识点
- Nginx 变量:proxy_protocol_addr、time_iso8601
- listen 指令:listen [::]:443 ipv6only=on|off、proxy_protocol
- log_format 转义:escape=json|none|default,防止 IPv6 冒号被 JSON 解析器误判
- Elasticsearch IP 字段:ip 类型需要“字符串且单值”,若被默认 text + keyword 多字段映射,冒号会被分词
- Ingest Pipeline / Logstash filter:mutate、grok、convert、ip 类型显式映射
- 热升级:nginx -s reopen 重新打开日志文件,配合 logrotate 的 copytruncate 与 dateext,实现毫秒级切割
- 高阶:使用 GeoIP2+MMDB 支持 IPv6 地理位置,避免 Elasticsearch 后期再 lookup
答案
-
Nginx 侧保证拿到真实 IPv6
a. 禁止 IPv4-mapped 地址:
listen [::]:80 ipv6only=on;
listen 80; # IPv4 独立监听
b. 若前面有四层 LB(如阿里 SLB、腾讯 CLB)开启 Proxy Protocol,则:
listen [::]:80 ipv6only=on proxy_protocol;
set_real_ip_from 2409:8c20::/32; # 云厂商 LB IPv6 段
real_ip_header proxy_protocol;
c. 自定义日志格式:
log_format access_json escape=json
'{"@timestamp":"time_iso8601",' '"client_ip":"remote_addr",' # 此时已是纯净 IPv6
'"status":status,' '"request":"request"}';
access_log /var/log/nginx/access.log access_json; -
日志采集侧禁止冒号拆词
Filebeat 示例:
processors:- script:
lang: javascript
source:
if (fields.client_ip.indexOf(':') !== -1) { fields.client_ip_v6 = fields.client_ip; }
output.logstash:
hosts: ["10.0.0.10:5044"]
Logstash 显式映射:
filter {
mutate { convert => { "client_ip" => "string" } }
}
output {
elasticsearch {
hosts => ["http://es-internal.node:9200"]
index => "nginx-access-%{+YYYY.MM.dd}"
template => "/etc/logstash/template/nginx.json"
template_overwrite => true
}
}
模板片段(nginx.json):
{
"mappings": {
"properties": {
"client_ip": { "type": "ip" }
}
}
} - script:
-
上线流程
- 预发环境:
nginx -t && nginx -s reload
curl -6 http://pre.domain 验证日志出现 240e:xx:xx 格式 - 灰度 5% 生产流量,观察 Elasticsearch 索引 mapping 冲突告警;
- 全量后,用 curator 删除旧索引,保证模板唯一;
- 监控:
- Grafana:rate(nginx_http_requests_total) by (client_ip) 看 IPv6 占比;
- Elasticsearch:查询 aggs { ip_range: { field: client_ip, ranges: [{mask:"240e::/32"}] } } 验证段分布。
- 预发环境:
拓展思考
- 如果客户端经过 CDN(阿里云 DCDN、腾讯云 ECDN),IPv6 地址在 X-Forwarded-For 最后一个段,需配置 real_ip_recursive on 并递归提取;同时要防止伪造,结合 CDN 提供的 AES 签名 token 做二次校验。
- 对超大规模集群(>10 万 QPS)可用 Nginx 的
$binary_remote_addr(16 字节固定长度)写日志,Filebeat 端用 Lua 脚本反解成文本,磁盘 I/O 降 30%。 - 安全合规:IPv6 地址属于用户个人信息,日志需脱敏存储。可在 Logstash 内做 anonymize 插件,保留 /48 前缀,其余置零,满足《个人信息保护法》最小可用原则。
- 零中断热升级:编译开启 --with-compat,使用 nginx -s reopen 瞬间重新打开 fd,配合 systemd 的 PrivateTmp=true,实现主程序升级而日志不丢行;回滚时直接还原旧模板并 rollover 索引即可。