Docker下Nginx+Tomcat实现负载均衡

本文介绍在Docker上配置负载均衡,启动一个nginx容器,三个tomcat容器。

结构如下:

Docker下Nginx+Tomcat实现负载均衡_第1张图片

配置步骤

1.在宿主机上安装docker并启动,请参照Centos7安装Docker最新版

2.拉取nginx、tomcat镜像,默认拉取最新的

docker pull tomcat
docker pull nginx

3.启动tomcat镜像并创建新首页

docker run -d -p 8081:8080 --name tomcat1 tomcat
docker run -d -p 8082:8080 --name tomcat2 tomcat
docker run -d -p 8083:8080 --name tomcat3 tomcat

配置新首页

vi index.jsp

this is tomcat1

三个容器分别执行

docker cp index.jsp tomcat1:/usr/local/tomcat/webapps/ROOT/index.jsp
docker cp index.jsp tomcat2:/usr/local/tomcat/webapps/ROOT/index.jsp
docker cp index.jsp tomcat3:/usr/local/tomcat/webapps/ROOT/index.jsp

4.准备nginx.conf配置文件

user  nginx;
worker_processes  1;
 
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
 
 
events {
    worker_connections  1024;
}
 
 
http {
 
    server {
                listen 80;
                location  / {
                        proxy_pass http://blance;
                }
        }
 
    upstream blance{
            server 192.168.0.130:8081;
            server 192.168.0.130:8082;
            server 192.168.0.130:8083;
    }
 
    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;
 
    include /etc/nginx/conf.d/*.conf;
}

其中一下为默认配置新增部分

    server {
                listen 80;
                location  / {
                        proxy_pass http://blance;
                }
        }
 
    upstream blance{
            server 192.168.0.130:8081;
            server 192.168.0.130:8082;
            server 192.168.0.130:8083;
    }

5.启动nginx容器

docker run -p 82:80 --name nginx1 -v /src/nginx/nginx.conf:/etc/nginx/nginx.conf -d nginx

6.检查上述容器是否正常启动,并关闭防火墙或者开启82、8081、8082、8083端口

7.测试

如上述都正确配置,即可进行测试

[root@kube-master ~]# while true; do wget -O - -q http://192.168.0.130:82;sleep 3; done
this is tomcat3
this is tomcat2
this is tomcat1
this is tomcat3
this is tomcat2

出现如上,说明设置成功。

你可能感兴趣的:(Docker,负载均衡与高可用)