Deploying your Go app on Google App Engine
This tutorial will show you how to deploy a Go app to both the GCP App Engine Standard and Flexible Environments
Prerequisites
Let’s Get Started
First, let’s make a directory and enter it:
mkdir ~/hello-world-go && cd hello-world-go
Now make sure we set our GOPATH to this directory:
export GOPATH=$(pwd):$GOPATH
Next, we’ll set up our project directory:
mkdir -p src/go-app && cd src/go-app
And now let’s go get the GCP App Engine library:
go get -u google.golang.org/appengine/...
Finally, we’ll set our Project ID (from GCP) as an environmental variable and configure gcloud
to use it:
PROJECT_ID=<project-id>
gcloud config set project $PROJECT_ID
Time to Write Some Some Code
First we need to make an app.yaml
file to configure your project’s settings:
runtime: go
api_version: go1
env: standard
handlers:
- url: /.*
script: _go_app
This tells the App Engine that we want to use the Go runtime, that we want to use the Standard environment, and sets up the handlers for when the server gets a request.
Take note of line 3 where it says
env: standard
Now let’s make our main.go
file for our server:
package mainimport (
"fmt"
"net/http"
"google.golang.org/appengine"
)func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, world!") // Response to request
}func main() {
http.HandleFunc("/", handler) // Set endpoint handler
appengine.Main() // Start the server
}
This first imports the libraries that we need, then sets up a handler for when you hit the /
endpoint, and finally starts the server.
Let’s Deploy!
This is so easy, simply run:
gcloud app deploy
And make sure to hit Y
when it asks you Do you want to continue (Y/n)?
Protip: use
yes | gcloud app deploy
if you want to skip the confirmation
Now, this should take ~30 seconds to deploy (sooooooo fast).
When it’s done either run gcloud app browse
or open your browser to https://<project-id>.appspot.com/
Bonus
Above, we deployed our Go app to the App Engine Standard Environment. But now let’s see how easy it is to deploy to the Flexible Environment.
Remember our app.yaml
file? Let’s change one word in line three:
runtime: go
api_version: go1
env: flex
handlers:
- url: /.*
script: _go_app
Can you spot the difference? We changed env: standard
to env: flex
Now simply re-run gcloud app deploy
and hit Y
again to confirm. Since we are deploying to the Flex Environment, this will take a bit longer (on the order of 3–5 minutes).
There’s different advantages for each environment, and I won’t discuss them here. However, if you want to look into it, there is a quick guide here on Choosing an App Engine Environment.
👋 ✌️
Thanks for reading! If you have any questions, comment below!