如何以非root用户身份构建go docker镜像?

时间:2020-03-07 17:25:40

标签: docker go

我很难从base-image go.13中以非root用户身份构建docker映像。

我的主要问题是,在go1.12之前可以设置go env变量GOCACHE="off",但是由于go1.12,这不再是一个选择。

这是我当前的Dockerfile,在Step: RUN mkdir ./build && go mod download && go mod verify && CGO_ENABLED=0 GOOS=linux go build -o app -x -mod vendor -trimpath返回输出

failed to initialize build cache at /nonexistent/.cache/go-build: mkdir /nonexistent: permission denied

# Go version
FROM golang:1.13 AS build-env
RUN chmod -R o=,g=rwX $GOPATH/
RUN mkdir /service

ENV USER=trevorjo
ENV UID=10001

# create a sytstem group dev with no password, no home directory set, and no shell so prevents the user form
# being a login account and reduces the attack vector
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
${USER}
#RUN groupadd -r dev && \
#useradd -r -s /bin/false -g dev trevorjo sudo
WORKDIR /service
COPY . /service
# change ownership of all /service content to created user
RUN chown -R trevorjo /service
USER trevorjo
#RUN echo "trevorjo ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/user && \
#chmod 0440 /etc/sudoers.d/user
# GOCACHE disable as get a permission denied error due to running as non root user
RUN mkdir ./build && \
go mod download && \
go mod verify && \
CGO_ENABLED=0 GOOS=linux go build -o app -x -mod vendor -trimpath

FROM scratch AS run-env
WORKDIR /build
COPY --from=build-env /service/build/app /build/
ENTRYPOINT ["/build/app"]

0 个答案:

没有答案