温馨提示×

debian nodejs如何配ssl

小樊
46
2026-09-14 11:31:24
栏目: 云计算

在 Debian 上给 Node.js 配置 SSL,通常有两种常见场景:

  1. Node.js 直接使用 SSL(自己起 HTTPS 服务)
  2. Node.js 跑在 Nginx 后面,由 Nginx 处理 SSL(推荐)

下面分别说明。


一、Node.js 直接使用 SSL(HTTPS)

1. 准备证书

你需要:

  • fullchain.pem(证书)
  • privkey.pem(私钥)

例如使用 Let’s Encrypt:

sudo apt install certbot
sudo certbot certonly --nginx -d example.com

证书一般在:

/etc/letsencrypt/live/example.com/
├── fullchain.pem
└── privkey.pem

2. Node.js 示例代码

const https = require('https');
const fs = require('fs');

const options = {
  cert: fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem'),
  key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello HTTPS');
}).listen(443, () => {
  console.log('HTTPS server running on port 443');
});

⚠️ 注意:

  • 需要 root 权限才能监听 443
  • 生产环境建议用 pm2systemd 管理

二、Nginx + Node.js(推荐)

1. Node.js 只监听本地端口

const http = require('http');

http.createServer((req, res) => {
  res.end('Hello from Node.js');
}).listen(3000, '127.0.0.1');

2. 安装 Nginx

sudo apt update
sudo apt install nginx

3. 配置 SSL(Let’s Encrypt)

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

Certbot 会自动:

  • 申请证书
  • 配置 Nginx SSL
  • 设置自动续期

4. Nginx 反向代理配置

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}

5. 测试并重启

sudo nginx -t
sudo systemctl restart nginx

三、证书自动续期

Let’s Encrypt 证书 90 天有效,Debian 默认已配置:

sudo systemctl status certbot.timer

可手动测试:

sudo certbot renew --dry-run

四、常见问题

✅ 防火墙放通 80 / 443

sudo ufw allow 'Nginx Full'

✅ Node.js 不要直接暴露 443(不安全、难维护)

✅ 生产推荐:Nginx + Let’s Encrypt


如果你愿意,我可以:

  • 给你 systemd 服务配置
  • 给你 pm2 + Nginx 完整方案
  • 帮你配 WebSocket SSL

你现在是 直接 Node.js 起 HTTPS,还是 Nginx 反代

0