专业的编程技术博客社区

网站首页 > 博客文章 正文

nginx配置http和tcp服务负载均衡

baijin 2024-12-19 10:12:34 博客文章 9 ℃ 0 评论

nginx是一个高性能的HTTP反向代理web服务器,通过它的反向代理功能,可以实现负载均衡

http服务负载均衡

例如有两个tomcat服务:127.0.0.1:8080/test,127.0.0.1:8081/test,需要做负载均衡,我们在它的http模块中,可以这样配置

http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    #配置做负载均衡的应用服务地址,注意名字 testserver 不要带下划线_,不然访问时会报错
    upstream testserver{
        server  127.0.0.1:8080;
        server  127.0.0.1:8081;
    }

    server {
        listen       80;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        location /test {
            root   html;
            proxy_pass  http://testserver/test;
            proxy_redirect default;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

tcp服务负载均衡

例如有两个netty提供的tcp socket服务:127.0.0.1:8800,127.0.0.1:8801,需要做负载均衡,nginx监听8000端口,并对外提供服务,客户端连接8000端口,这样我们在它的stream模块中,可以这样配置

stream {
   upstream nettyserver {
        server  127.0.0.1:8800;
        server  127.0.0.1:8801;
   }
   server {
        listen       8000;
        proxy_pass   nettyserver;
   }
}


好了,通过以上配置,就可以愉快使用nginx做负载均衡了,也来试试吧!

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表