Deploy App with Kubernetes to GCP

Tram Ho

Getting Started

In this article I will show you how to deploy a simple Go application that will consume a public Anime api called Jikan. The goal is to guide you through how to setup a kubernetes cluster on Google Cloud Platform and deploy an application there, so I won’t go into details on how Go code work.

What you need to work along the way in this article is as follow:

Prepare a Demo Project

As always the source code is available on my github account and you can get it here. Before we dive into the actual deployment, lets take a quick look at what our demo project does shall we?

Our demo project is called Jikan, it’s an anime searching service which consume MyAnimeList public API named (you guess it) Jikan. To consume service issue a GET request to the following endpoint

Here is our main logic. Basically all it does is consume Jikan api, map response to our own type and return.

To run a project locally

Packing Our App

The first step to deployment is to pack our application into a container. I want the image to be as small as possible so I picked scratch as base image. To summary what’s going is we use multi-stage build. The first stage is to build our Go application into a binary file and then in the final stage copy that binary and execute it in an entrypoint.

The resulting image is ~ 6MB

Now push image to docker registry

Define Kubernetes Deployment

The following will create a deployment name jikan that manage 4 replication of our apps which expose on container port 8080. The image will be pull from my docker hub repository norin/jikan:1.0.0.

Next we need a way to access our application from the web. There are many way to archive this but here I chose to create a LoadBalancer. It will distribute traffic it receive to service labeled with app: jikan and map to it port 8080.

Setup GCP Project & Cluster

The next task is to setup GCP project & cluster by run the following commands. The first command will authenticate and get access token needed to subsequence commands. Next will create a project name Jikan Anime with id jikan-anime. And finally we create a cluster name jikan-anime in Singapor. The last command switch kubernetes current context to our previous created cluster.

Deploy App to GCP

Last but not least it’s time to deploy our application

As you can see from the output 4 pods and 1 loadbalancer are created as defined in the spec.

Testing

Try to search for anime title by issue a GET request to the following endpoint. Note the external ip from loadbalancer.

Fix Bug

There is a bug in version 1.0.0 of our code, which didn’t property escape the query string. Lets fix this and deploy the patch to production.

Rebuild image

Release patch to production and notice the finall pod image version

Share the news now

Source : Viblo