Search code examples
node.jsexpresslets-encrypt

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


I created nodejs application and I'm using Lets Encrypt SSL certificates. Following is my Code

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);

I have used pm2 to start this application using following command

sudo pm2 start app.js --watch

I am updating SSL certificates by using following cronjob

0 8 * * * sudo certbot renew

I want to reload SSL certificates automatically whenever certbot renews SSL certificates. How can I achieve this?


Solution

  • You can use the flag --post-hook to restart your application after every renewal.

    certbot renew --post-hook "pm2 restart app_name"
    
    Update #1

    Please note that the command we are running is in crontab and any global program has to be referenced with the full path. You can use the which command to find the executable file path for the command.