Docker_Golang_IronOverview

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 is a simple web server using Gorilla mux for routing:

 

Now let’s get down to business.

 

Table of Contents

Related Reading: Docker inc isn't dead

Achieve Cloud Elasticity with Iron

Speak to us to find how you can achieve cloud elasticity with a serverless messaging queue and background task solution with free handheld support.

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

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

docker-container

Iron.io Serverless Tools

Speak to us to learn how IronWorker and IronMQ are essential products for your application to become cloud elastic.

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

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.

Iron

Unlock the Cloud with Iron.io

Find out how IronWorker and IronMQ can help your application obtain the cloud with fanatical customer support, reliable performance, and competitive pricing.

2 Comments

  1. Richard Bucker on October 13, 2015 at 5:27 pm

    do you have the go 1.5 params for static linking?

  2. Cody Weber on June 30, 2018 at 6:17 pm

    I think I need a few more details, because that scary statement just errors for me and I really don’t even know where to start to fix it.

    docker: Error response from daemon: invalid volume spec “:/gopath”: invalid volume specification: ‘:/gopath’.

Leave a Comment





This site uses Akismet to reduce spam. Learn how your comment data is processed.