Day-08 基于 Docker安装 Nginx 镜像-负载均衡

1、反向代理后,自然而然就引出了负载均衡,下面简单实现负载均衡的效果;

2、实现该效果需要再添加一个 Nginx ,所以要增加一个文件夹。

bash 复制代码
/home
    |---mutou
           |----nginx
                  |----conf.d
                  |----html
                  |----conf.d2
                  |----html3

1.创建 html3 文件夹, 新建 index.html、index-test.html 文件

bash 复制代码
cd html3/
vi index.html
vi index-test.html

index.html、index-test.html 代码如下

html 复制代码
<html>
  <body>
    <h2>it is html3</h2>
  </body>
</html>

2. 修改 home/mutou/nginx/conf.d/default.conf 配置文件

bash 复制代码
vi defaul.conf

修改内容如下:

bash 复制代码
server {
    listen       80;
    server_name  localhost;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    location /demo {
       try_files $uri $uri/ /index-test.html;
    }
}

3. 重启 Docker 镜像

此时,查看所有运行中的docker容器

bash 复制代码
docker ps

然后重启该停止:

bash 复制代码
docker restart 容器id

4. 启动新容器, 挂载配置文件

ps: 端口为 8081 、 8080

bash 复制代码
docker run -d -p 8081:80 -v /home/mutou/nginx/conf.d:/etc/nginx/conf.d  -v /home/mutou/nginx/html3:/usr/share/nginx/html nginx
bash 复制代码
docker run -d -p 8080:80 -v /home/mutou/nginx/conf.d:/etc/nginx/conf.d  -v /home/mutou/nginx/html3:/usr/share/nginx/html nginx

5.配置负载均衡

1、访问ip/demo 时,平均分发到8080端口和8081端口上;

2、即it is html1it is html3间接出现;

配置负载均衡,那就是配置在第二次的nginx上,就是反向代理的nginx上,

我们去conf.d2文件夹下,修改default.conf文件,如下:

bash 复制代码
upstream group{
    server 58.87.88.124:8081;
    server 58.87.88.124:8080;
}
server {
    listen       80;
    server_name  localhost;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    location /demo {
        # 在该位置配置反向代理,将ip/demo1请求拦截,发送给8080端口,如果不是本机请使用公网ip
        proxy_pass  http://group;
    }
}

此时,查看所有运行中的docker容器:

bash 复制代码
docker ps

然后重启该容器:

bash 复制代码
docker restart 容器id

6. 查看效果

1、访问ip/demo,每次刷新页面;

2、页面都会在 html1 和 html3 中进行切换,此时负载均衡的效果就实现了。

7.配置负载均衡的权重

1、可以使用下面的配置修改两个端口的权重(即谁被访问的概率大);

ps: weight 越大权重越高 ;

bash 复制代码
upstream group1{
    server 你的刚才的ip地址:8080 weight=1;
    server 你的刚才的ip地址:8081 weight=10;
}

server {
    listen       80;
    server_name  localhost;
    location /demo1 {
        proxy_pass   http://group1/;
    }
}

ps: 修改配置文件, 保存退出, 然后重启该容器; 即可实现.

相关推荐
雪域迷影4 小时前
PostgreSQL Docker Error – 5432: 地址已被占用
数据库·docker·postgresql
莹雨潇潇5 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
苹果醋37 小时前
快速玩转 Mixtral 8x7B MOE大模型!阿里云机器学习 PAI 推出最佳实践
spring boot·nginx·毕业设计·layui·课程设计
tangdou3690986558 小时前
Docker系列-5种方案超详细讲解docker数据存储持久化(volume,bind mounts,NFS等)
docker·容器
漫无目的行走的月亮12 小时前
在Docker中运行微服务注册中心Eureka
docker
大G哥14 小时前
记一次K8S 环境应用nginx stable-alpine 解析内部域名失败排查思路
运维·nginx·云原生·容器·kubernetes
妍妍的宝贝14 小时前
k8s 中微服务之 MetailLB 搭配 ingress-nginx 实现七层负载
nginx·微服务·kubernetes
大道归简15 小时前
Docker 命令从入门到入门:从 Windows 到容器的完美类比
windows·docker·容器
zeruns80215 小时前
如何搭建自己的域名邮箱服务器?Poste.io邮箱服务器搭建教程,Linux+Docker搭建邮件服务器的教程
linux·运维·服务器·docker·网站
爱跑步的程序员~15 小时前
Docker
docker·容器