Build statically linked binaries (#156)

Prior to this commit, we released two linux binaries:

* `dbmate-linux-amd64` (built with cgo, dynamically linked)
* `dbmate-linux-musl-amd64` (built without cgo, statically linked, no sqlite support)

The statically linked binary is desirable for alpine linux users (or anyone else using musl libc or minimal docker images). The original reason for having two separate binaries was that the easiest method to create a static binary for go is to set `CGO_ENABLED=0`, but unfortunately this also prevented us from building sqlite (which requires cgo).

With this commit, all linux and windows binaries are explicitly statically linked while leaving cgo enabled. Hat tip to https://www.arp242.net/static-go.html which explained the necessary flags to enable this.

As an added bonus, the `dbmate` docker image now now uses a `scratch` base rather than `gcr.io/distroless/base`, reducing the image size from 26.7 MB to 9.8 MB.
This commit is contained in:
Adrian Macneil 2020-08-11 13:05:55 -07:00 committed by GitHub
parent df461ff6c7
commit 4581acafad
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 20 deletions

View file

@ -1,8 +1,6 @@
# build image
FROM techknowlogick/xgo:go-1.14.x as build
WORKDIR /src
ENTRYPOINT []
CMD ["/bin/bash"]
# enable cgo to build sqlite
ENV CGO_ENABLED 1
@ -30,7 +28,10 @@ RUN go mod download
COPY . ./
RUN make build
ENTRYPOINT []
CMD ["/bin/bash"]
# runtime image
FROM gcr.io/distroless/base
FROM scratch
COPY --from=build /src/dist/dbmate-linux-amd64 /dbmate
ENTRYPOINT ["/dbmate"]