Go, also known as Golang, is an open-source programming language developed by Google. Go is designed for efficiency, ease of use, and scalability. It is very popular for building web applications, microservices, and cloud-based applications. In this guide, we will discuss how to deploy a simple Go web application on Ubuntu using Nginx as a reverse proxy and Systemd to manage the application service.
Install Go
Update and install Go:
sudo apt update wget https://go.dev/dl/go1.23.3.linux-amd64.tar.gz sudo tar –C /usr/local –xzf go1.23.3.linux–amd64.tar.gz echo ‘export PATH=$PATH:/usr/local/go/bin’ >> ~/.profile source ~/.profile |
Verifying Go installation by displaying the version number:
The response to the command:
go version go1.23.3 linux/amd64 |
Creating a Go App
Create a directory for the application project with the name goweb:
mkdir ~/goweb && cd ~/goweb |
Creating the main.go file:
The contents of the file main.go:
import (
“fmt”
“net/http”
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, “Hello, World!”)
}
func main() {
http.HandleFunc(“/”, handler)
http.ListenAndServe(“:8080”, nil)
}
package main
import ( “fmt” “net/http” )
func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, “Hello, World!”) }
func main() { http.HandleFunc(“/”, handler) http.ListenAndServe(“:8080”, nil) } |
Compile the application:
Creating a Service
Create a systemd service file:
sudo nano /etc/systemd/system/goweb.service |
File contents:
[Service]
ExecStart=/home/youruser/goweb/app
Restart=always
User=youruser
Group=youruser
Environment=PORT=8080
[Install]
WantedBy=multi-user.target
[Unit] Description=Go Web App After=network.target
[Service] ExecStart=/home/youruser/goweb/app Restart=always User=youruser Group=youruser Environment=PORT=8080
[Install] WantedBy=multi–user.target |
Enable the service:
sudo systemctl daemon–reload sudo systemctl enable goweb sudo systemctl start goweb sudo systemctl status goweb |
Nginx Configuration
Install Nginx:
sudo apt install nginx –y |
Create the Nginx configuration file:
sudo nano /etc/nginx/conf.d/goweb.conf |
File contents:
location / {
proxy_pass
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;
}
}
server { listen 80; server_name yourdomain.com;
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; } } |
Restart Nginx:
sudo systemctl restart nginx |
Test the Application
Open your browser and visit the address:
The result is the text “Hello, World!”.
Lifestyle
Berita Olahraga
Anime Batch
News
Pelajaran Sekolah
Berita Terkini
Berita Terkini
Comments are closed, but trackbacks and pingbacks are open.