Getting Started with Golang on Docker

GolangDocker

Prerequisites

Docker

To follow this tutorial, you need a working installation of Docker on your computer.

Golang

Golang will be useful in this tutorial to test our web server before creating a Docker image. So please make sure that Golang is installed and well configured. For more information please check this documentation and this one too.

Introduction

Golang is an open source programming language developed at Google in 2007. It makes it easy to create simple and efficient software and web apps. It’s currently being used at Google in production for some projects surch as the godoc document server on Google App Engine or Google’s download server (dl.google.com) which delivers large binaries and apt-get packages. It’s also good to know that the entire Docker project is written in Go due to it’s great performance and reliability.
This tutorial is a step by step guide to deploy a simple golang web server on a cloud infrastructure using Docker and Tutum.

Code

For the purpose of this tutorial we are going to build a simple web server that displays a message. It will have no dependencies outside Golang’s standard library and requires no additional package to run. It’s just a simple web server.
Create a file called main.go in your GOPATH and paste the following code:

package main

import(
"fmt"
"net/http"
"runtime"
)

func indexHandler( w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "hello world, I'm running on %s with an %s CPU ", runtime.GOOS,runtime.GOARCH)

}

func main(){
http.HandleFunc("/", indexHandler)
http.ListenAndServe(":8080",nil)
}

This web server is pretty simple. We use http.HandleFunc to handle all requests to “/” with the function indexHandler, then we call http.ListenAndServe in order to block the runtime until the program is terminated.

Concerning the indexHandler function, it takes two arguments:

  • http.ResponseWriter, which will assemble and send the HTTP server response to the client.

  • http.Request, which is the client’s HTTP request.

In this example, by requesting http://localhost:8080 if the server is running on your machine, we will get a hello world message followed by some basic system information we get from runtime.GOOS and runtime.GOARCH which respectively gives us the OS and architecture info.

Now that we are sure our server is working, let’s write a Dockerfile that will help us deploy this tiny app.

Dockerfile

First let’s create a file called Dockerfile in the same directory and paste (and complete) the following content into it:

FROM golang

ADD . /go/src/[Path to your project]
RUN go install [Path to your project]
ENTRYPOINT /go/bin/basic_web_server

EXPOSE 8080

In order to write a good and optimized Dockerfile, please take a look at this article here.

For this tutorial, we are not going to install the whole golang package manually. Instead, we will prefer the official golang Docker image (a Debian image with the latest version of Go installed on top).

Thanks to the ADD instruction, we copy the local package file to the container workdir which is /go in the official golang Docker image. Another way to deal with this is to push your code on github and download the repository while building the image.
Then by using RUN we build the basic_web_server command.
Finally, the ENTRYPOINT keyword will run the basic_web_server command which will launch our web server inside our container.

Those 3 keywords are always used for any kind of golang project Dockerfile, so this one could easily be reused to deploy other golang applications.

We can now build the image using

docker build -t go_basic .

This command will run all the command detailed inside the Dockerfile and tag the final image as go_basic.

Once it’s done, we can run a container from the resulting image with the following command:

docker run -p 8000:8080 -name go_web_server go_basic

-p tells our container to publish the “exposed” port 8080, which we defined in our Dockerfile, to the external port 8000.

-name gives our container the name go_web_server. This flag is not mandatory, but it helps us to keep our Docker containers organized.

Once the container is running we can access our server with a curl command or simply by opening a browser on http://localhost:8000.

We should see something like this:

192_168_59_103_6060

If you are using a Docker daemon on another machine or if you are using boot2docker, you will need to replace localhost with the IP of your machine or VM.

Eventually, we can shut down our container by invoking

docker stop [ID of the go_basic container]

It’s now ready to be deployed.

Deploying on Tutum

Pushing the image in the cloud

The first thing we want to do, is put our go_basic Docker image online on Tutum. One of the fastest way to do this is to use boatyard.io. It’s one of Tutum’s open source projects that builds your Docker image from a Dockerfile directly to the Docker registry of your choice. For more information about boatyard, take a look at Bryan’s article.

