多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 网络链路 很多情况都是k8s集群使用的traefik是没有公网暴露面的。但是又想通过网络访问traefik服务,通常做法是traefik前面挂载一个lb服务将流量转发到traefik主机上。 网络链路: `客户端` --> `lb(一或多个)` --> `traefik` --> `后端业务程序` # 配置 >[info] 演示的后端业务程序是nginx。方便查看 `X-Forwarded-For` 以及 `X-Real-IP` > 客户端使用 `curl命令` 以及 `Google浏览器` 从上面的网络链路可知,需要配置的地方有两个。分别是 `lb` 以及 `traefik` 上。如果lb有多个的话,多个lb都需要配置的。 ## web(http)协议 >[info] 这里 lb 使用HTTP代理方式转发。 优点:网络链路清晰 缺点:效率没有四层转发快 ### lb配置 >[info] 该配置内容写在 `http{}` 块里面 ```conf upstream ingress_http { server 192.168.32.127:80; server 192.168.32.128:80; } server { listen 80; server_name _; location / { # 客户端域名赋值给Host请求头中传给下游服务器 proxy_set_header Host $http_host; # 将 $remote_addr(客户端IP地址) 赋值给 X-Real-IP 请求头中传给下游服务器 proxy_set_header X-Real-IP $remote_addr; # 将 $proxy_add_x_forwarded_for 赋值给 X-Forwarded-For 请求头中传给下游服务器 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://ingress_http; } } ``` ### traefik配置 >[info] 在traefik配置文件的 `entryPoints.web` 配置项下添加下面内容。IP写成 `lb` 地址。 ```yaml entryPoints: web: address: ":80" # 添加以下的内容 forwardedHeaders: trustedIPs: - "192.168.32.128" - "192.168.32.129" ``` ### 验证 curl 方法验证 ```shell curl -H "Host: nginx.ecloud.com" http://192.168.32.188 ``` 浏览器验证 ![](https://img.kancloud.cn/ef/17/ef17a65948956b5eec78f3eb4996c67d_1447x542.png) 查看后端业务nginx日志 ![](https://img.kancloud.cn/f2/09/f209151947031af3da855c6fadb50ac6_1901x282.png) ## webSecurity(https)协议 >[info] 这里 lb 使用TCP代理方式转发,目前使用 HTTP 代理没有成功过。 优点:效率高 缺点:只记录客户端IP及traefik地址,没有记录lb的IP地址 ### lb配置 >[info] 该配置内容写在 `stream{}` 块里面 ```conf upstream ingress_https { server 192.168.32.127:443 max_fails=3 fail_timeout=5s; server 192.168.32.128:443 max_fails=3 fail_timeout=5s; } server { listen 443; # 开启proxy_protocol协议。必须有该参数 proxy_protocol on; proxy_pass ingress_https; access_log /var/log/nginx/ingress_https_tcp_access.log proxy; error_log /var/log/nginx/ingress_https_error.log; } ``` ### traefik配置 >[info] 在traefik配置文件的 `entryPoints.webSecurity` 配置项下添加下面内容。IP写成 `lb` 地址。 ```yaml webSecurity: address: ":443" proxyProtocol: trustedIPs: - "192.168.32.128" - "192.168.32.129" ``` ### 验证 使用curl验证 ```shell curl -k -H "Host: nginx.ecloud.com" https://192.168.32.188 ``` 使用浏览器验证 ![](https://img.kancloud.cn/6a/83/6a8313c74d181d4b682a0e7b054b2769_1378x366.png) 查看后端业务nginx日志 ![](https://img.kancloud.cn/9a/4e/9a4e62279294f9479547c921c152c389_1893x184.png)