Build your own ngrok

This simple setup can help us expose our local development environment to the public internet. I usually paid for ngrok, but the last time I tried them, they were expensive, and their customer support was terrible.

For a small-size project, we can build our own small ngrok with Linux, Caddy, and SSH port forwarding.

Requirements:

  • A VPS with Linux. In this example, we will use Ubuntu 20.01 LTS
  • SSH access to your server
  • Caddy
  • A domain name. In this example, we will use mydomain.io

Add DNS record

We need to add two A records to our domain DNS zone:

  • An A record pointing to our server’s IP address
  • A wildcard A record pointing to our server’s IP address

For example, if our server IP address is 5.164.71.442, our records will look like this:

HostnameTypeAddress
@A5.164.71.442
*A5.164.71.442
DNS records example

Configure Caddy

First, Install Caddy.

Then, create a Caddyfile to route traffic from a specific domain name to a local port; in this case, we will do app.mydomain.io and port 8881.

touch ~/Caddyfile
app.mydomain.io {
  reverse_proxy 127.0.0.1:8881
  log {
    output file /var/log/access.log
  }
}

Reload caddy.

caddy reload

> 2023/05/30 17:55:25.272 INFO    using adjacent Caddyfile

And our server is ready.

Create an SSH tunnel

With SSH, you can create a secure connection between your computer and the server, with the services relayed, i.e., every request to the server will be forwarded to your local development environment.

For example, if we are building our application in localhost:8000, we can do the following:

# ssh -R <server port>:<server domain>:<local port> <server ssh user>@<server domain>
ssh -R 8881:app.mydomain.io:8000 user@mydomain.io

Now, every request you send to app.mydomain.io will be forwarded to localhost:8000 on your computer.

Resources

No artificial intelligence was used in the making of this post.

Leave a Reply

Your email address will not be published. Required fields are marked *