利用nginx和两个tomcat容器
nginx映射8181端口,tomcat分别映射9191和9292端口。
(关闭firewalld等服务。本机地址为192.168.200.104,docker私有仓库)
创建不同的主页来区分这两个tomcat容器。
[root@server ~]# echo "this tomcat1 port:9191" > tomcat1/index.html
[root@server ~]# echo "this tomcat2 port:9292" > tomcat2/index.html
[root@server ~]# cat tomcat1/index.html
this tomcat1 port:9191
[root@server ~]# cat tomcat2/index.html
this tomcat2 port:9292
配置nginx负载均衡器:(nginx默认端口80)
[root@server ~]# docker run -dit --name nginx -p 8181:80 192.168.200.104:5000/nginx:latest
98a219645301e873f8960277faace72303301b244f233f0bba5ee42ce2dfd573
复制nginx配置文件到宿主机:
[root@server ~]# docker cp nginx:/etc/nginx/nginx.conf .
在http{}下添加:upstream server项和server项。
[root@server ~]# cat 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 {
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;
upstream server{
server 192.168.200.104:9191;
server 192.168.200.104:9292;(负载均衡列表)
}
server {
listen 80;(nginx监控端口)
server_name 192.168.200.104;(接管的访问地址)
location / {
proxy_pass http://server;
root html;
index index.html index.htm;
}
}
}
将配置文件复制到nginx容器,然后重启容器:
[root@server ~]# docker cp nginx.conf nginx:/etc/nginx/
[root@server ~]# docker restart nginx
nginx
[root@server ~]# docker ps | grep nginx
98a219645301 192.168.200.104:5000/nginx:latest "nginx -g 'daemon off" 9 minutes ago Up 6 seconds 0.0.0.0:8181->80/tcp nginx
分别运行两个tomcat容器:(tomcat的默认端口是8080)
[root@server ~]# docker run -dit --name tomcat1 -v /root/tomcat1/:/usr/local/tomcat/webapps/ROOT -p 9191:8080 192.168.200.104:5000/tomcat:latest
b300bfea2a972c756062c03c9813781ce18579a7ba8a620d80cee9ddc3c37a38
[root@server ~]# docker exec -it tomcat1 bash
root@b300bfea2a97:/usr/local/tomcat# sh bin/startup.sh
Tomcat started.
[root@server ~]# docker run -dit --name tomcat2 -v /root/tomcat2/:/usr/local/tomcat/webapps/ROOT -p 9292:8080 192.168.200.104:5000/tomcat:latest
a681d7e3ea3b8f1b0f9c899a945fa43ea080d83c99f8ba61431e9f8fef1cef07
[root@server ~]# docker exec -it tomcat2 bash
root@a681d7e3ea3b:/usr/local/tomcat# sh bin/startup.sh
Tomcat started.
访问nginx端口(等容器完全启动后):
[root@server ~]# curl http://192.168.200.104:8181
this tomcat1 port:9191
[root@server ~]# curl http://192.168.200.104:8181
this tomcat2 port:9292
over!