Nginx 作为前端服务器与 Node.js 配合使用有几个优势: - 处理静态文件更高效 - 提供负载均衡 - 实现反向代理 - 处理 SSL 加密 - 提供更好的安全性和性能
根据你的操作系统安装 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
编辑 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;
}
}
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设置...
}
}
使用 Let's Encrypt 免费 SSL 证书:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
确保 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 进程:
npm install -g pm2
pm2 start app.js # 启动应用
pm2 save # 保存进程列表
pm2 startup # 设置开机启动
502 Bad Gateway 错误
/var/log/nginx/error.log
静态文件无法访问
性能问题
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 应用集成,获得更好的性能和安全性。