Run Go server on Ubuntu VPS with nginx and Lets encrypt

I had my fair share of 502 errors to debug this weekend so I thought I would share my nginx config and some of the steps. You need to setup https with lets encrypt for your domain that you plan on using.

Build Go app

I used GOOS=linux GOARCH=amd64 go build to build my go app for my server.

Now I setup a systemd file so we can run the app in the background sudo nano /etc/systemd/system/jobs.service

[Unit]
Description= instance to serve jobs api
After=network.target

[Service]
User=root
Group=www-data

ExecStart=/home/path/to/binary/you/uploaded(which in my case is/var/www/go/jobs)

[Install]
WantedBy=multi-user.target

And now we can control our app with these commands

sudo systemctl start jobs
sudo systemctl enable jobs

Now we need to setup nginx

Here is my config file for nginx file. I used the port my golang app is running and my server ip address.

server {
    server_name localhost www.example.com example.com;

    location / {
            proxy_pass http://ip-address:port;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For;
            proxy_cache_bypass $http_upgrade;
    }

    listen 443 ssl default_server; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/caregiversbythehour.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/caregiversbythehour.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}


server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    server_name www.example.com caregiversbythehour.com;
    listen 80;

    location / {
        proxy_pass http://example;
        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;
    }

    return 404; # managed by Certbot

}

Now restart nginx with sudo systemctl restart nginx.

That should fix it and after you visit the website you can see your app.

Issues still?

  • Make sure your app is running with sudo netstat -ntlp | grep LISTEN, you should see what port your app is running on there and it should be running
  • Still have issues with nginx or a 502 error? Use sudo tail -f /var/log/nginx/error.log and to see what's really going on.