Home > Mobile >  Building a Docker container for Golang code: package PACKAGE_NAME is not in GOROOT
Building a Docker container for Golang code: package PACKAGE_NAME is not in GOROOT

Time:04-21

I built a small Golang application and I want to run it on a Docker container.

I wrote the following Dockerfile:

# syntax=docker/dockerfile:1

FROM golang:1.16-alpine

WORKDIR /app

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

COPY ./* .
RUN go env -w GO111MODULE=on

RUN go build -o /docker-gs-ping

EXPOSE 8080

CMD [ "/docker-gs-ping" ] 

However, when I run the command:

docker build --tag docker-gs-ping .

I get the errors:

#16 0.560 found packages controllers (controller.go) and repositories (csv_file_repository.go) in /app #16 0.560 main.go:4:2: package MyExercise/controllers is not in GOROOT (/usr/local/go/src/MyExercise/controllers)

I want to mention that the package controllers exists in my working directory and all files associated with this directory are placed in MyExercise/controllers folder.

Do you know how to resolve this error?

Edit: This is the directory tree:

.
├── Dockerfile
├── REDAME
├── controllers
│   └── controller.go
├── go.mod
├── go.sum
├── logging
│   └── logger.go
├── main.go
├── models
│   └── location.go
├── output.log
├── repositories
│   ├── csv_file_repository.go
│   ├── csv_file_repository_builder.go
│   ├── csv_file_repository_builder_test.go
│   ├── csv_file_repository_test.go
│   ├── repository_builder_interface.go
│   ├── repository_interface.go
│   └── resources
│       └── ip_address_list.txt
└── services
    ├── ip_location_service.go
    ├── ip_location_service_test.go
    ├── rate_limiter_service.go
    ├── rate_limiter_service_interface.go
    ├── rate_limiter_service_test.go
    └── time_service.go

import section in main.go:

import (
    "MyExercise/controllers"
    "MyExercise/logging"
    "MyExercise/repositories"
    "MyExercise/services"
    "errors"
    "github.com/gin-gonic/gin"
    "os"
    "strconv"
    "sync"
)

CodePudding user response:

Do go mod vendor in your app directory. Documentaion.

For build the container docker build -t app:v1 .

Dockerfile

FROM golang:1.16-alpine

WORKDIR /app/

ADD . .

RUN go build -o /app/main

EXPOSE 5055

CMD [ "/app/main" ]

CodePudding user response:

There is actually an issue with your Dockerfile.

COPY ./* .

does not actually do what you think. It will copy all files recursively in a flat structure to the /app directory.

Modify your Dockerfile to something like:

# syntax=docker/dockerfile:1

FROM golang:1.16-alpine

WORKDIR /app

ADD . /app

RUN go mod download

RUN go env -w GO111MODULE=on

RUN go build -o /docker-gs-ping

EXPOSE 8080

CMD [ "/docker-gs-ping" ] 

Basically, remove all of the COPY directives and replace with a single ADD directive

  • Related