一、准备工作
1.下载文件 apache-tomcat-8.5.59.tar.gz jdk-8u271-linux-x64.tar.gz
2.开放80、8080端口并拉取相关镜像
[root@Centos8 ~]# docker pull centos:latest nginx:latest tomcat:latest
二、建立相关目录树
[root@Centos8 ~]# mkdir ~/jvm
[root@Centos8 ~]# cat > ~/jvm/docker-compose.yml << EOF
>version: "3"
>services:
> nginx:
> image: nginx:latest
> restart: always
> ports:
> - 80:80
> links:
> -tomcat1:tomcat1
> -tomcat2:tomcat2
> volumes:
> - ./webserver:/webserver
> - ./nginx/nginx.conf:/etc/nginx/nginx.conf
> - ./etc/localtime:/etc/localtime
> depends_on:
> - tomcat1
> - tomcat2
> tomcat1:
> hostname: tomcat1
> build: ./tomcat
> volumes:
> - ./webserver/tomcatA:/usr/local/apache-tomcat-8.5.59/webapps/ROOT
> - ./etc/localtime:/etc/localtime
> tomcat2:
> hostname: tomcat2
> build: ./tomcat
> volumes:
> - ./webserver/tomcatB:/usr/local/apache-tomcat-8.5.59/webapps/ROOT
> - ./etc/localtime:/etc/localtime
>EOF
[root@Centos8 ~]# mkdir ~/jvm/etc
[root@Centos8 ~]# cp /etc/localtime ~/jvm/etc/
[root@Centos8 ~]# mkdir ~/jvm/nginx
[root@Centos8 ~]# cat > ~/jvm/nginx/nginx.conf << EOF
>worker_processes 1;
>events {
> worker_connections 1024;
>}
>http {
> upstream webserver { //开启负载均衡模块
> ip_hash; //固定ip负载
> server 172.19.0.3:8080 weight=2; //按权重均衡,地址为之后新建的两个tomcat容器ip
> server 172.19.0.4:8080 weight=8;
> }
> server {
> listen 80;
> server_name 127.0.0.1;
> location / {
> proxy_pass http://webserver;
> }
> }
>}
>EOF
[root@Centos8 ~]# mkdir ~/jvm/tomcat
[root@Centos8 ~]# cat > ~/jvm/tomcat/Dockerfile << EOF
>FROM centos:latest
>ADD jdk-8u271-linux-x64.tar.gz /usr/local
>ENV JAVA_HOME /usr/local/jdk1.8.0_271
>ADD apache-tomcat-8.5.59.tar.gz /usr/local
>EXPOSE 8080
>ENTRYPOINT ["/usr/local/apache-tomcat-8.5.59/bin/catalina.sh","run"]
>EOF
[root@Centos8 ~]# mkdir ~/jvm/webserver
[root@Centos8 ~]# cat > ~/jvm/webserver/tomcatA/index.jsp << EOF
>This is tomcat-A server.
>EOF
[root@Centos8 ~]# cat > ~/jvm/webserver/tomcatB/index.jsp << EOF
>This is tomcat-B server.
>EOF
最终目录树如下:
[root@Centos8 jvm]# tree
.
├── docker-compose.yml
├── etc
│ └── localtime
├── nginx
│ └── nginx.conf
├── tomcat
│ ├── apache-tomcat-8.5.59.tar.gz
│ ├── Dockerfile
│ └── jdk-8u271-linux-x64.tar.gz
└── webserver
├── tomcatA
│ └── index.jsp
└── tomcatB
└── index.jsp
三、docker-compose进行编排
[root@Centos8 jvm]# docker-compose up -d
查看容器启动情况
[root@Centos8 jvm]# docker-compose ps
包含jvm_nginx_1、jvm_tomcat1_1、jvm_tomcat2_1三个容器
查看容器ip
docker inspect | grep IPAddress jvm_tomcat1_1
四、测试负载均衡
[root@Centos8 jvm]# curl http://localhost