Caddy — Reverse Proxy a Node.js App

Caddy is a powerful platform to serve your web applications and services. You can use Caddy as a reverse proxy to forward requests from the Internet to your Node.js application running on your server.

This tutorial shows you how to use Caddy as a reverse proxy for your Node.js app.

Caddy Series Overview

Prerequisites and Preparations

This tutorial assumes your server meets the following requirements:

  • you use a Linux server (we use Ubuntu)
  • you have Caddy v2 installed
  • you have the caddy command available (run caddy help to verify that caddy is in your PATH)
  • a running Node.js server on your server
  • we’re assuming your Node.js server runs on the local port 3000

Reverse Proxy a Node.js App Using a Caddyfile

We’re using a Caddyfile to configure the reverse proxy to your Node.js server. The Caddyfile then contains an explicit configuration that is reviewable and shareable with your coworkers.

After installing Caddy you can find a caddy directory in /etc/caddy. This directory contains a default Caddyfile. You can change this existing Caddyfile to configure the reverse proxy.

Here’s a basic reverse proxy setup reverse proxying all HTTP requests to a locally running server on port 3000. We’re assuming you started your Node.js server on port 3000 already.

Now, open /etc/caddy/Caddyfile (for example with nano) and adjust the contents to this:

:80 {
  reverse_proxy localhost:3000
}

Save the changes and tell Caddy to serve the configuration by running the following command from the /etc/caddy directory:

caddy run Caddyfile  

At this point, find the IP address of your server. Then open your browser and paste your server’s IP address into the URL bar. Submit the request to hit your server and check whether Caddy forwards the requests.

Reverse Proxying a Domain

We use Caddy to serve the superchargejs.com website. In the example above, we told Caddy to forward all requests hitting Caddy to the configured server behind the reverse proxy.

When hosting two or more applications on your server you want to reverse proxy each domain to a different server.

Create a New Caddyfile

We use a dedicated Caddyfile to serve the Supercharge website. The website’s Caddyfile is named superchargejs.com. It lives beside the default Caddyfile.

The content of the superchargejs.com Caddyfile is this:

superchargejs.com {  
  reverse_proxy localhost:2021
}

We then import the Caddyfile for superchargejs.com inside of the default Caddyfile. Open and edit /etc/caddy/Caddyfile to import the configuration for the Supercharge website:

import ./superchargejs.com

:80 {
  reverse_proxy localhost:3000
}

Then reload Caddy to pick up the changed configuration:

$ caddy reload Caddyfile
2021/11/14 12:11:03.805    INFO    using adjacent Caddyfile  

That’s it.

Enjoy reverse proxying your Node.js apps with Caddy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.