以前写的golang项目一直使用的都是公开的module,最近使用私有gitlab仓库的module时,发现go get mod时需要输入用户名密码,开发环境还好解决,手动输一次让他记住就好了。但是项目正式上线,通过公司统一的jenkins Pipeline执行构建时,没有办法去手动输用户名密码。
Dockerfile配置
要解决这个问题,可以通过.netrc文件来处理。Dockerfile如下:
FROM mirror.ccs.tencentyun.com/library/golang:1.17 as builder
ARG GIT_USR
ARG GIT_PWD
ENV GOPROXY=https://goproxy.cn,direct
ENV GOPRIVATE=stash.xxxx.com
ENV GOOS=linux
ENV GIT_TERMINAL_PROMPT=1
WORKDIR /build
COPY . ./
RUN go env -w GOPRIVATE=stash.xxxx.com \
&& echo "machine stash.xxxx.com login ${GIT_USR} password ${GIT_PWD}" > ~/.netrc \
&& GO111MODULE=on CGO_ENABLED=0 GOOS=${GOOS} GOPROXY=${GOPROXY} go build -o=knative-audit-log
################################################################################
## MAIN STAGE ##
################################################################################
# Copy the manager into the distroless image.
FROM mirror.ccs.tencentyun.com/library/alpine:3.13
RUN echo 'https://mirrors.cloud.tencent.com/alpine/v3.13/main' > /etc/apk/repositories \
&& echo 'https://mirrors.cloud.tencent.com/alpine/v3.13/community' >>/etc/apk/repositories \
&& apk update && apk add tzdata && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone
WORKDIR /usr/local/app
COPY --from=builder /build/knative-audit-log /usr/local/app/knative-audit-log
RUN chmod 755 /usr/local/app/knative-audit-log
ENTRYPOINT ["/usr/local/app/knative-audit-log"]
重点在3,4行和15行,3,4行通过传入GIT_USR和GIT_PWD两个参数到docker构建内,第15行生成.netrc配置。
现在我们就可以通过传参的方式来构建了:
docker build -t hub.docker.com/xxx/knative-audit-log:v0.1 --build-arg GIT_USR=**** --build-arg 'GIT_PWD=****' -f ./Dockerfile .