Software Engineers who work on Golang applications need to keep them running forever on servers and monitor their performance.
These applications are business critical and must adhere to a strict Service-Level Agreements (SLAs), so they must be able to scale across available CPUs without code modifications. Maintaining performance and achieving 99.999% availability throughout the year is important to handle customers demand spikes.
In this tutorial, we will demonstrate the effectiveness of PM2, a production process manager for Node.js applications, and how we can use it to keep Golang applications running forever. PM2 comes with built-in features, such as load balancers, for running high-performance applications.
Install Golang on Amazon EC2
Connect to the ec2 instance and use yum configuration manager to install Go.
sudo yum update -y
sudo yum install -y golang
Add Go to folder
go version
go env
cd /usr/lib/golang/bin
mkdir projects
Add command to ~/.bash_profile
# GOROOT is the location where Go package is installed on your system
export GOROOT=/usr/lib/golang
# GOPATH is the location of your work directory
export GOPATH=$HOME/projects
# PATH in order to access go binary system wide
export PATH=$PATH:$GOROOT/bin
Install PM2
PM2 is a command line tool that requires minimal configuration. If you already have NPM installed on your virtual machine (Amazon EC2), then you can install PM2 by simply running the following command:
npm i pm2
Build Go Application
go mod init main
go mod tidy
go build main.go #build golang application
sudo chmod +x main #give execution permission to the binary
Don’t forget to add the port to Security Groups inbound rules.
Create Package.json File
{
"apps": [
{
"name": "cryptodatapi",
"version": "0.0.5",
"license": "MIT",
"private": true,
"author": "Moat Systems Limited",
"script": "./main"
}
],
"dependencies": {
"pm2": "^5.2.0"
}
}
Once the package.json file has been created, you are ready to start the Golang application.
Start Golang Application 🚀
Start the Golang application you want to keep running forever by running these commands:
pm2 start package.json --name "cryptodatapi" --watch -f -i 0 #start golang application
pm2 save #synchronize with saved process list
pm2 startup #enable PM2 to auto-start at system boot
Monitor Golang Application
pm2 monit
Keymetrics Inc. offers a paid version, which includes additional features.
That’s all for now, friends. We hope you found it useful. Toodles! 😎