iooi
iooi

Reputation: 523

How to build a golang docker image with go.mod in a sub folder?

I have a go project folder as

my_project
|- common
    |- library
        |- golang
|- my_app
    |- Dockerfile
    |- go.mod
    |- go.sum
    |- main.go

The Dockerfile is from google cloud official example:

FROM golang:1.15-buster as builder

WORKDIR /app

COPY go.* ./
RUN go mod download

COPY . ./

RUN go build -mod=readonly -v -o server

FROM debian:buster-slim
RUN set -x && apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
    ca-certificates && \
    rm -rf /var/lib/apt/lists/*

COPY --from=builder /app/server /server

CMD ["/server"]
    

The go.mod is using a common library in the same project but belongs to a private repository:

module run

go 1.15

require (
    github.com/my/private/my_project/common/library/golang v0.0.0-00010101000000-000000000000
)

replace (
    github.com/my/private/my_project/common/library/golang => ../common/library/golang
)

When I run docker build under my_app path to build an image, got this error:

...
 => ERROR [builder 4/6] RUN go mod download                                                                                                                                                                  1.0s
------
 > [builder 4/6] RUN go mod download:
#13 0.934 go: github.com/my/private/my_project/[email protected]: parsing /common/library/golang/go.mod: open /common/library/golang/go.mod: no such file or directory
------
executor failed running [/bin/sh -c go mod download]: exit code: 1

Why can't it find the go.mod file in the current path but using /common/library/golang/go.mod?

Upvotes: 3

Views: 8272

Answers (2)

Anand
Anand

Reputation: 316

You could have a separate Dockerfile for both of the projects/services & stitch them together in docker-compose.yml file with depends_on & same network

Upvotes: 0

colm.anseo
colm.anseo

Reputation: 22027

Your docker context (docker build .) only sees files in the . directory - not the parent directory and thus not ../common/.

To fix this, move the Dockerfile to a higher directory & update all the build references to the various sub-directories, so they will all be accessible from this more encompassing docker context.

Upvotes: 6

Related Questions