An Easier Way to Create Tiny Golang Docker Images

Travis Reeder
Jul 31, 2015 · 2 min read

Atlassian 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

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

2. Build Static Binary

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 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

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:

Travis on Docker

My posts about Docker.

Travis on Docker

My posts about Docker.

Travis Reeder

Written by

Founder, CTO at GoChain - Building and breaking things

Travis on Docker

My posts about Docker.