From bc9708c14d8256ed297006c0a2972e290dbc7759 Mon Sep 17 00:00:00 2001 From: Thomas Ferrandiz Date: Mon, 29 Apr 2024 15:38:31 +0000 Subject: [PATCH] Optimize build-time by using cross-compilation --- Dockerfile | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/Dockerfile b/Dockerfile index 3aff93a..fa0e5dd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,25 +1,35 @@ #ARG BCI_IMAGE=registry.suse.com/bci/bci-micro ARG GO_IMAGE=rancher/hardened-build-base:v1.21.9b1 + +# Image that provides cross compilation tooling. +FROM --platform=$BUILDPLATFORM rancher/mirrored-tonistiigi-xx:1.3.0 as xx + #FROM ${BCI_IMAGE} as bci -FROM ${GO_IMAGE} as builder +FROM --platform=$BUILDPLATFORM ${GO_IMAGE} as base-builder +# copy xx scripts to your build stage +COPY --from=xx / / +RUN apk add file make git clang lld +ARG TARGETPLATFORM # setup required packages RUN set -x && \ - apk --no-cache add \ - file \ + xx-apk --no-cache add \ gcc \ - git \ + musl-dev \ + build-base \ libselinux-dev \ - libseccomp-dev \ - make + libseccomp-dev + # setup the build +FROM base-builder as metrics-builder ARG PKG="github.com/kubernetes-incubator/metrics-server" ARG SRC="github.com/kubernetes-sigs/metrics-server" ARG TAG=v0.7.1 -ARG ARCH="amd64" +ARG ARCH RUN git clone --depth=1 https://${SRC}.git $GOPATH/src/${PKG} WORKDIR $GOPATH/src/${PKG} RUN git fetch --all --tags --prune RUN git checkout tags/${TAG} -b ${TAG} +RUN go mod download RUN go install -mod=readonly -modfile=scripts/go.mod k8s.io/kube-openapi/cmd/openapi-gen && \ ${GOPATH}/bin/openapi-gen --logtostderr \ -i k8s.io/metrics/pkg/apis/metrics/v1beta1,k8s.io/apimachinery/pkg/apis/meta/v1,k8s.io/apimachinery/pkg/api/resource,k8s.io/apimachinery/pkg/version \ @@ -27,19 +37,29 @@ RUN go install -mod=readonly -modfile=scripts/go.mod k8s.io/kube-openapi/cmd/ope -O zz_generated.openapi \ -h $(pwd)/scripts/boilerplate.go.txt \ -r /dev/null; -RUN GO_LDFLAGS="-linkmode=external \ +# cross-compilation setup +ARG TARGETPLATFORM +RUN xx-go --wrap && \ + CGO_ENABLED=1 \ + GO_LDFLAGS="-linkmode=external \ -X ${PKG}/pkg/version.Version=${TAG} \ -X ${PKG}/pkg/version.gitCommit=$(git rev-parse HEAD) \ -X ${PKG}/pkg/version.gitTreeState=clean \ " \ go-build-static.sh -gcflags=-trimpath=${GOPATH}/src -o bin/metrics-server ./cmd/metrics-server RUN go-assert-static.sh bin/* +RUN xx-verify --static bin/* RUN if [ "${ARCH}" = "amd64" ]; then \ go-assert-boring.sh bin/*; \ fi -RUN install -s bin/* /usr/local/bin +RUN install bin/metrics-server /usr/local/bin + +FROM ${GO_IMAGE} as strip_binary +#strip needs to run on TARGETPLATFORM, not BUILDPLATFORM +COPY --from=metrics-builder /usr/local/bin/metrics-server /usr/local/bin RUN metrics-server --help +RUN strip /usr/local/bin/metrics-server FROM scratch as k8s-metrics-server -COPY --from=builder /usr/local/bin/metrics-server / +COPY --from=strip_binary /usr/local/bin/metrics-server / ENTRYPOINT ["/metrics-server"]