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?

Roberto Rizzi
  • 1,525
  • 5
  • 26
  • 39

1 Answers1

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" ]
Gari Singh
  • 11,418
  • 2
  • 18
  • 41
  • Modified the above to include gcc in the image as it's not included in the golang base image – Gari Singh Sep 10 '21 at 09:16
  • 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. – Gari Singh Sep 10 '21 at 09:40