Certbot: Renew certificate in standalone mode with nginx

When you use the Standalone mode for the validation of your certificate, you cannot use your normal webserver (Apache or, in this case, nginx). You have to use the built in webserver from Certbot.

If you want to renew your certificate and you forget to shutdown your webserver, you will get the following error during renewal:

Attempting to renew cert (example.com) from /etc/letsencrypt/renewal/example.com.conf produced an unexpected error: Problem binding to port 80: Could no t bind to IPv4 or IPv6.. Skipping
All renewal attempts failed. The following certs could not be renewed:
/etc/letsencrypt/live/example.com/fullchain.pem (failure)

To solve this problem, I’ve edited the /etc/letsencrypt/renewal/example.com.conf file and added the following two lines:

pre_hook = systemctl stop nginx.service
post_hook = systemctl start nginx.service

Note: change nginx.service to apache2.service for Apache

These two lines make sure that the web server is shutdown (pre_hook) before the renewal request is done, and starts the webserver again when the renewal procedure is succesful (post_hook).

When run again, you’ll get the following result:

Congratulations, all renewals succeeded. The following certs have been renewed:
  /etc/letsencrypt/live/example.com/fullchain.pem (success)