Dockerizing Your Go Application

Prerequisites

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 :)

https://www.docker.com/get-docker

https://golang.org/


Jumping In

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

FROM scratch
ADD 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:
application:
container_name: application
build: .
ports:
- 80:80
environment:
- 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:

build:
./build.sh
docker-build: build
docker-compose up --build
docker-up:
docker-compose up
docker-rm:
docker rm application
default: build

Also, I put some stuff inside a build.sh 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 "github.com/gin-gonic/gin"
import "os"
import "net/http"
func main() {
router := gin.Default()

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

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 github.com/go-gonic/gin

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 http://0.0.0.0/ 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! ❤