Saif Ahmad Pre-med programmer

Building a Reverse Proxy with Caddy

Hosting services on your own server comes with a few challenges: linking multiple services under one domain, properly handling SSL, exposing ports on your own network, etc. The solution to the above is a reverse proxy setup. Caddy is one such reverse proxy solution (Caddy comes with more functionality, but that’s not the focus for right now). This guide assumes you have already installed docker and portainer.

Installing Caddy

Create a new container in portainer called caddy. The image we’ll be using is the official Caddy image from Docker Hub, so just put caddy in the image field. Next we have to map the ports 80 and 443 (you’ll have to port forward 80 and 443 too), so add those to the configuration as well. Now your current configuration should match the following:

screenshot of portainer container configuration

Next we have to bind some volumes. First, create a folder where you want your configuration to be stored. We will call this the $DATA_DIR. Create a file called Caddyfile (you can leave it empty for now) and go back to portainer. Under the “Volumes” tab down below, add the following volumes:

Host Container
$DATA_DIR/config /config
$DATA_DIR/site /usr/share/caddy
$DATA_DIR/Caddyfile /etc/caddy/Caddyfile
$DATA_DIR/data /data

…and that’s it for the container. Deploy the container and navigate to $DATA_DIR.

Configuring Caddy

Edit your Caddyfile so it looks like the following:

example.com {
    root * /usr/share/caddy
    
    file_server
}

and reload the container. This will show whatever page is in /site when example.com is loaded. To point it to a service running on your network, change it to look like the following:

example.com {
    reverse_proxy 192.168.1.xxx:80
}

example.com should now point to whatever service is running on that service on port 80, with SSL enabled automatically with no additional configuration. Additional services can be added with subdomains:

example.com {
    reverse_proxy 192.168.1.xxx:80
}

plex.example.com {
    reverse_proxy 192.168.1.xxx:32400
}

Configuring DNS

If your reverse proxy is giving you domain or certificate errors, you probably haven’t configured DNS properly. Go to your site’s DNS settings and add some custom resource records. One should have the name ‘@’ of type A that points to your home IP. You will need an additional entry for any subdomains you want to have. The only thing that will change is the name. For example, plex.example.com will have a name of ‘plex’ of type A that points to your home IP. Once this is configured, everything else should fall into place.