在Ubuntu上配置Node.js应用程序的SSL证书,通常涉及以下几个步骤:
首先,你需要一个SSL证书。你可以从以下几种方式获取:
安装Certbot:
sudo apt update
sudo apt install certbot
运行Certbot获取证书:
sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com
按照提示完成证书的获取和安装。
假设你已经有一个Node.js应用程序,并且使用Express框架。
安装必要的Node.js模块:
npm install express https fs
创建一个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');
});
Let’s Encrypt证书每90天需要续期一次。你可以使用Certbot的自动续期功能。
创建一个续期脚本:
sudo nano /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
添加以下内容到续期脚本:
#!/bin/bash
systemctl reload nginx # 或者你使用的其他Web服务器
赋予脚本执行权限:
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
测试续期脚本:
sudo /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
设置定时任务自动续期:
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"
每次续期证书后,你需要重启Node.js应用程序以应用新的证书。
sudo systemctl restart your-node-app
通过以上步骤,你可以在Ubuntu上成功配置Node.js应用程序的SSL证书,并确保证书自动续期。