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

相关推荐
qq_2187533124 分钟前
服务器查日志太慢,试试grep组合拳
运维·服务器
Jie_171 小时前
【linux】高可用集群Keepalived
linux·运维·服务器
思绪漂移1 小时前
阿里云【免费试用】Elasticsearch 智能运维 AI 助手
运维·elasticsearch·阿里云
21号 12 小时前
4.应用层自定义协议与序列化
运维·服务器·网络
墨迹的陌离4 小时前
【Linux】重生之从零开始学习运维之Mysql
linux·运维·服务器·数据库·学习·mysql
Ray Song4 小时前
Linux DNS解析1--终端通过网关或者路由器进行域名解析的原理
linux·运维·服务器·dns解析
2025年一定要上岸5 小时前
【pytest高阶】源码的走读方法及插件hook
运维·前端·python·pytest
Zero .5 小时前
macbook安装homebrew
linux·运维·服务器
FJW0208145 小时前
负载均衡集群HAproxy
linux·服务器·云原生·负载均衡
伟大的大威5 小时前
Docker 部署 Supabase并连接
运维·docker·容器