文章目录
1. 引言2. 创建多个 tomcat 服务2.1 启动 tomcat 容器2.2 创建 tomcat 后端资源
3. 配置 nginx 负载均衡3.1 需改配置3.2 验证效果
4. 参考
1. 引言
承接上文 《docker 安装及配置 nginx + tomcat (一)》,如果 docker、nginx、tomcat 的环境配置没有准备好,请查看上篇。 本文通过 docker 创建多个 tomcat 服务器,利用 nginx 的反向代理挂载多个 tomcat 服务器,实现负载均衡。
2. 创建多个 tomcat 服务
2.1 启动 tomcat 容器
这里简单启动下,没有用挂载方式启动:
# 如果之前已经创建了 tomcat 的容器,则不用执行
docker run -d -p 8080:8080 --name tomcat tomcat:9.0
# 以下为新增的 tomcat 容器,tomcat1 及 tomcat2
docker run -d -p 8081:8080 --name tomcat1 tomcat:9.0
docker run -d -p 8082:8080 --name tomcat2 tomcat:9.0
2.2 创建 tomcat 后端资源
为了区分不同 tomcat 的服务器,访问 tomcat 服务器要求返回不同的结果。
进入 tomcat 容器中,创建资源
docker exec -it tomcat bash
在容器中创建 test.html 资源
cd webapps
mkdir test
cd test
echo "
tomcat!
" > test.html然后执行 exit 退出。
继续进入到 tomcat1,tomcat2 容器,其他步骤都一样,最后一句:
# 仅 tomcat1 执行
echo "
tomcat1!
" > test.html# 仅 tomcat2 执行
echo "
tomcat2!
" > test.html验证 tomcat 服务器 不同端口,同一路径,返回的结果不一样:
3. 配置 nginx 负载均衡
3.1 需改配置
上一篇文章介绍了将 nginx 以 volume 挂载方式启动容器,因此可以在本地目录中修改即可。
如果容器没有以 volume 挂载方式启动,修改会麻烦些(因为 nginx 没有 vi ),可以在本地修改完成后,然后 docker cp 到容器内。
我的配置挂载到 /root/nginx/conf/conf.d/default.conf,对应 nginx 容器的 /etc/nginx/conf.d/default.conf。修改 default.conf 配置如下:
# 新增
upstream testservers {
server 172.16.2.128:8080; # ip 选择你的实际主机 ip
server 172.16.2.128:8081;
server 172.16.2.128:8082;
}
server {
listen 80;
listen [::]:80;
server_name 172.16.2.128; # 对应主机 ip
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
proxy_pass http://testservers; # 新增一条规则匹配转发,testservers 对应 upstream 的 testservers 名字
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 /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
注意新增了 upstream 以及 在 location 中增加了 proxy_pass 。修改配置后,记得重启下 nginx:
docker exec -it nginx nginx -s reload
3.2 验证效果
可以看到是将流量随机分配到3台 tomcat 服务器上:
4. 参考
《nginx 视频学习》 《docker 安装及配置 nginx + tomcat(一)》
文章来源
发表评论