debian

Debian如何为Node.js应用配置SSL证书

小樊
43
2025-06-01 18:14:07
栏目: 云计算

在Debian系统上为Node.js应用配置SSL证书,可以按照以下步骤进行:

1. 获取SSL证书

首先,你需要获取一个SSL证书。你可以从Let’s Encrypt免费获取,或者从其他证书颁发机构购买。

使用Let’s Encrypt

  1. 安装Certbot:

    sudo apt update
    sudo apt install certbot
    
  2. 运行Certbot以获取证书:

    sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com
    

    按照提示完成证书的申请和验证过程。

2. 配置Node.js应用

假设你的Node.js应用运行在http://localhost:3000,你可以使用express框架来配置SSL。

安装必要的模块

npm install express https fs

创建SSL配置文件

在你的Node.js应用目录下创建一个ssl-config.js文件,内容如下:

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

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

const app = require('./app'); // 你的Express应用

https.createServer(options, app).listen(443, () => {
  console.log('Server is running on https://yourdomain.com');
});

3. 更新防火墙设置

确保你的防火墙允许HTTPS流量(端口443):

sudo ufw allow 443/tcp

4. 重启Node.js应用

重启你的Node.js应用以应用新的SSL配置:

pm2 restart your-app-name

或者如果你没有使用pm2,可以直接运行你的Node.js应用:

node ssl-config.js

5. 自动续期证书

Let’s Encrypt证书每90天会过期一次,你需要设置自动续期。

  1. 编辑Certbot的续期脚本:

    sudo nano /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
    
  2. 添加以下内容以重启Node.js应用:

    #!/bin/sh
    systemctl restart your-app-name
    
  3. 赋予脚本执行权限:

    sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
    
  4. 设置定时任务以每天检查证书续期:

    sudo crontab -e
    

    添加以下行:

    0 0 * * * /usr/bin/certbot renew --deploy-hook "/etc/letsencrypt/renewal-hooks/deploy/renewal.sh"
    

通过以上步骤,你就可以在Debian系统上为Node.js应用成功配置SSL证书了。

0
看了该问题的人还看了