1. Nginx架构,反向代理和负载均衡

Nginx 介绍

Nginx(读作 "Engine X")是一款高性能的 Web 服务器、反向代理服务器及负载均衡器。由 Igor Sysoev 于 2004 年开发,初衷是解决当时大型网站的高并发连接问题。

Nginx 以 事件驱动架构 和 异步处理 著称,因此在处理大量并发连接时表现非常优秀。


主要功能

1. Web 服务器

  • 可以直接提供静态文件(HTML、CSS、JS、图片等)。
  • 支持 HTTP、HTTPS 协议。
  • 高效处理高并发请求,资源占用低。

2. 反向代理

  • 客户端请求先到 Nginx,由 Nginx 转发到后端服务器(如 Apache、Tomcat、Node.js)。
  • 可以缓存后端内容,减轻后端压力。
  • 提供安全隔离和请求过滤功能。

3. 负载均衡

  • 将请求分发到多台后端服务器,提高系统可用性和扩展性。
  • 支持多种负载均衡策略:
    • 轮询(Round Robin)
    • 最少连接(Least Connections)
    • IP 哈希(IP Hash)

4. 邮件代理

  • 支持 IMAP、POP3、SMTP 协议代理。

5. 静态资源缓存

  • 可以缓存常访问的内容,提升访问速度。

架构特点

事件驱动(Event-Driven)

  • 使用异步非阻塞 I/O 模型。
  • 每个工作进程可以同时处理成千上万的并发连接。

模块化设计

  • 核心功能轻量,额外功能通过模块扩展(例如 HTTP 模块、Stream 模块、Mail 模块)。

高性能、高稳定性

  • 少量进程即可处理大量连接。
  • 在大型网站中广泛使用(如 Netflix、WordPress.com)。

典型应用场景

  • 静态网站:提供 HTML、图片、CSS 等静态资源。
  • 反向代理:隐藏后端服务器,统一入口。
  • 负载均衡:提高系统吞吐量和高可用性。
  • API 网关:管理和转发 API 请求。
  • 内容缓存加速:提高访问速度,降低后端压力。

1. 架构图

2. 直观的反向代理 + 两台后端服务流程图

C:\nginx\conf\nginx.conf

bash 复制代码
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    upstream my_app {
        server 127.0.0.1:3000;
        server 127.0.0.1:3001;
    }

    server {
        listen       80;
        server_name  localhost;

        root         C:/nginx/my_site;
        index        index.html;

        #access_log  logs/host.access.log  main;

        location / {
            # root   html;
            # index  index.html index.htm;
            # try_files $uri $uri/ =404;  # 如果文件不存在,返回 404

            proxy_pass http://my_app;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

创建2个js

//app1.js

bash 复制代码
const http = require('http');

const PORT = 3000;

http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello from Node.js app1 on port 3000\n');
}).listen(PORT, () => console.log(`App1 listening on ${PORT}`));

//app2.js

bash 复制代码
const http = require('http');

const PORT = 3001;

http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello from Node.js app2 on port 3001\n');
}).listen(PORT, () => console.log(`App2 listening on ${PORT}`));

打开2个终端,分别运行

node app1.js

App1 listening on 3000

node app2.js

App2 listening on 3001

启动一个简单 Node.js 服务 node app.js 在 3000 端口

通过 Nginx 访问 http://localhost,确认能看到 Node.js 输出。

刷新网页交替输出:

bash 复制代码
Hello from Node.js app2 on port 3001
bash 复制代码
Hello from Node.js app1 on port 3000
相关推荐
tonydf8 小时前
没完了,Nginx又报新漏洞!
运维·nginx
飞奔的瓜牛12 小时前
Linux 下使用 OpenSSL 生成自签名证书完整指南
运维·服务器·nginx
JaguarJack15 小时前
NGINX 两处漏洞可导致未经身份验证的远程代码执行(CVE-2026-123633 和 CVE-2026-123007)
后端·nginx·nginx2root
BingoGo15 小时前
NGINX 两处漏洞可导致未经身份验证的远程代码执行(CVE-2026-123633 和 CVE-2026-123007)
后端·nginx
Csvn1 天前
Nginx 反向代理入门:proxy_pass 两种形态、超时链与 502/504 分辨
后端·nginx
yyuuuzz1 天前
nginx 502 排查,先看上游超时那一行
android·java·运维·nginx·502
月夏2 天前
我把全栈项目塞进已有 nginx 的服务器,卡我最久的是三个斜杠
nginx·react.js·docker
飞奔的瓜牛2 天前
Nginx 实现TCP与UDP转发:新版与老版本配置详解
tcp/ip·nginx·udp
飞奔的瓜牛2 天前
Nginx 生产环境运维实践:常见问题、关注要点与日常维护
运维·nginx
飞奔的瓜牛2 天前
Nacos 三节点集群部署手册:MySQL 持久化 + Nginx 负载均衡
mysql·nginx·负载均衡