Home > Blockchain >  Dockerizing Go API not working without setting up git project repo
Dockerizing Go API not working without setting up git project repo

Time:11-12

I have a very simple project - a Go API with the following directory structure

├── Dockerfile
├── go.mod
├── go.sum
├── main.go
└── user
    ├── repository.go
    └── user.go

My Dockerfile looks like so

FROM golang:1.17-alpine
WORKDIR /app
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY *.go ./
RUN go build -o /api
CMD [ "/api" ]

and I keep getting this error:

[7/7] RUN go build -o /api: #11 0.462 main.go:4:2: package api/user is not in GOROOT (/usr/local/go/src/api/user)

After reading a bit it looks like I might need to setup a github repository and let go pull the code from git? I think that's honestly crazy since the code is RIGHT THERE in the Docker image.

How can I build/Dockerize this Go project without setting up the git repo like github.com/alex/someproject? Asking because I don't want to publish this onto github - this should be dead simple from local.

CodePudding user response:

You do not need to publish your Go code to a service like github.com just to be able to compile it.

All you need to do is to make sure that the code you want to compile is on the machine on which you are compiling it. Your go build command is failing because the package mentioned in the error message is nowhere on the machine to be found.


The following assumes that the Go project itself is in order and you are able to compile it on your local machine. If that is not the case and the answer that follows does not help you resolve the problem then you'll need to include more information in your question, like the content of your go.mod file, main.go file, and also the user package.

Note that COPY *.go ./ will NOT copy all the go files recursively, i.e. it will not copy the files in the ./user/ directory.

COPY:

Each <src> may contain wildcards and matching will be done using Go’s filepath.Match rules.

filepath.Match:

The pattern syntax is:

pattern:
  { term }
term:
  '*'         matches any sequence of non-Separator characters
  '?'         matches any single non-Separator character
  '[' [ '^' ] { character-range } ']'
              character class (must be non-empty)
  c           matches character c (c != '*', '?', '\\', '[')
  '\\' c      matches character c

character-range:
  c           matches character c (c != '\\', '-', ']')
  '\\' c      matches character c
  lo '-' hi   matches character c for lo <= c <= hi

Notice that the '*' term matches any sequence of non-Separator characters, this means that *.go will not match foo/bar.go because of the separator /.


It should be enough to have the following in your Dockerfile:

FROM golang:1.17-alpine

WORKDIR /app
COPY . ./
RUN go build -o /api

CMD [ "/api" ]

But if you want to be selective about the files you copy, then you can do:

COPY go.mod ./
COPY go.sum ./
COPY user/ ./user/
COPY *.go ./
  • Related