Caddy within container

Varun Sharma
3 min readJul 1, 2022

--

I have started with a little background story, if you are interested in action you can directly jump to the setting up section.
After reading this you will be getting the answers to the questions like How to set up the Caddy server? how to do it within a container? how to write a Caddy config file? how to route multiple endpoints to a specific service?

Photo by Taylor Vick on Unsplash

Background

There were multiple tools hosted on a single server, and to handle routing for them an Apache webserver was installed. Soon one by one other tool were moved to other appropriate servers. And, to make the tool standalone I had the chance to use Caddy. The following were reasons for choosing Caddy, other than the basic ones [Open-source, production-ready, Lightweight]

  • Automatic HTTP to HTTPS
  • Automatically obtain and renew TLS certificate
  • Configuration is a too easy as a lot of modules are already in build as compared to other open-source servers

Setting up

Docker and docker-compose are the pre-requisite here. We will be going to end up with 2 files.

  • caddyFile (caddy configuration file)
  • docker-compose.yml (configuration to run them on docker container)

There are multiple ways you can configure Caddy, like oneliners, API, or caddyFile. We will be continuing with the latter, simply because it’s easier to maintain.

I refer to the official documentation to configure Caddy. I liked how they represent the information in docs.

Here is the content of caddyFile.

In line 3 we mentioned the server domain name [replace it with your website name], to identify which website we are hosting and Caddy will automatically obtain the TLS certificates for this website and continues to renew it using OCSP. Isn’t it awesome?

“root” directive on line 5 is a declaration that this path should be considered as the root of this project and file_server on next is just to serve the static files from there while enabling the encoding mentioned on line 7.

“handle” directive on multiple lines (10 and 13) are used to identify URL patterns and code between there body {} is the way we want to operate them like “/api/old*” is our previous API’s URL which is needed to be redirected to PHP container and same with others. The “handle” with no pattern is the one used to capture any URL that wasn’t captured on the above two conditions.

And at last if there is any custom header that is required within your tool, then mention them on line 24.

Following is the docker-compose.yml, you can use it directly to run the Caddy directly in the production environment.

I would be happy to answer if you have any questions.

--

--

Varun Sharma
Varun Sharma

Written by Varun Sharma

Fall in love with building products, now learning to make them successful.

No responses yet