温馨提示×

debian nodejs怎么配nginx

小樊
32
2026-09-07 16:27:09
栏目: 编程语言

下面给你一个Debian + Node.js + Nginx 的常见配置流程(以 Debian 11/12 为例,Node 用 18/20 均可)。


一、安装 Node.js

方式一:用 NodeSource(推荐)

curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs

验证:

node -v
npm -v

二、启动 Node.js 服务(示例)

假设你的项目在 /var/www/myapp

cd /var/www/myapp
npm install

本地测试:

node app.js
# 或
npm start

假设监听:

http://127.0.0.1:3000

三、安装 Nginx

apt update
apt install -y nginx

启动并设置开机自启:

systemctl enable --now nginx

四、配置 Nginx 反向代理

新建站点配置:

nano /etc/nginx/sites-available/myapp

示例配置(最常用):

server {
    listen 80;
    server_name example.com;  # 改成你的域名或服务器IP

    location / {
        proxy_pass http://127.0.0.1:3000;
        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_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}

启用站点:

ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/

测试并重载:

nginx -t
systemctl reload nginx

五、让 Node.js 后台运行(重要)

方式一:PM2(推荐)

npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup

方式二:systemd(不依赖第三方)

nano /etc/systemd/system/myapp.service
[Unit]
Description=Node.js App
After=network.target

[Service]
User=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/node app.js
Restart=always

[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable --now myapp

六、可选:HTTPS(Let’s Encrypt)

apt install -y certbot python3-certbot-nginx
certbot --nginx -d example.com

七、常见问题

  • 502 Bad Gateway

    • Node 没启动
    • 端口不对
    • 防火墙没开 80/443
  • 静态文件 交给 Nginx:

    location /static/ {
        root /var/www/myapp/public;
    }
    

如果你愿意,可以告诉我:

  • Debian 版本
  • Node 版本
  • 是否用域名
  • Node 项目类型(Express / Nest / Next 等)

我可以直接给你一套完整可用配置

0