Picture

Hi, I'm Boopathi Rajaa.

Hacker, Dancer, Biker, Adventurist

Dockerfile for golang applications

A few headers

We will assume that we are deploying our applications on Ubuntu.

    FROM ubuntu:12.04
    MAINTAINER My Name <me@domain.tld>

Install dependencies

Add Mercurial Repository (if necessary)

# Mercurial
RUN echo 'deb http://ppa.launchpad.net/mercurial-ppa/releases/ubuntu precise main' > /etc/apt/sources.list.d/mercurial.list
RUN echo 'deb-src http://ppa.launchpad.net/mercurial-ppa/releases/ubuntu precise main' >> /etc/apt/sources.list.d/mercurial.list
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 323293EE

Install dependencies

RUN apt-get update
RUN apt-get install -y curl git bzr mercurial
  • Curl is required to download Go tar ball.
  • git, bazaar and mercurial are used by go get to download your application dependencies.

Install Go

RUN curl -s https://go.googlecode.com/files/go1.2.linux-amd64.tar.gz | tar -v -C /usr/local/ -xz

Configure Environment for Go

ENV PATH /usr/local/go/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
ENV GOPATH /go
ENV GOROOT /usr/local/go

Hack - To cache go get

RUN go get github.com/myname/my-golang-project

This is called immediately before adding the project files to the repo and essentially before performing a go get from inside the repo's directory within the container. Docker's ADD doesn't support caching until 0.7.3. Adding the source files to the container and then performing a go get doesn't utilize the cache. It downloads all the dependencies once again and is time consuming.

Add source files to the container

WORKDIR /go/src/github.com/myname/my-golang-project
ADD . /go/src/github.com/myname/my-golang-project

Fetch new dependencies if any

RUN go get

Install application

RUN go build

If your app exposes a port, expose it

EXPOSE 8080

Set entrypoint

ENTRYPOINT ./my-golang-project -option value args

When you set the entrypoint in docker, the entire container behaves as if it was that single application/executable. You can daemonize this with docker run -d .

A simpler method

I have done the first few parts and pushed it to index.docker.io. You can create your image with that as the base image. And this is how you do it.

FROM boopathi/go:latest
MAINTAINER myname <emailaddress>
WORKDIR /go/src/github.com/myname/my-golang-repo
RUN go get github.com/myname/my-golang-repo
ADD . /go/src/github.com/myname/my-golang-repo
RUN go get
RUN go build
EXPOSE 8080
ENTRYPOINT ./my-golang-project -option value args

Links

Go dev environment docker image:  https://index.docker.io/u/boopathi/go/