docker上配置nginx负载均衡

Posted supertonny

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了docker上配置nginx负载均衡相关的知识,希望对你有一定的参考价值。

采用ubuntu系统,docker安装自行百度

1.安装tomcat

docker run -d -p 8088:8080 tomcat
docker run -d -p 8089:8080 tomcat

安装两个实例,端口分别为8088,8089

2.安装nginx

docker run -p 8080:80 -d docker.io/nginx

安装nginx,端口为8080。在测试的过程中,发现ubuntu上对80端口有限制,不能直接访问,所以映射为8080

3.修改nginx配置

3.1查看实例

    sudo docker ps
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
    516b1562b0e3        nginx               "nginx -g ‘daemon of…"   21 minutes ago      Up 2 minutes        0.0.0.0:8080->80/tcp                musing_dewdney
    36e48585253f        tomcat              "catalina.sh run"        About an hour ago   Up About an hour    0.0.0.0:8089->8080/tcp              keen_wescoff
    7eb77e6a33e5        tomcat              "catalina.sh run"        About an hour ago   Up About an hour    0.0.0.0:8088->8080/tcp              frosty_grothendieck
    2069f54ea331        mysql:5.7           "docker-entrypoint.s…"   3 hours ago         Up 3 hours          0.0.0.0:3306->3306/tcp, 33060/tcp   mysqltest

3.2进入nginx的bash

sudo docker exec -it 516b1562b0e3 bash

3.3修改配置

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


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

    proxy_buffer_size 128k;
    proxy_buffers 32 128k;
    proxy_busy_buffers_size 128k;


    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    # 注意,这里的server名字即org.tonny.balance不能带下划线,tomcat是上面安装的tomcat
    upstream org.tonny.balance {
        server 192.168.126.128:8088 weight=1;
        server 192.168.126.128:8089 weight=1;
    }

    server {
        #注意,这里保留80,因为前面的docker运行命令,会映射80端口
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        # 不带数据的请求
        location / {
            root   html;
            index  index.html index.htm;
            #访问映射
            proxy_pass   http://org.tonny.balance; 
        }

        #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;
        }
    }
}

3.4重启nginx

sudo docker restart 516b1562b0e3

4.测试

通过ip,端口访问即可

以上是关于docker上配置nginx负载均衡的主要内容,如果未能解决你的问题,请参考以下文章

Docker 安装 Nginx 负载均衡配置

nginx安装部署+负载均衡+动静分离配置

用docker搭建nginx负载均衡测试环境

Nginx负载均衡配置

nginx+docker负载均衡

nginx+docker负载均衡