Go Dockerfile

Updated at 2018-12-31 03:13

How to build a minimal Docker image based on a Go application source code.

FROM golang:1.9.2
WORKDIR /go/src/
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build .

FROM scratch
COPY --from=0 /go/src/ .
ENTRYPOINT ["/executable"]
  • We use temporary container to build the executable using golang:1.9.2. We create a new directory where Go would the source to be, copy project directory there and build the executable. We disable CGO that would enable the creation of Go packages that call C code, but that won't work when cross-compiling.
  • Then we create the actual image, copying just the executable to the empty image.
  • Finally we set that running the Docker image will just run the Go executable by default.