302 words
2 minutes
Using Caddy to Host Websites and Docker Containers

Using Caddy to Host Websites and Docker Containers#

Learn how to use Caddy to host static websites and forward traffic to Docker containers.

Installing Caddy#

Install Caddy:

apt install caddy

Set Caddy to start automatically on boot:

sudo systemctl enable caddy

Configuring Caddyfile#

Create var/www/html directory and go into it:

mkdir -p /var/www/html
cd /var/www/html
sudo chown -R username:username /var/www/

Static Website#

Move your website files (HTML, CSS, JavaScript) into the var/www/html directory.

Open Caddyfile:

sudo nano /etc/caddy/Caddyfile

Edit Caddyfile:

example.com {
  root * /var/www/html
  file_server
}

Restart Caddy:

sudo systemctl restart caddy

You can go to your website at https://example.com.

To use a subdomain, add this configuration to Caddyfile:

example.com {
  root * /var/www/html
  file_server
  encode zstd gzip
}

subdomain.example.com {
  root * /var/www/html/folder
  file_server
  encode zstd gzip
}

Restart Caddy.

Reverse Proxy#

Start a Docker application on port 4321.

Open Caddyfile:

sudo nano /etc/caddy/Caddyfile

Configure Caddyfile:

example.com {

  route /subdomain* {
    uri strip_prefix /subdomain
    redir https://subdomain.{host}{uri}
  }

  root * /var/www/html
  file_server
  encode zstd gzip
}

subdomain.example.com {
  reverse_proxy localhost:4321
  encode zstd gzip
}

Restart Caddy:

sudo systemctl restart caddy

You can go to your Docker application at https://subdomain.example.com.

To use ‘www’ subdomain, add this configuration to Caddyfile:

example.com {
  root * /var/www/html
  file_server
  encode zstd gzip

  route / {
    redir https://www.{host}{uri}
  }
}

www.example.com {
  reverse_proxy localhost:4321
  encode zstd gzip
}

Restart Caddy.

Example#

Here’s a Caddyfile example for serving multiple Docker containers and static websites:

# Ports
#  8080: docker-app1   /sub1
#  8081: docker-app2   /sub2
#      : site1         /sub3
#      : site2         /sub4

example.com {

  route /sub1* {
    uri strip_prefix /sub1
    redir https://sub1.{host}{uri}
  }

  route /sub2* {
    uri strip_prefix /sub2
    redir https://sub2.{host}{uri}
  }

  root * /var/www/html
  file_server
  encode zstd gzip
}

sub1.example.com {
  reverse_proxy localhost:8081
  encode zstd gzip
}

sub2.example.com {
  reverse_proxy localhost:8082
  encode zstd gzip
}

sub3.example.com {
  root * /var/www/html/site1
  file_server
  encode zstd gzip
}

sub4.example.com {
  root * /var/www/html/site2
  file_server
  encode zstd gzip
}
NOTE

The encode zstd gzip compresses your website’s content. This helps your site load faster and use less bandwidth.

Using Caddy to Host Websites and Docker Containers
https://blog.juyoun.gg/posts/en/2025/01/19/
Author
Jay
Published at
2025-01-19
License
CC BY