Golang and Docker for development and production

Josh McMenemy
Feb 12, 2017 · 3 min read
Image for post
Image for post

Why you would want to use Docker for dev and production:

  • Quick on-boarding (anyone with Docker installed can start coding without setting up any other dependencies or GOPATH variables);
  • Dev environment is the same as production.

What you will learn in this article:

  • How to write a single Dockerfile that allows you to build a dev container that will reload code changes you make locally (without rebuilding the container) and a production container that serves the binary build;
  • This is done using shared volumes, pilu/fresh, and build arguments.

How to do it:

To get started run the following commands in Terminal:

$ mkdir myGoDockerApp
$ cd myGoDockerApp
$ mkdir app
$ cd app
$ touch app.go
$ cd .. 
$ touch Dockerfile
  • ARG app_env => allows app_env to be set during build (defaults to empty string)
  • ENV APP_ENV $app_env => sets an environment variable to app_env argument, this way the variable will persist in the container for use in code
  • COPY ./app /go/src/github.com/user/myProject/app => copy the local project code into a directory in the container’s GOPATH
  • WORKDIR /go/src/github.com/user/myProject/app => set this to the working directory so all subsequent commands will run from this directory
  • RUN go get ./ => install all dependencies
  • RUN go build => build the binary
  • CMD if … => If arg_env was set to production run the binary otherwise use pilu/fresh to hot reload the code when it changes
  • EXPOSE 8080 => This is the port the app was programed to serve on
$ docker build ./
$ pwd
$ docker run -it -p 8080:8080 -v [put your path here]/app:/go/src/github.com/user/myProject/app [image id]
$ docker build ./ --build-arg app_env=production
$ docker run -i -t -p 8080:8080 [image id]


Keeping developers informed.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store