Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Using Nginx as a Reverse Proxy for a Go Application

1 min read .
Using Nginx as a Reverse Proxy for a Go Application

A Go web application often listens directly on an application port such as :8080. If you want users to access it through a normal domain on port 80 or 443, you can place Nginx in front of it as a reverse proxy.

Using Nginx in front of a Go service provides several benefits:

  • Client requests reach Nginx before being forwarded to the Go application.
  • TLS termination can be handled at the proxy layer.
  • Multiple application instances can be load balanced.
  • Static assets can be served separately when that architecture makes sense.

This guide shows a basic setup.

1. Install Nginx

On Ubuntu or Debian:

sudo apt update
sudo apt install nginx

2. Create the Reverse Proxy Configuration

Create a site configuration for the Go application:

sudo nano /etc/nginx/sites-available/myapp

Add:

server {
    listen 80;
    server_name yourdomain.com;  # replace with your domain or server IP

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

This forwards requests for yourdomain.com to the Go application listening on localhost:8080.

3. Enable the Configuration

Create a symbolic link in sites-enabled:

sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/

4. Test the Configuration

Before reloading Nginx, validate the configuration:

sudo nginx -t

If Nginx reports that the syntax and configuration test are successful, continue.

5. Reload Nginx

sudo systemctl reload nginx

Nginx is now ready to proxy traffic to the Go application.

6. Access the Application

Open http://yourdomain.com. Requests should arrive at Nginx and then be forwarded to the Go service on port 8080.

Optional: Add HTTPS with Let’s Encrypt

If Certbot is installed and your DNS is already pointing to the server, you can configure a Let’s Encrypt certificate with the Nginx plugin:

sudo certbot --nginx -d yourdomain.com

Follow Certbot’s prompts and verify the resulting HTTPS configuration before relying on it in production.

Related Posts

chevron-up