实验:一台服务器上安装nginx,并在该服务器上启用两个docker进程模拟负载均衡
1、安装nginx

# rpm -vih http://nginx.org/packages/rhel/7/x86_64/RPMS/nginx-1.16.0-1.el7.ngx.x86_64.rpm

2、安装docker
二进制包下载地址:https://download.docker.com/linux/static/stable/x86_64/

#tar zxvf docker-18.09.6.tgz
mkdir /etc/docker
# mv docker/* /usr/bin
# mkdir /etc/docker
# mv daemon.json /etc/docker
# mv docker.service /usr/lib/systemd/system
# systemctl start docker
# systemctl enable docker

2.1daemon.json文件内容

 {
    "registry-mirrors": ["http://bc437cce.m.daocloud.io"]
}

2.2docker.service文件内容

 [Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service containerd.service
Wants=network-online.target

[Service]
Type=notify
ExecStart=/usr/bin/dockerd
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always
StartLimitBurst=3
StartLimitInterval=60s
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
Delegate=yes
KillMode=process

[Install]
WantedBy=multi-user.target

拉取tomcat的docker镜像并启动两个docker进程

# doker pull tomcat
#docker run --name tomcat1 -p 8081:8080 -v /data/tomcat1/webapps1:/usr/local/tomcat/webapps -d tomcat
#docker run --name tomcat2 -p 8082:8080 -v /data/tomcat1/webapps1:/usr/local/tomcat/webapps -d tomcat
#docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
284264b13148        tomcat              "catalina.sh run"   2 hours ago         Up 2 hours          0.0.0.0:8081->8080/tcp   tomcat1
a96d092ce945        tomcat              "catalina.sh run"   17 hours ago        Up 2 hours          0.0.0.0:8082->8080/tcp   tomcat

注意:pull下来的tomcat的webapps目录是空目录,需要自定义index.html文件内容,否则访问会报错404
我分别填写的内容是tomcat1 和tomcat2

配置nginx
进入nginx配置文件目录并新建zs.conf文件,文件名自定义。将以下内容添加进去即可

# cd /etc/nginx/conf.d/
vi zs.conf
upstream localhost{
        server 192.168.100.216:8081 weight=1;
        server 192.168.100.216:8082 weight=1;
        }
server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
        proxy_pass   http://localhost;
       }
}

upstream后面的名称要与 proxy_pass后面的名称保持一致。server_name可以在本地添加host将IP解析成任意域名。
这样做的目的是方便管理,一个文件对应一个应用。需要添加其他应用的负载均衡的时候直接在该目录新建一个.conf。要停掉某个应用的负载的时候直接删除该.conf即可。

重启nginx
#systemctl restart nginx

浏览器访问http://192.168.100.216