GO / Golang run project on Docker issues - Cannot find packages (internal folders)

1.2k views Asked by At

I'm trying to run my first Golang project on Docker. While I succeeded with a simple "hello world" application, I'm facing some difficulties with a slightly more structured project.

The project has some folders inside which I imported in the main.go file. When I try to run my solution on Docker, it gets stuck while loading those "packages".

This is my Dockerfile

FROM golang:1.17-alpine

WORKDIR /app

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

COPY *.go ./

RUN go env GOROOT
RUN go build -o /my-api

EXPOSE 8080

CMD [ "/my-api" ]

This is the error I get

Step 8/10 : RUN go build -o /my-api
 ---> Running in c1c9d1058caa
main.go:10:2: package my-api/Repositories is not in GOROOT (/usr/local/go/src/my-api/Repositories)
main.go:11:2: package my-api/Settings is not in GOROOT (/usr/local/go/src/my-api/Settings)

One thing I noticed is that this path

/usr/local/go/src/my-api/Settings

should be

/usr/local/gocode/src/my-api/Settings

on my local machine

Here is a glimpse into how my project is structured

enter image description here

Any ideas?

1

There are 1 answers

2
Gari Singh On

Why not use a Dockerfile like:

FROM golang:1.17-alpine
RUN apk add build-base

WORKDIR /app

ADD . /app
RUN go build -o /my-api

EXPOSE 8080

CMD [ "/my-api" ]

This will copy the contents of the local directory on your local machine to /app in the image.

Note: To build a "production grade" image, I'd use a multistage build:

FROM golang:1.17-alpine as builder
RUN apk add build-base

WORKDIR /app
ADD . /app
RUN go build -o /my-api

FROM alpine:3.14
COPY --from=builder /my-api /
EXPOSE 8080
CMD [ "/my-api" ]