Introduction
A reverse proxy is a server that sits in front of web servers and forwards client (e.g., browser) requests to those web servers. Reverse proxies help distribute incoming traffic across multiple backend servers, improving load balancing, and adding security layers such as an additional firewall or providing SSL (Secure Sockets Layer) termination. In this article, we'll discuss how to set up a reverse proxy for Go applications using two popular tools: NGINX and Caddy.
Why Use a Reverse Proxy?
- Load Balancing: Distribute incoming requests to multiple backends, preventing server overload and ensuring efficient resource utilization.
- SSL Termination: Manage SSL certificates more easily by handling encryption/decryption at the proxy level.
- Security: Add an additional layer for blocking attacks, configuring security headers, and preventing direct exposure of backend servers.
Using NGINX as a Reverse Proxy
Step 1: Install NGINX
sudo apt update
sudo apt install nginx
Step 2: Configure NGINX to Reverse Proxy to the Go App
Open the NGINX configuration file in a text editor:
sudo nano /etc/nginx/sites-available/defaultAdd the following configuration to proxy requests to your Go application running on localhost:8080:
server {
listen 80;
location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Test and restart NGINX:
sudo nginx -t
sudo systemctl restart nginx
Using Caddy as a Reverse Proxy
Step 1: Install Caddy
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo tee /etc/apt/trusted.gpg.d/caddy-stable.asc
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/deb/debian/caddy-stable.list' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddy
Step 2: Configure Caddy for Reverse Proxying
Create or edit the Caddyfile in the default Caddy configuration path (like /etc/caddy/Caddyfile):
example.com {
reverse_proxy localhost:8080
}
Replace example.com with your domain.
Reload the Caddy configuration:
sudo systemctl reload caddy
Testing Your Setup
Once you have set up the reverse proxies, test both configurations by accessing them through your web browser. Navigate to either your server's IP address or the domain name if one is configured and ensure connections are being proxied to your Go application correctly.
Conclusion
Setting up a reverse proxy is an essential part of deploying, securing, and scaling your Go applications effectively. By using tools like NGINX and Caddy, you can easily manage traffic, improve security, and enhance the user experience for your applications.