How to Renew Let’s Encrypt SSL Certificates with Certbot and Cron Job

How to Renew Let’s Encrypt SSL Certificates with Certbot and Cron Job

This guide shows you how to set up automatic renewal for Let’s Encrypt SSL certificates using Certbot and a cron job on your Linux server.

1. Create a Renewal Script

Create a folder for scripts if you haven’t already:

sudo mkdir -p ~/scripts/cronjobs

Create a script named renew_ssl_certificates.sh in ~/scripts/cronjobs:

sudo nano ~/scripts/cronjobs/renew_ssl_certificates.sh

Add the following content:

#!/bin/bash

# Script to renew Let's Encrypt certificates and restart Nginx
certbot renew --quiet --post-hook "systemctl reload nginx"

Make the script executable:

chmod +x ~/scripts/cronjobs/renew_ssl_certificates.sh

2. Set Up a Cron Job

Edit the root user’s crontab:

crontab -e

Add this line to run the script at 6am and 11pm daily.

# Certbot renew SSL certificates
0 6,23 * * * /bin/bash /home/admin/scripts/cronjobs/renew_ssl_certificates.sh

If your root user’s home directory isn’t /admin, adjust the path (e.g., /home/youruser/scripts/cronjobs/renew_ssl_certificates.sh).

3. Test the Script

Run the script manually to ensure it works:

sudo /bin/bash ~/scripts/cronjobs/renew_ssl_certificates.sh

Check certificate expiration dates to confirm renewal:

sudo certbot certificates

Conclusion

  • The script only renews certificates within 30 days of expiration, so it’s safe to run twice daily.
  • The –post-hook systemctl reload nginx ensures Nginx applies the new certificates after renewal.

Now your certificates will renew automatically, keeping your sites secure!

Categories: Server