Simple double stage Golang docker image

Simple double stage Golang docker image

The efficient way to run golang app inside docker is to convert it to the binary and run. It is one of the advantage of compiled programming languages against interpreted programming languages. Compared to all the files needed to run a nodejs application, Golang binaries are much more manageable.

Docker

It is important to make the docker image small as possible to save storage and make the process faster. The solution is Multi Stage Builds. Using multi stage building we can build the app to get the binary and in the second stage copy the binaries and any other dependency in to the base image. We are using the scratch image from docker, Which used to create the base images.

Scratch image does not contain any of the executables normally found inside a container. Remember to add the executables or files needed. As you can see I’ve added CA Certificates.It is also possible to avoid using the scratch image and run it in a base alpine image, And still able create comparatively small image

# First stage
FROM golang:1.14-alpine AS build
RUN apk --update add ca-certificates# Selecting work directory
WORKDIR /src/
# Copy the project directory to the image
COPY . .
# Actual build
RUN CGO_ENABLED=0 go build -o /bin/app ./path/to main# Second stage
FROM scratch
# Copying build 
COPY --from=build /bin/app /bin/app
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crtENTRYPOINT ["/bin/app"]
EXPOSE 8080