原创

可负载可网页nginx

温馨提示:
本文最后更新于 2025年09月29日,已超过 257 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

可负载可网页nginx 可负载可网页nginx.bash

#!/bin/bash

# nginx-manager.sh - 管理多个 Nginx 服务的脚本

# 配置参数
NGINX_COUNT=3
BASE_PORT=8080
NETWORK_NAME="nginx-multi-network"
CONFIG_BASE_PATH="${1:-/data/load_nginxs}"  # 默认配置文件路径
BACKEND_PORTS="3022|3033"  # 反向代理的后端端口,格式:起始端口|结束端口

# 静态文件静态服务配置
STATIC_SERVICE="TRUE"
#将静态文件复制到运行中的容器 默认文件夹路径 /data/static_files
STATIC_SERVICE_FILEPATH="/root/dist"

# 解析端口范围
parse_port_range() {
    if [[ "$BACKEND_PORTS" == *"|"* ]]; then
        local start_port=$(echo $BACKEND_PORTS | cut -d'|' -f1)
        local end_port=$(echo $BACKEND_PORTS | cut -d'|' -f2)
        echo "$start_port $end_port"
    else
        # 兼容旧格式
        echo "3022 3033"
    fi
}

# 创建必要的目录结构
setup_directories() {
    echo "创建目录结构于: $CONFIG_BASE_PATH"
    for i in $(seq 1 $NGINX_COUNT); do
        mkdir -p $CONFIG_BASE_PATH/nginx$i/conf $CONFIG_BASE_PATH/nginx$i/html
        # 根据 STATIC_SERVICE 配置决定创建什么内容
        if [[ "$STATIC_SERVICE" == "true" || "$STATIC_SERVICE" == "TRUE" ]]; then
            # 静态服务模式 - 创建默认页面
            cat > $CONFIG_BASE_PATH/nginx$i/html/index.html << EOF
<!DOCTYPE html>
<html>
<head>
    <title>Nginx Static Service $i</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
        h1 { color: #2c3e50; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>欢迎访问 Nginx 静态服务 $i</h1>
        <p>这是第 $i 个 Nginx 静态实例</p>
        <p>端口: $((BASE_PORT + i))</p>
        <p>配置路径: $CONFIG_BASE_PATH/nginx$i</p>
    </div>
</body>
</html>
EOF
        else
            # 反向代理模式 - 创建默认页面
            local port_info=($(parse_port_range))
            local start_port=${port_info[0]}
            local end_port=${port_info[1]}
            local port_list=""
            for port in $(seq $start_port $end_port); do
                port_list+="$port "
            done
            
            cat > $CONFIG_BASE_PATH/nginx$i/html/index.html << EOF
<!DOCTYPE html>
<html>
<head>
    <title>Nginx Service $i</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
        h1 { color: #2c3e50; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>欢迎访问 Nginx 服务 $i</h1>
        <p>这是第 $i 个 Nginx 实例</p>
        <p>端口: $((BASE_PORT + i))</p>
        <p>配置路径: $CONFIG_BASE_PATH/nginx$i</p>
        <p>反向代理端口范围: $start_port - $end_port</p>
    </div>
</body>
</html>
EOF
        fi
    done
}

# 创建高并发优化的 nginx.conf 配置文件
create_nginx_configs() {
    for i in $(seq 1 $NGINX_COUNT); do
        cat > $CONFIG_BASE_PATH/nginx$i/conf/nginx.conf << EOF
user nginx;
worker_processes auto;
worker_rlimit_nofile 100000;

events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    # 高并发优化设置
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 100000;
    types_hash_max_size 2048;
    
    # 日志格式
    log_format main '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                   '\$status \$body_bytes_sent "\$http_referer" '
                   '"\$http_user_agent" "\$http_x_forwarded_for"';
    
    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;
    
    # 负载均衡相关设置
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g 
                     inactive=60m use_temp_path=off;
    
    include /etc/nginx/conf.d/*.conf;
}
EOF
    done
}

# 创建反向代理配置文件
create_proxy_configs() {
    # 解析端口范围
    local port_info=($(parse_port_range))
    local start_port=${port_info[0]}
    local end_port=${port_info[1]}
    
    for i in $(seq 1 $NGINX_COUNT); do
        # 生成 upstream 配置
        local upstream_config="upstream backend {\n"
        for port in $(seq $start_port $end_port); do
            upstream_config+="    server 127.0.0.1:$port;\n"
        done
        upstream_config+="}"
        
        cat > $CONFIG_BASE_PATH/nginx$i/conf/default.conf << EOF
$upstream_config

server {
    listen 80;
    server_name localhost;

    # 高并发配置 - 支持 30W QPS
    location / {
        proxy_pass http://backend;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        
        # 超时设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}
EOF
    done
}

# 创建静态文件服务配置文件
create_static_configs() {
    for i in $(seq 1 $NGINX_COUNT); do
        cat > $CONFIG_BASE_PATH/nginx$i/conf/default.conf << EOF
server {
    listen 80;
    server_name localhost;

    # 静态文件服务
    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files \$uri \$uri/ =404;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}
EOF
    done
}

# 创建自定义配置文件
create_configs() {
    create_nginx_configs
    if [[ "$STATIC_SERVICE" == "true" || "$STATIC_SERVICE" == "TRUE" ]]; then
        create_static_configs
        echo "已创建静态文件服务配置"
    else
        create_proxy_configs
        echo "已创建反向代理配置"
    fi
}

# 创建 Docker 网络
create_network() {
    if ! docker network ls | grep -q $NETWORK_NAME; then
        echo "创建 Docker 网络: $NETWORK_NAME"
        docker network create $NETWORK_NAME
    else
        echo "Docker 网络已存在: $NETWORK_NAME"
    fi
}

# 复制静态文件到运行中的容器
copy_static_files() {
    local container_ids=("$@")
    
    if [ ${#container_ids[@]} -eq 0 ]; then
        return
    fi

    echo "正在向运行中的容器复制静态文件..."

    for i in "${container_ids[@]}"; do
        if [ -d "$STATIC_SERVICE_FILEPATH" ] && [ "$(ls -A $STATIC_SERVICE_FILEPATH)" ]; then
            echo "向 nginx-service-$i 复制静态文件..."
            # 使用 docker cp 将静态文件复制到运行中的容器
            docker cp $STATIC_SERVICE_FILEPATH/. nginx-service-$i:/usr/share/nginx/html/ 2>/dev/null
            
            if [ $? -eq 0 ]; then
                echo "✓ 已复制静态文件到 nginx-service-$i 容器"
            else
                echo "✗ 复制静态文件到 nginx-service-$i 容器失败"
            fi
        else
            echo "警告: 静态文件路径 $STATIC_SERVICE_FILEPATH 不存在或为空"
        fi
    done
}

# 启动所有 Nginx 服务
start_services() {
    echo "启动 $NGINX_COUNT 个 Nginx 服务..."
    echo "配置文件路径: $CONFIG_BASE_PATH"
    if [[ "$STATIC_SERVICE" == "true" || "$STATIC_SERVICE" == "TRUE" ]]; then
        echo "服务模式: 静态文件服务"
        echo "静态文件路径: $STATIC_SERVICE_FILEPATH"
    else
        local port_info=($(parse_port_range))
        local start_port=${port_info[0]}
        local end_port=${port_info[1]}
        echo "服务模式: 反向代理"
        echo "反向代理端口范围: $start_port - $end_port"
    fi
    create_network

    local containers_to_copy=()  # 记录需要复制文件的容器

    for i in $(seq 1 $NGINX_COUNT); do
        PORT=$((BASE_PORT + i))

        # 检查容器是否已存在
        if docker ps -a --format '{{.Names}}' | grep -q "nginx-service-$i"; then
            echo "容器 nginx-service-$i 已存在,正在重启..."
            docker stop nginx-service-$i >/dev/null 2>&1
            docker rm nginx-service-$i >/dev/null 2>&1
        fi

        # 启动新的容器
        docker run -d \
            --name nginx-service-$i \
            --network $NETWORK_NAME \
            -p $PORT:80 \
            -v $CONFIG_BASE_PATH/nginx$i/conf/nginx.conf:/etc/nginx/nginx.conf \
            -v $CONFIG_BASE_PATH/nginx$i/conf/default.conf:/etc/nginx/conf.d/default.conf \
            -v $CONFIG_BASE_PATH/nginx$i/html:/usr/share/nginx/html \
            nginx:latest >/dev/null 2>&1

        if [ $? -eq 0 ]; then
            echo "✓ Nginx 服务 $i 已启动,访问端口: $PORT"
            # 如果是静态服务模式,记录需要复制文件的容器
            if [[ "$STATIC_SERVICE" == "true" || "$STATIC_SERVICE" == "TRUE" ]]; then
                containers_to_copy+=("$i")
            fi
        else
            echo "✗ Nginx 服务 $i 启动失败"
        fi
    done

    # 在容器启动完成后复制静态文件
    if [[ "$STATIC_SERVICE" == "true" || "$STATIC_SERVICE" == "TRUE" ]]; then
        copy_static_files "${containers_to_copy[@]}"
    fi
}

# 停止所有 Nginx 服务
stop_services() {
    echo "停止所有 Nginx 服务..."
    for i in $(seq 1 $NGINX_COUNT); do
        if docker ps -a --format '{{.Names}}' | grep -q "nginx-service-$i"; then
            docker stop nginx-service-$i >/dev/null 2>&1
            docker rm nginx-service-$i >/dev/null 2>&1
            echo "✓ Nginx 服务 $i 已停止"
        fi
    done
}

# 查看服务状态
status_services() {
    echo "Nginx 服务状态:"
    echo "配置文件路径: $CONFIG_BASE_PATH"
    if [[ "$STATIC_SERVICE" == "true" || "$STATIC_SERVICE" == "TRUE" ]]; then
        echo "服务模式: 静态文件服务"
        echo "静态文件路径: $STATIC_SERVICE_FILEPATH"
    else
        local port_info=($(parse_port_range))
        local start_port=${port_info[0]}
        local end_port=${port_info[1]}
        echo "服务模式: 反向代理"
        echo "反向代理端口范围: $start_port - $end_port"
    fi
    for i in $(seq 1 $NGINX_COUNT); do
        if docker ps --format '{{.Names}}' | grep -q "nginx-service-$i"; then
            PORT=$((BASE_PORT + i))
            echo "✓ 服务 $i: 运行中 (端口: $PORT)"
        elif docker ps -a --format '{{.Names}}' | grep -q "nginx-service-$i"; then
            echo "● 服务 $i: 已停止"
        else
            echo "○ 服务 $i: 未创建"
        fi
    done
}

# 清理所有资源
cleanup() {
    echo "清理所有资源..."
    stop_services
    if docker network ls | grep -q $NETWORK_NAME; then
        docker network rm $NETWORK_NAME >/dev/null 2>&1
        echo "✓ Docker 网络已删除"
    fi
    echo "✓ 清理完成"
}

# 显示帮助信息
show_help() {
    echo "Nginx 多服务管理脚本"
    echo "使用方法: $0 [选项] [配置路径]"
    echo ""
    echo "参数:"
    echo "  配置路径  Nginx配置文件放置地址 (默认: /data/load_nginxs)"
    echo ""
    echo "配置变量:"
    echo "  STATIC_SERVICE        服务模式 (true/FALSE, 默认: FALSE)"
    echo "  STATIC_SERVICE_FILEPATH 静态文件路径 (默认: /data/static_files)"
    echo "  BACKEND_PORTS         反向代理端口范围 (格式: 起始端口|结束端口, 默认: 3022|3033)"
    echo ""
    echo "选项:"
    echo "  start     启动所有 Nginx 服务"
    echo "  stop      停止所有 Nginx 服务"
    echo "  status    查看服务状态"
    echo "  setup     创建目录结构和配置文件"
    echo "  cleanup   清理所有资源"
    echo "  restart   重启所有服务"
    echo "  help      显示帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 /data/load_nginxs"
    echo "  $0 start /data/load_nginxs"
    echo "  $0 status"
}

# 主函数
main() {
    case "${1:-default}" in
        start)
            start_services
            ;;
        stop)
            stop_services
            ;;
        status)
            status_services
            ;;
        setup)
            setup_directories
            create_configs
            ;;
        cleanup)
            cleanup
            ;;
        restart)
            stop_services
            sleep 2
            start_services
            ;;
        help)
            show_help
            ;;
        default)
            setup_directories
            create_configs
            start_services
            ;;
    esac
}

# 执行主函数
main "$@"

s使用说明

# Nginx 多服务管理脚本使用说明

## 基本功能
- 一键创建多个 Nginx 服务实例
- 支持反向代理负载均衡模式
- 支持静态文件服务模式
- 自动配置高并发优化参数

## 配置参数

### 主要配置变量
- `NGINX_COUNT`: Nginx 服务实例数量(默认:3)
- `BASE_PORT`: 基础端口号(默认:8080)
- `CONFIG_BASE_PATH`: 配置文件存储路径(默认:/data/load_nginxs)
- `BACKEND_PORTS`: 反向代理端口范围(格式:起始端口|结束端口,默认:3022|3033)
- `STATIC_SERVICE`: 服务模式(TRUE/FALSE,默认:TRUE)
- `STATIC_SERVICE_FILEPATH`: 静态文件路径(默认:/root/dist)

## 使用方法

### 1. 基本使用
```bash
# 使用默认配置启动
./可负载可网页nginx.bash

# 指定配置路径
./可负载可网页nginx.bash /custom/config/path
```


### 2. 命令选项
- `start`: 启动所有 Nginx 服务
- `stop`: 停止所有 Nginx 服务
- [status](file://E:\chat\demo\model\src\main\java\org\example\chat\ChatUser.java#L14-L14): 查看服务状态
- `setup`: 创建目录结构和配置文件
- `cleanup`: 清理所有资源
- `restart`: 重启所有服务
- `help`: 显示帮助信息

### 3. 使用示例
```bash
# 启动服务
./可负载可网页nginx.bash start

# 查看状态
./可负载可网页nginx.bash status

# 停止服务
./可负载可网页nginx.bash stop
```


## 服务模式

### 静态文件服务模式(STATIC_SERVICE=TRUE)
- 将 `STATIC_SERVICE_FILEPATH` 路径下的文件作为静态资源提供
- 文件在容器启动后自动复制到容器中

### 反向代理模式(STATIC_SERVICE=FALSE)
- 将请求负载均衡到指定端口范围的服务
- 支持高并发配置,优化 30W QPS 场景

## 端口分配
- 服务1: 8081端口
- 服务2: 8082端口
- 服务3: 8083端口
- 依此类推...
正文到此结束