Building Go apps with private modules in Docker

笑着哭i 提交于 2021-02-07 09:30:37

问题


I'm trying to build a go project in a docker container that relies on private submodules.

I was hoping that --mount=type=ssh would pass my ssh credentials to the container and it'd work. Currently I can build locally with just make the GOPRIVATE variable set and the git config update.

Here is my relevant Dockerfile currently

# syntax = docker/dockerfile:experimental

FROM golang:1.14.3-alpine AS build
RUN apk add --no-cache git \
                openssh-client \
                ca-certificates

WORKDIR /src
ENV GIT_TERMINAL_PROMPT=1
ENV GOPRIVATE="gitlab.com/company_foo"
RUN git config --global url."ssh://git@gitlab.com".insteadOf "https://gitlab.com"



# Authorize SSH Host
# Skip Host verification for git
RUN mkdir -p /root/.ssh && \
    chmod 0700 /root/.ssh && \
    ssh-keyscan gitlab.com > /root/.ssh/known_hosts &&\
    chmod 644 /root/.ssh/known_hosts && touch /root/.ssh/config \
    && echo "StrictHostKeyChecking no" > /root/.ssh/config

COPY go.mod go.sum .
RUN --mount=type=ssh mkdir -p /var/ssh && \
    GIT_SSH_COMMAND="ssh -o \"ControlMaster auto\" -o \"ControlPersist 300\" -o \"ControlPath /var/ssh/%r@%h:%p\"" \
    go mod download
COPY . .
RUN --mount=type=cache,target=/root/.cache/go-build go build -o api-server ./cmd/api-server
RUN --mount=type=cache,target=/root/.cache/go-build go build -o migrations ./cmd/migrations

I've also tried adding a CI_JOB_TOKEN with

RUN echo -e "machine gitlab.com\nlogin gitlab-ci-token\npassword ${CI_JOB_TOKEN}" > ~/.netrc

but this also didn't work. Perhaps I did it wrong.

All of this results in the failure:

 revision v0.0.3: unknown revision v0.0.3

relating to one of our private repos.

Any advice would be appreciate.

I'm absolutely at a lost.


回答1:


This workes for me.

FROM golang:1.14
ARG USERNAME=user1
ARG PASSWORD=secret

WORKDIR /app
ADD . .
ENV GOPRIVATE=private.git.local/*
RUN echo "machine private.git.local login $USERNAME password $PASSWORD" > ~/.netrc

RUN go build -o testGo main.go
CMD ["/app/testGo"]



回答2:


pass your gitlab_token to docker file from gitlab_ci.yaml and do the following steps

RUN git config --global url."https://oauth2:$GITLAB_TOKEN@gitlab.com/".insteadOf "https://git@gitlab.com/"

add your repo as GO_PRIVATE

ENV GOPRIVATE=gitlab.com/*

copy .netrc file to docker root

COPY confidential/.netrc /root/.netrc

.netrc file will have the following structure

machine gitlab.com
login gitlab_user
password p@$$word


来源:https://stackoverflow.com/questions/62960934/building-go-apps-with-private-modules-in-docker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!