Just to add onto the example @Whitestrake gave you, you may run into issues and hit LetsEncrypt rate limits if your domain is misconfigured, if you use a restart policy like restart: unless-stopped
.
See the details I posted here: Problem when using a restart policy if Caddy errors out · Issue #65 · abiosoft/caddy-docker · GitHub
You can use that shell script, name it docker-entrypoint.sh
and put it beside the following Dockerfile
and you can build from that instead.
Dockerfile
FROM abiosoft/caddy:latest
COPY docker-entrypoint.sh /usr/bin/docker-entrypoint.sh
ENTRYPOINT ["/usr/bin/docker-entrypoint.sh"]
CMD ["/usr/bin/caddy", "--conf", "/etc/Caddyfile", "--log", "stdout"]
docker-entrypoint.sh
#!/bin/ash
# The file that tracks if this container has been started with errors
errorfile="/root/.caddy/haserror"
# Implement a reset command to remove the errorfile
if [ "$1" = 'reset' ]; then
rm -f "$errorfile"
exit 0
fi
# Caddy is being run normally
if [ "$1" = '/usr/bin/caddy' ] || [ "$1" = 'caddy' ]; then
# Quit early if the error file exists
# We do this so that we don't hit Let's Encrypt rate limits
# if we have startup errors
if [ -e "$errorfile" ]; then
echo "Exiting, we previously ran with an error."
exit 1
fi
# Run caddy
"$@"
# Get caddy exit code
cmdoutput="$?"
# Error 1 is a startup error, other exit codes don't concern us
# See https://caddyserver.com/docs/cli#exit-codes
if [ $cmdoutput -eq 1 ]; then
echo "Exited with error $cmdoutput."
touch "$errorfile"
fi
# Exit with the same status code as caddy did
exit "$cmdoutput"
fi
# If the command is not caddy, we'll just run it normally
exec "$@"
To recap, what the shell script does is prevent Caddy from starting if there’s a haserror
file, which should be persisted if you properly have your /root/.caddy
volume set up. This file gets created if the shell script detects Caddy had an error during startup (indicated by exit code 1).
You can check if you hit the limit with the docker log
command, it’ll show a message like “Exiting, we previously ran with an error.” If that happens and you know your DNS and whatnot is now properly configured, you can delete the haserror
file from the volume, or you can run this command …
docker-compose run --rm --no-deps caddy reset
… which tells the entrypoint shell script to delete the file. Useful for scripting stuff yourself with uptime checks against the container.