Minimal Reverse Proxy Setup with Caddy and Docker
Recently was the first time I set up a reverse proxy for my two Docker containers on my Ubuntu VPS using Caddy. I'd like to share my experience and setup process, which may be helpful for others new to reverse proxying with Docker and Caddy.
About Caddy
Caddy itself says:
Most people use Caddy as a web server or proxy, but at its core, Caddy is a server of servers.
In my setup, I leveraged Caddy's reverse proxy functionality to efficiently route requests to two Flask servers, each running in separate Docker containers
Caddy also uses a straightforward configuration file format called a Caddyfile, which is easy to read and write. I will show you my own version in the next section.
My Setup
Caddy can be containerized using Docker, offering isolation and simplified deployment across various
environments. To
begin, I created a new directory on my server and added a docker-compose.yml file to configure the
Caddy Docker container.. In the file I specified the official Caddy image and the Docker volume. I opted to set
the
network_modeto host instead of exposing the Docker container to a specific port. This
removes network isolation and and allowing the application to access other ports on my server. This
configuration
enables Caddy to locate the Docker ports specified later in the Caddyfile.
services:
caddy:
image: caddy:latest
network_mode: host
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile
The Caddyfile, created in the same directory, contains the Caddy server configuration.
It begins by listing the URLs for request redirection, in this example, http://url-one.com and http://url-two.com.
Each
URL is followed by curly braces containing further specifications. Next I am defining the Caddyfile directives.
Directives are functional keywords that define how a site is served and are crucial for configuring the behavior
of
a Caddy server. As I want to use the Caddy server as a reverse proxy I assigned the directive
reverse_proxy to each of the urls, followed by the upstream addresses of my Docker-containerized
applications. Because I set thenetwork_mode of the Caddy server to host, Caddy will be
able to locate the exposed ports of the other Docker containers.
http://url-one.com {
reverse_proxy localhost:3000
}
http://url-two.com {
reverse_proxy localhost:3001
}
Find out more about the Caddy reverse_proxy directive and the upstream address configuration here.
And that’s basically it!
With this configuration in place, starting the Caddy Docker container is straightforward. Simply run
docker compose up in the Caddy directory, and requests will be redirected as specified in the
Caddyfile. (Prerequisite is of course to have Docker installed on the server. Check out the Docker documentation
for
Ubuntu here.)
Hope this helped!