插件窝 干货文章 Node.js中怎么配置和使用Nginx服务器

Node.js中怎么配置和使用Nginx服务器

Nginx proxy 配置 sudo 913    来源:    2025-04-22

Node.js 与 Nginx 配置使用指南

Nginx 是一个高性能的 HTTP 和反向代理服务器,常与 Node.js 应用配合使用。以下是详细的配置和使用方法:

1. 为什么使用 Nginx 搭配 Node.js

  • 负载均衡:分发请求到多个 Node.js 实例
  • 静态文件服务:更高效地处理静态文件
  • SSL 终端:处理 HTTPS 加密
  • 反向代理:隐藏 Node.js 服务器细节
  • 缓存:提高性能

2. 安装 Nginx

Ubuntu/Debian

sudo apt update
sudo apt install nginx

CentOS/RHEL

sudo yum install epel-release
sudo yum install nginx

macOS (Homebrew)

brew install nginx

3. 基本 Nginx 配置

作为反向代理

编辑 Nginx 配置文件(通常在 /etc/nginx/sites-available/yourdomain/etc/nginx/conf.d/default.conf):

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    location / {
        proxy_pass http://localhost:3000; # Node.js 应用端口
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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_cache_bypass $http_upgrade;
    }
}

处理静态文件

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        proxy_pass http://localhost:3000;
        # ...其他代理设置同上
    }

    location /static/ {
        alias /path/to/your/static/files/;
        expires 30d;
        access_log off;
    }
}

4. 启用 HTTPS (Let's Encrypt)

  1. 安装 Certbot:
sudo apt install certbot python3-certbot-nginx
  1. 获取证书:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
  1. 自动续期测试:
sudo certbot renew --dry-run

5. 负载均衡配置

upstream nodejs_servers {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
    server 127.0.0.1:3002;
}

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        proxy_pass http://nodejs_servers;
        # ...其他代理设置
    }
}

6. 常用命令

  • 启动 Nginx:sudo systemctl start nginx
  • 停止 Nginx:sudo systemctl stop nginx
  • 重启 Nginx:sudo systemctl restart nginx
  • 重新加载配置:sudo systemctl reload nginx
  • 检查配置:sudo nginx -t

7. Node.js 应用注意事项

  1. 确保 Node.js 应用绑定到 localhost 而不是 0.0.0.0(由 Nginx 处理外部请求)
  2. 使用环境变量(如 PORT)配置应用端口
  3. 考虑使用 PM2 管理 Node.js 进程:
npm install pm2 -g
pm2 start app.js
pm2 save
pm2 startup

8. 性能调优

  • 调整 worker 进程数(在 /etc/nginx/nginx.conf):
worker_processes auto;
  • 启用 Gzip 压缩:
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
  • 调整缓冲区大小:
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;

通过以上配置,你可以高效地将 Nginx 与 Node.js 应用结合使用,获得更好的性能和安全性。