在Ubuntu / Centos上部署和运行Go API服务器

I just finished my first backend with Go using Iris framework but now I need to put it on production so I can use it in the Slack app I built.

In order to test the code locally I only run my file with go run main.go and ngrok to test with the Slack API, it's working and it's finished.

I have a droplet with Ubuntu 16.04.3 and other one with Centos 7... I was searching for something like pm2 for go, running the server and using nginx to point that port but I read that with Go it's different and I have to use something like this https://fabianlee.org/2017/05/21/golang-running-a-go-binary-as-a-systemd-service-on-ubuntu-16-04/

But that's a very long configuration for a simple server and my questions are:

  • Is this the usual way to config the APIs with Go?
  • Apart of DigitalOcean, do you recommend to use a different service to run my API?

This is really my first time with Go and I just want to learn more, I am a backend developer with Laravel and NodeJS.

I think most people use Supervisor for this purpose, including me.

To make it very easy for you, just take a look at my Golang project, isaac-racing-server and use it as a template for yours by replacing isaac-racing-server with the name of your app. (The Supervisor files are in a subdirectory.)

You can use pm2 if you want. When you build a go project it creates a binary executable, lets say backend-server, which you can run from terminal and will start the app like this:

$ ./backend-server

If it's not executable or has permission denied issue, add the executable permission to it.

$ chmod +x backend-server

You binary should be ready to run. I like to do it with a json config file (process.json) so that I can pass extra env variables as well and don't have to type a lot in terminal. My process.json looks something like this:

{
  "apps" : [{
    "name"        : "backend-app",
    "script"      : "./backend-server",
    "env": {
      "DB_USER": "db_user",
      "PORT": 8080
    }
  }]
}

Finally you can start the app using pm2 like this:

$ pm2 start process.json

More details about json config can be found in official doc