Video:

A Simple Dockerfile For Go Applications

March 12, 2023

Course Instructor: Elliot Forbes

Hey Gophers! My name is Elliot and I'm the creator of TutorialEdge and I've been working with Go systems for roughly 5 years now.

Twitter: @Elliot_f

At this point in the course, we should have at least a basic grasp as to how we can create docker images and run them as containers.

In this video, we’ll be expanding on the concepts we’ve covered and look at how we can build a single-stage Dockerfile for our Go applications.

Our Go App

Let’s start off by creating a lightweight Go application that runs on localhost:3000 and returns Hello World whenever someone hits the server.

main.go
package main

import (
    "fmt"
    "html"
    "log"
    "net/http"
)

func main() {

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World")
    })

    log.Fatal(http.ListenAndServe(":3000", nil))

}

Our Dockerfile

Now that we have our Go app in place, and we’ve verified it works and runs locally. Let’s have a look at building out our Dockerfile

The first thing we’ll want to do is choose a suitable base image. In this case, I want to build my app using the latest version of Go, and as such I can use the official golang image and specify the :latest tag like so:

FROM golang:latest

This image should have the go CLI installed and available on its path, ready to use.

We then need to think about what files and directories we want within our image. As it stands, if we were to build this dockerfile as an image and run it, it wouldn’t have our .go files inside of it and we wouldn’t be able to build and run our app.

We can fix that by firstly creating a directory within our Dockerfile using the WORKDIR command like so:

FROM golang:latest
WORKDIR /app
# from this point on, any commands will be executed within this /app directory

We now have a directory we can work in that’s separate from the other directories already on the base image. We just need to figure out how we can copy our application files to this new /app directory:

FROM golang:latest
WORKDIR /app
COPY . .

Perfect, using the COPY command, we’ve been able to copy the contents of the current directory our Dockerfile lives in, into the newly created /app directory within our image.

Building and Running our App

We have the Go cli available to us, we also have our apps source files ready. The final step is building and running our app:

FROM golang:latest
WORKDIR /app
COPY . .
RUN go build -o main ./...
CMD ["./main"]

With these final two commands, we’ve should now build our application and create a binary called main. After this has successfully built, we then specify the CMD command within our image which calls our ./main binary executable.

Building our Docker Image

$ docker build -t my-go-app .
$ docker run -it -p 3000:3000 my-go-app

http://localhost:3000