如何在 Node.js 应用程序中自动重新加载更新的 SSL 证书

How to automatically reload updated SSL certificates in Node.js Application

我创建了 nodejs 应用程序并且我正在使用 Lets Encrypt SSL 证书。以下是我的代码

var express = require(‘express’);
var https = require(‘https’);
var fs = require(‘fs’);
var option = {
    key: fs.readFileSync(‘/etc/letsencrypt/live/$DOMAIN/privkey.pem’),
    cert: fs.readFileSync(‘/etc/letsencrypt/live/$DOMAIN/fullchain.pem’)
};
const app = express();
app.use((req, res) =>
{
    res.end(‘Hello World’);
});

https.createServer(option, app).listen(8000);

我已经使用 pm2 使用以下命令启动此应用程序

sudo pm2 start app.js --watch

我正在使用以下 cronjob 更新 SSL 证书

0 8 * * * sudo certbot renew

我想在 certbot 更新 SSL 证书时自动重新加载 SSL 证书。我怎样才能做到这一点?

您可以在每次续订后使用标志 --post-hook 重新启动您的应用程序。

certbot renew --post-hook "pm2 restart app_name"
更新#1

请注意,我们的命令 运行 在 crontab 中,任何全局程序都必须使用完整路径进行引用。可以使用which命令查找命令的可执行文件路径。

您可以在不重新启动服务器的情况下重新加载新证书。

根据来自 mscdex 的问题Reload certificate files of https.createServer() without restarting node server #15115 , specifically this comment

FWIW you can already do this with SNICallback():

const https = require('https');
const tls = require('tls');
const fs = require('fs');
var ctx = tls.createSecureContext({
  key: fs.readFileSync(config.sslKeyPath),
  cert: fs.readFileSync(config.sslCrtPath)
});
https.createServer({
  SNICallback: (servername, cb) => {
    // here you can even change up the `SecureContext`
    // based on `servername` if you want
    cb(null, ctx);
  }
});

With that, all you have to do is re-assign ctx and then it will get used for any future requests.

使用上面的示例,您只需在 SNICallback 中的证书路径上再次执行 fs.readFileSync 并将它们附加到 ctx 对象。但是,您只想在知道它们刚刚更改时执行此操作。您可以查看 javascript 中的文件以了解更改。您可以使用 fs.watch() for that or something from npm.