Dockerizing Your Go Application


Craig Childs
2 min readMar 30, 2017

I’m going to assume you’ve got Go and Docker installed locally, if you haven’t then head on over to these links and head back here once you’re done :)

Jumping In

So first we’ll create our Dockerfile ready to run our compiled web server, called main

FROM scratchADD main /EXPOSE 80
CMD ["/main"]

I like to use Docker-Compose because it makes it really easy to setup a Docker based environment on your local machine. This is the docker-compose.yml we’ll be using.

version: "2"services:
container_name: application
build: .
- 80:80
- HOST=:80

This defines our container, ensures we’re opening port 80 and allows us to pass through aHOST environment variable.

For ease of running this I like to setup some commands in a Makefile too, if you don’t want to do so just use the commands nested inside.

Inside the Makefile:

docker-build: build
docker-compose up --build
docker-compose up
docker rm application
default: build

Also, I put some stuff inside a to keep this Makefile clean. You can see that here:

# Remove the existing binary
rm main
# Build a Go binary for our linux scratch image
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
# Build the docker image
docker build .

Now let’s start adding some code to run! Create a new file main.go and inside put the following.

import ""
import "os"
import "net/http"
func main() {
router := gin.Default()

router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"Hello": "World",

The above code will start a new server using the Gin framework running on port 80. To ensure your Go environment has the Gin dependency run go get

Once you’ve done that we can then get things up and running. If you’ve got the Makefile in your project you should run make docker-build

If you then visit your browser at you should see the following:

"Hello": "World"

Et Voila! We’ve done it! We’ve successfully setup a simple Go web server running on a very small docker container.

If you’ve enjoyed this article please recommend it and follow me on here for some more adventures with Go. If you have any questions or spot a mistake please let me know so I can update it :) Happy coding! ❤



Craig Childs

Multi-pronged web developer with a passion for cutting edge tooling!