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

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

Nginx proxy Node 配置 600    来源:    2025-04-27

Node.js 与 Nginx 配置指南

为什么使用 Nginx 搭配 Node.js

Nginx 作为前端服务器与 Node.js 配合使用有几个优势: - 处理静态文件更高效 - 提供负载均衡 - 实现反向代理 - 处理 SSL 加密 - 提供更好的安全性和性能

基本配置步骤

1. 安装 Nginx

根据你的操作系统安装 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

2. 配置 Nginx 作为反向代理

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

server {
    listen 80;
    server_name yourdomain.com;  # 替换为你的域名或IP

    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_cache_bypass $http_upgrade;
    }

    # 静态文件处理
    location /static/ {
        root /path/to/your/app;
        expires 30d;
    }
}

3. 测试并重启 Nginx

sudo nginx -t  # 测试配置是否正确
sudo systemctl restart nginx  # 重启Nginx

高级配置选项

负载均衡

upstream node_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://node_servers;
        # 其他proxy设置...
    }
}

SSL 配置

使用 Let's Encrypt 免费 SSL 证书:

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com

WebSocket 支持

确保 WebSocket 连接也能通过代理:

location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
}

PM2 管理 Node.js 应用

建议使用 PM2 管理 Node.js 进程:

npm install -g pm2
pm2 start app.js  # 启动应用
pm2 save  # 保存进程列表
pm2 startup  # 设置开机启动

常见问题解决

  1. 502 Bad Gateway 错误

    • 检查 Node.js 应用是否运行
    • 检查防火墙设置
    • 查看 Nginx 错误日志 /var/log/nginx/error.log
  2. 静态文件无法访问

    • 确保路径正确
    • 检查文件权限
  3. 性能问题

    • 调整 Nginx 缓冲设置
    • 启用 gzip 压缩

性能优化建议

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

# 调整缓冲
proxy_buffers 16 16k;
proxy_buffer_size 32k;

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