Back to blog
backend February 06, 2023

Deploying a Go Application on Ubuntu Server

In this tutorial, we'll go over the steps to deploy a Go application on an Ubuntu server.

Step 1: Install Go

First, we need to install Go on the server. Open a terminal and run the following commands:

sudo apt-get update
sudo apt-get install golang-go

This will install the latest version of Go on your server. You can verify the installation by running go version.

Step 2: Set up GOPATH

Go requires a workspace directory where all Go projects will reside. To set this up, we need to set the GOPATH environment variable in the .bashrc file.

nano ~/.bashrc

Add the following line at the end of the file:

export GOPATH=$HOME/go

Save the file and run the following command to reload the .bashrc file:

source ~/.bashrc

Step 3: Copy the Application to the Server

We can copy the application to the server using scp:

scp <local_path_to_app> <username>@<server_ip>:<remote_path>

Step 3 (Alternate): Clone from Git

cd /root/
mkdir go
cd go/
git clone https://github.com/<username>/<repo>.git

Step 4: Build the Application

cd app/cmd/backend/
go build

Step 5: Set up a Systemd Service

nano /etc/systemd/system/backend.service

Add the following content:

[Unit]
Description=Go Application

[Service]
WorkingDirectory=/root/go/app/cmd/backend
ExecStart=/root/go/app/cmd/backend/backend
Restart=always
User=root

[Install]
WantedBy=multi-user.target

Then run:

systemctl daemon-reload
systemctl start backend
systemctl enable backend

Step 6: Install Nginx

sudo apt-get install nginx

Step 7: Configure Nginx as a Reverse Proxy

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

Add the server block configuration with proxy_pass to your Go app port, then:

sudo ln -s /etc/nginx/sites-available/backend /etc/nginx/sites-enabled/
sudo systemctl restart nginx