Alpine go builds with cgo enabled

It is impossible to compile and run Go programs in Alpine images right away. When you try it, you will get a not found error. This is caused by CGO. Most resolutions found on the Internet suggest to disable CGO

$ CGO_ENABLED=0 go install -a [your_package]

This will fix the issue, but what if you want that CGO enabled. I prepared a Dockerfile based on Alpine Linux which resolves this issue

FROM alpine:edge AS build
RUN apk add --no-cache --update go gcc g++
WORKDIR /app
ENV GOPATH /app
COPY src /app/src
RUN go get server # server is name of our application
RUN CGO_ENABLED=1 GOOS=linux go install -a server

FROM alpine:edge
WORKDIR /app
RUN cd /app
COPY --from=build /app/bin/server /app/bin/server
CMD ["bin/server"]

With this Dockerfile everything will work as expected. The reason for this issue is that Go from the Golang Docker image is compiled with standard libraries which are located under the /lib64 directory. Alpine uses the /lib folder to store its libraries which is why the Go executable cannot find them. We resolve this issue by downloading the gcc, g++, and go packages right from the Alpine repository. With this resolution you use all packages from same Alpine environment.

Shamelessly stolen from:

  • http://kefblog.com/2017-07-04/Golang-ang-docker

An alternative is to install Alpine’s build tools through its meta package:

RUN apk add --no-cache git make build-base