后台程序负载均衡(Nginx)

in Linux with 0 comment

后台程序负载均衡

nginx是性能非常出色的反向代理服务器,最大可以支持8万/秒的并发访问

安装nginx镜像

docker pull nginx

docker run -it -d –name nginx1 -v /home/nginx1/nginx.conf:/etc/nginx/nginx.conf --net=host --privileged ninx

编写nginx配置文件:


user  nginx;
worker_processes  1;

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
worker_connections 1024;
}

http {
include /etc/nginx/mime.types;
default_type application/octet-stream;

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

access_log  /var/log/nginx/access.log  main;

sendfile        on;
#tcp_nopush     on;

keepalive_timeout  65;

#gzip  on;

proxy_redirect          off;
proxy_set_header        Host $host;
proxy_set_header        X-Real-IP $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size    10m;
client_body_buffer_size   128k;
proxy_connect_timeout   5s;
proxy_send_timeout      5s;
proxy_read_timeout      5s;
proxy_buffer_size        4k;
proxy_buffers           4 32k;
proxy_busy_buffers_size  64k;
proxy_temp_file_write_size 64k;

upstream tomcat {
	server 192.168.99.104:6001;
	server 192.168.99.104:6002;
	server 192.168.99.104:6003;
}
server {
    listen       6101;
    server_name  192.168.99.104; 
    location / {  
        proxy_pass   http://tomcat;
        index  index.html index.htm;  
    }  

}

}

nginx双击负载需要创建两个nginx配置文件,启动两个容器

image-20200418142933539

nginx容器内安装keepalived负载均衡:

docker exec -it nginx1 bash

apt-get update

apt-get install keepalived

安装完成后:

docker exec -it n1 bash

vi /etc/keepalived/keepalived.conf

vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 123456
    }
    virtual_ipaddress {
        192.168.99.151
    }
}
virtual_server 192.168.99.151 6201 {
    delay_loop 3
    lb_algo rr
    lb_kind NAT
    persistence_timeout 50
    protocol TCP
    real_server 192.168.99.104 6101 {
        weight 1
    }
}

service keepalived start

检测是否成功 ping 192.168.99.151