测试Nginx跨运营商负载均衡配置

1、拓扑图

2、Nginx配置:

# cat  /etc/nginx/conf.d/www.conf 

server {
listen 80;
server_name 116.63.184.96; # 可以绑定域名

location / {
    proxy_pass  http://127.0.0.1:8000;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    proxy_set_header        Accept-Encoding   "";
    proxy_set_header        Host            $host;
    proxy_set_header        X-Real-IP       $remote_addr;
    proxy_set_header        X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}


upstream mysvr {
    server 199.247.16.38:9999;
    server 45.63.91.241:9999;
    ip_hash;
}
server {
    listen 8000;
    server_name 127.0.0.1;

    location / { # 斜杠(/)代表根目录
        proxy_pass http://mysvr; #//转发地址
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_connect_timeout 1;
        proxy_read_timeout 1;
        proxy_send_timeout 1;
    }
}

3、测试负载均衡节点的Web服务器

3.1、简易Web 服务器代码:

cat /opt/shttp.py

import socket

HOST, PORT = '', 9999

listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print('Serving HTTP on port %s ...' % PORT)
while True:
    client_connection, client_address = listen_socket.accept()
    request = client_connection.recv(1024)

    a = request.decode("utf-8")
    alist = a.split('\r\n')
    YouIP=''
    Host=''
    for i in alist:
        j = i.split(":")
        if j[0] =='Host':
            Host = "\nNginx Server IP:" + j[1].strip()
        if j[0] =='X-Forwarded-For':
            temp = j[1].split(',')[0].strip()
            YouIP = "\nYour IP:" + temp

    http_response = """\
HTTP/1.1 200 OK

Hello, World!
Node IP: 199.247.16.38
"""
    result = http_response + Host + YouIP
    client_connection.sendall(result.encode("utf-8"))
    client_connection.close()

3.2、后台运行简易Web Server:

nohup python shttp.py 2>&1 &

4、测试:

URL:

http://116.63.184.96/

第1次访问:

第2次访问(刷新):

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注