Skip to content

Commit

Permalink
Optimize build-time by using cross-compilation
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasferrandiz committed Apr 29, 2024
1 parent 35d7917 commit d027c19
Showing 1 changed file with 30 additions and 10 deletions.
40 changes: 30 additions & 10 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,45 +1,65 @@
#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 \
-p ${PKG}/pkg/generated/openapi/ \
-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=metrics-builder /usr/local/bin/metrics-server /
ENTRYPOINT ["/metrics-server"]

0 comments on commit d027c19

Please sign in to comment.