Nginx 负载均衡案例配置

负载均衡案例

基于 docker 进行 案例测试

1、创建三个 Nginx 实例

创建目录结构

为每个 Nginx 实例创建单独的目录,用于存储 HTML 文件和配置文件

bash 复制代码
mkdir -p data/nginx1/html
mkdir -p data/nginx2/html
mkdir -p data/nginx3/html

添加自定义 HTML 文件

在每个目录中创建一个 index.html 文件,用于区分不同的 Nginx 实例

  • /root/data/nginx1/html/index.html
html 复制代码
<h1>Welcome to Nginx 1</h1>
  • /root/data/nginx2/html/index.html
html 复制代码
<h1>Welcome to Nginx 2</h1>
  • /root/data/nginx3/html/index.html
html 复制代码
<h1>Welcome to Nginx 3</h1>

分别启动三个 Nginx 容器 ,并绑定到 不同的 端口

bash 复制代码
docker run -d -p 801:80 --name nginx1 -v /root/data/nginx1/html:/usr/share/nginx/html nginx:latest

docker run -d -p 802:80 --name nginx2 -v /root/data/nginx2/html:/usr/share/nginx/html nginx:latest

docker run -d -p 803:80 --name nginx3 -v /root/data/nginx3/html:/usr/share/nginx/html nginx:latest

配置负载均衡服务器

创建一个目录(nginx4)并添加配置文件

bash 复制代码
mkdir -p data/nginx4/conf

/root/data/nginx4/conf/nginx.conf 中添加以下内容

nginx 复制代码
worker_processes 1;

events {
    worker_connections 1024;
}

http {
    upstream backend_servers {
        # 权重
        server 192.168.159.130:801 weight=4;
        server 192.168.159.130:802 weight=2;
        server 192.168.159.130:803 weight=2;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://backend_servers;
        }
    }
}

启动一个新的容器作为负载均衡和代理服务器

bash 复制代码
docker run -d -p 80:80 --name nginx4 -v /root/data/nginx4/conf/nginx.conf:/etc/nginx/nginx.conf nginx:latest

访问 地址 http://192.168.159.130/ ,会发现响应分别来自 192.168.159.130:801; 192.168.159.130:802; 192.168.159.130:803

相关推荐
滴答滴答嗒嗒滴2 分钟前
GitHub Actions 深度实践:零运维搭建 CI/CD 流水线
运维·ci/cd·github
搬码临时工16 分钟前
公司内网远程访问配置教程:本地服务器(和指定端口应用)实现外网连接使用
运维·服务器
白总Server29 分钟前
Golang实现分布式Masscan任务调度系统
java·运维·服务器·开发语言·分布式·后端·golang
Sca_杰35 分钟前
android过渡动画
android·运维·nginx
GLAB-Mary43 分钟前
红帽认证工程师(RHCE):掌握Linux自动化的关键
linux·运维·自动化·rhce
中云DDoS CC防护蔡蔡1 小时前
自己的服务器被 DDOS跟CC攻击了怎么处理,如何抵御攻击?
运维·服务器·经验分享·网络安全·ddos
chian-ocean1 小时前
永不休眠:Linux 守护进程的工作原理
linux·运维·服务器
GalaxyPokemon2 小时前
LeetCode - 76. 最小覆盖子串
运维·服务器·数据结构·算法·leetcode
wearegogog1233 小时前
Docker Buildx 简介与安装指南
运维·docker·容器
wanhengidc3 小时前
造成服务器宕机的原因都有哪些?
运维·服务器·网络