How to setup letsencrypt renewal as an automated task in linux

assumptions: you have certbot and nginx running on a docker container

first run:

crontab -e

then inside place

0 1 1 * * ~/your-directory/letsencrypt_renew.sh

then:

nano letsencrypt_renew.sh

and inside place (code generated in copilot):


#!/bin/bash
set -e

# Directory where docker-compose.yml lives
COMPOSE_DIR="/root/odoo-16-docker-compose"

# Where to store logs
LOG_FILE="$COMPOSE_DIR/letsencrypt_renew.log"

echo "==== Renewal run: $(date) ====" >> "$LOG_FILE"

cd "$COMPOSE_DIR"

# Run certbot renew and capture exit code
docker compose run --rm certbot renew >> "$LOG_FILE" 2>&1
RENEW_STATUS=$?

# If renewal failed
if [ $RENEW_STATUS -ne 0 ]; then
    echo "Certbot renewal failed! Exit code: $RENEW_STATUS" >> "$LOG_FILE"
    exit $RENEW_STATUS
fi

# Check if any certificates were actually renewed
if grep -q "No renewals were attempted" "$LOG_FILE"; then
    echo "No certificates renewed; not restarting nginx." >> "$LOG_FILE"
else
    echo "Certificates renewed; restarting nginx." >> "$LOG_FILE"
    docker compose restart nginx >> "$LOG_FILE" 2>&1
fi

echo "==== Renewal completed ====" >> "$LOG_FIL