有时,虽然我们搭建了测试服务器,也可以模拟流量来对服务器进行测试,但是真实的线上流量还是会很难完全模拟。这时候我们就可以使用nginx的mirror模块,可以把线上的实时流量复制到测试环境中,来更真实地测试服务器。可以实现版本的预先测试,或者流量放大后进行压测等功能。

配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
server {
    listen  80;

    location / {
        root   /opt/docker_dir/nginx/html/demo;
        index  index.html index.htm;
    }

    location ^~ /api/v1{
        proxy_pass http://127.0.0.1:18080;
        
        mirror /mirror; #指定镜像的url
        mirror_request_body on; #是否镜像请求body部分
    
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # 镜像站点配置
    location /mirror {
        internal; #设置这个location为内部配置,外部的调用请求会返回404
        proxy_pass http://127.0.0.1:28080$request_uri; #指定将镜像数据发送到哪
        proxy_pass_request_body on; # Indicates whether the original request body is passed to the proxied server. default value is on
        proxy_set_header X-Original-URI $request_uri; # reset uri
    }
}

注意

  • mirror的返回nginx收到之后会丢弃,不会转发给客户端,所以对真实环境中的用户使用不会有影响