Tutum’s Docker registry is: tutum.co. Now we just have to fill out the Boatyard form with our Tutum username and password, paste the Dockerfile we just wrote and push the button Build it.

Screenshot 2015-01-12 12.49.36

Once the build is finished, we can find our go_basic Docker image in the Private images section of Tutum’s service creation wizard.

Screenshot 2015-01-12 12.51.49

However, as we are copying local files to our container in the Dockerfile process we might encounter some difficulties. So instead of the ADD keyword just put a RUN command that downloads a github repository containing your golang code.

Another way of pushing images on our Tutum private registry is to use the terminal. First we need to enter our credentials using:

docker login tutum.co

This will ask us to input our username, password and email address.

Now we need to correctly tag our image

docker tag go_basic tutum.co/yourusername/go_basic

Then we can directly push our image with

docker push tutum.co/yourusername/go_basic

If you need more information about pushing images to Tutum’s Docker registry, please check this documentation

Creating a node and a service on Tutum

Now that our image is available on Tutum’s private Docker registry, the first step will be to create a node cluster. From the Node dashboard, click on the Launch new node cluster button. We just need to fill the following form and then click on Launch node cluster.

Create_a_node_cluster___Tutum

It could take up to 10 minutes for our node to deploy.

Once it’s done, we will have to create a service using our go_basic image we just pushed online. Just go to the Services tab and click on Create service or Launch first service if your dashboard is empty.

The image is available in the Private Image section. Select it to move on to the next step.

Now it’s time to configure our container. There is not much to do, but we must not forget to publish our container port so we can access the golang web server once it’s deployed.

New_Service_Wizard___Tutum

By clicking on Create and deploy, we will deploy and launch our container and the golang web server.

go-basic___Tutum

 

Once it’s deployed let’s go to the Service dashboard where we should see our go_basic container up and running. By clicking on the expand icon (little arrow) on it’s left, we can see the individual container.

Service_dashboard___Tutum

If we click on the individual container link go-basic-1 we will be redirected to the container’s endpoints tab which displays a link to access our golang web server.

Click on it and you should see our web server running!

We also have some extra information about how our service is running thanks to the Logs and Monitoring tab.

Conclusion

We now have a live golang web application deployed on a cloud infrastructure with Tutum. We learned how to build a specific Dockerfile for golang projects, how to deploy the image on Tutum’s Docker registry, that the deployment required no external libraries, and the configuration was very simple without the need for extra knowledge.

http://maximeheckel.com

Tagged with: , , ,
Posted in Tutorial
12 comments on “Getting Started with Golang on Docker
  1. Great intro. Lots of action around Go as of late, for good reason.

  2. Thomas Wood says:

    godoc.org does not run on App Engine as stated in the article.

  3. […] used the code and explanation at this blog to create a very (extremely) basic go web app. The blog also has a few explanations of the code […]

  4. heitorts says:

    Hey, thanks for the post! Just a small thing, the link to boatyard.io is broken

  5. This means that 50 dollars per kilogram of polysilicon production costs, the industry’s enterprises,
    “life and death mark. In sum, prices are taking place whereas effectivity is rising for this various gas technology. The one possible drawback to the photovoltaic panel is that is very expensive and new information and innovation can help lower the charge.

  6. Lader would speak on behalf of the school system atcolleges and universities across
    the country. However most hospitals and medical offices require they remove certain piercings and cover any visible tattoos despite the number of physicians and
    surgeons that have undisclosed tattoos. Interview questions which are asked to find out about
    your experiences can be turned into answers which directly address the organisation’s
    needs.

  7. That way the significance of delving into models of past
    bargaining agreements can be fully emphasized, as essential to project management learning disciplines.
    Counter-Strike: Global Offensive was built with the latest version of Valve’s
    Source Engine. Tend not to stress though, between rounds
    you are able to spend-your entire earned money for your round.

  8. John says:

    I have a web api in go deployed in a docker container. But it is behaving differently when you run in docker with regards to httpstatuscodes. For any validation errors with 404/500 it replaces the formatted validation messages with a “Bad Request” message. The issue is only when it is installed in docker container.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories
%d bloggers like this: