An Easier Way to Create Tiny Golang Docker Images


Docker_Golang_IronAtlassian just posted a blog post about creating Static Go binaries with Docker on OSX which shows how to make a tiny little Docker image (~6MB total) with your Go program inside. When I read it, I thought “this is cool… but way too complicated”. I’ve been using Docker a lot lately and knew there had to be an easier way. Here is that way.

So we have our little Go program, this one being a simple web server using Gorilla mux for routing:

Now let’s get down to business.

1. Vendor Dependencies

The first thing we want to do is vendor our dependencies. We’re going to use godep here:

go get github.com/gorilla/mux
godep save -r

2. Build Static Binary

Now we build a static binary for our program. Yes, this looks scary, but just copy and paste it and you’re golden:

docker run --rm -it -v "$GOPATH":/gopath -v "$(pwd)":/app -e "GOPATH=/gopath" -w /app golang:1.4.2 sh -c 'CGO_ENABLED=0 go build -a --installsuffix cgo --ldflags="-s" -o hello'

You’ll end up with a binary called `hello`.

3. Build Tiny Docker Image

Now we embed that `hello` binary in the smallest Docker image possible. The Dockerfile looks like this:

Now that we have the Dockerfile, just run:

docker build -t treeder/go-hello-http .

That will build an image named `treeder/go-hello-http` and it should only be about~4MB!!

4. Run/Test It

Now run it:

docker run --rm -it -p 8080:8080 treeder/go-hello-http

Surf to: http://localhost:8080/ . Boom.

That’s it. You now have a super simple, super tiny Docker image containing your Go program. If you want to share it with people, push it up to Docker hub and tell people to `docker run your/image`.

All the source code and everything can be found here:https://github.com/treeder/tiny-golang-docker

If you want to read more about developing your apps with Docker, check out my previous post.

Other topics that may interest you:  

Docker Docker Images Go Golang Images