Search code examples
dockergodependenciesdependency-managementgo-modules

How to use go mod with local package and docker?


I have two go modules github.com/myuser/mymainrepo and github.com/myuser/commonrepo

Here is how i have the files in my local computer

- allmyrepos  
 - mymainrepo
   - Dockerfile
   - go.mod
 - commonrepo
   - go.mod

mymainrepo/go.mod

...
require (
  github.com/myuser/commonrepo
)

replace (
  github.com/myuser/commonrepo => ../commonrepo
)

It works well i can do local development with it. Problem happens when i'm building docker image of mymainrepo

mymainrepo/Dockerfile

...
WORKDIR /go/src/mymainrepo

COPY go.mod go.sum ./
RUN go mod download


COPY ./ ./
RUN go build -o appbinary
...

Here replace replaces github.com/myuser/commonrepo with ../commonrepo but in Docker /go/src/commonrepo does not exists.

I'm building the Docker image on CI/CD which needs to fetch directly from remote github url but i also need to do local development on commonrepo. How can i do both ?

I tried to put all my files in GOPATH so it's ~/go/src/github.com/myuser/commonrepo and go/src/github.com/myuser/mymainrepo. And i removed the replace directive. But it looks for commonrepo inside ~/go/pkg/mod/... that's downloaded from github.


Solution

  • Create two go.mod files: one for local development, and one for your build. You can name it go.build.mod for example.

    Keep the replace directive in your go.mod file but remove it from go.build.mod.

    Finally, in your Dockerfile:

    COPY go.build.mod ./go.mod
    COPY go.sum ./