Run Go Applications on a Server

Ubuntu: How to Run Go Applications on a Server

Go (Golang) is a modern, compiled programming language designed for performance and concurrency. It is widely used for building web servers, APIs, and microservices. This guide explains how to install Go, build a Go application, and run it on an Ubuntu server.


Step 1: Install Go

sudo apt update

sudo apt install golang -y

Verify installation:

go version


Step 2: Write a Simple Go Server

Create a file named server.go:

package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello from Go Server!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }

Step 3: Build the Application

go build server.go

This creates a binary named server.


Step 4: Run the Application

./server

The server will start listening on port 8080. Access it in your browser:

http://your-server-ip:8080


Step 5: Run as a Background Service

Create a systemd service file:

sudo nano /etc/systemd/system/go-server.service

Example configuration:

[Unit] Description=Go Server After=network.target [Service] ExecStart=/home/username/server Restart=always User=username [Install] WantedBy=multi-user.target

Enable and start the service:

sudo systemctl enable go-server

sudo systemctl start go-server

Check status:

sudo systemctl status go-server


Step 6: Deploy with Reverse Proxy (Optional)

For production, run Go behind Nginx for SSL and load balancing:

sudo apt install nginx -y

Edit Nginx config to proxy requests from port 80/443 to Go’s port 8080.


Best Practices

  • Always compile Go apps before deployment
  • Run Go apps as systemd services for reliability
  • Use Nginx or Caddy for SSL termination
  • Monitor logs with journalctl -u go-server
  • Use environment variables for configuration (e.g., database credentials)

Note: HostPalace offers optimized servers for Go applications, ensuring high performance and secure deployments.