Alpine go builds with cgo enabled

It is impossible to compile and run Go program in Docker right away. When you try it, you will get 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 issue, but what if you want that CGO enabled. I prepared docker file based on Alpine Linux which resolves this issue

FROM alpine:edge AS build
RUN apk update
RUN apk upgrade
RUN apk add --update go=1.8.3-r0 gcc=6.3.0-r4 g++=6.3.0-r4
ADD 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
RUN cd /app
COPY --from=build /app/bin/server /app/bin/server
CMD ["bin/server"]

With this dockerfile everything will work as expected. Reason for this issue is that Go from Golang docker image is compiled with standard libraries which are located under /lib64 directory. Alpine use /lib folder to store it’s libraries thus Go executable cannot find them. We resolve this issue by downloading gcc, g++, and go packages right from Alpine repository and use them. With this resolution you use all packages from same Alpine environment.

Shamlessly stolen from:


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

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