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