ubuntu

如何在Ubuntu上配置Node.js的SSL证书

小樊
48
2025-09-23 08:44:39
栏目: 云计算

在Ubuntu上配置Node.js应用程序的SSL证书,通常涉及以下几个步骤:

1. 获取SSL证书

首先,你需要一个SSL证书。你可以从以下几种方式获取:

使用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应用程序,并且使用Express框架。

  1. 安装必要的Node.js模块:

    npm install express https fs
    
  2. 创建一个SSL配置文件(例如ssl-config.js):

    const fs = require('fs');
    const https = require('https');
    const express = require('express');
    
    const app = express();
    
    // 读取SSL证书文件
    const options = {
      key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem', 'utf8'),
      cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem', 'utf8')
    };
    
    // 定义路由
    app.get('/', (req, res) => {
      res.send('Hello, SSL!');
    });
    
    // 启动HTTPS服务器
    https.createServer(options, app).listen(443, () => {
      console.log('Server is running on https://yourdomain.com');
    });
    

3. 自动续期证书

Let’s Encrypt证书每90天需要续期一次。你可以使用Certbot的自动续期功能。

  1. 创建一个续期脚本:

    sudo nano /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
    
  2. 添加以下内容到续期脚本:

    #!/bin/bash
    systemctl reload nginx  # 或者你使用的其他Web服务器
    
  3. 赋予脚本执行权限:

    sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
    
  4. 测试续期脚本:

    sudo /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
    
  5. 设置定时任务自动续期:

    sudo crontab -e
    

    添加以下行:

    0 0,12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot renew --deploy-hook "/etc/letsencrypt/renewal-hooks/deploy/renewal.sh"
    

4. 重启Node.js应用程序

每次续期证书后,你需要重启Node.js应用程序以应用新的证书。

sudo systemctl restart your-node-app

通过以上步骤,你可以在Ubuntu上成功配置Node.js应用程序的SSL证书,并确保证书自动续期。

0
看了该问题的人还看了