0

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?

5
  • RUN go env GOROOT what is the purpose of this? Commented Sep 10, 2021 at 8:36
  • Can you add GOROOT and GOPATH environment variables values? Commented Sep 10, 2021 at 8:38
  • 2
    COPY *.go ./ does not copy the Repositories and Settings folders. Commented Sep 10, 2021 at 8:49
  • @dwij sorry, it is nothing really. It is a leftover of something I was trying to do Commented Sep 10, 2021 at 8:50
  • @Gari Singh thanks for your answer. How can I make it copy also the folders? Commented Sep 10, 2021 at 8:51

1 Answer 1

2

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" ]
Sign up to request clarification or add additional context in comments.

2 Comments

Modified the above to include gcc in the image as it's not included in the golang base image
If you are looking to build a production container, then I'd use a multistage build as well so that you don't ship Go and the build tools in your image. I'll modify my answer above this option as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.