Search code examples
dockergodocker-build

How to build docker image with local package inside folder with main.go?


I'm trying docker build -t test_1 . , but have this err:

package docker_test/mult: unrecognized import path "docker_test/mult" (import path does not begin with hostname)

The command '/bin/sh -c go get -d -v ./...' returned a non-zero code: 1

My dockerfile (path /gowork/src/Dockerfile):

FROM golang:1.9.1
COPY ./docker_test/mult /go/src/app

WORKDIR go/src/app
COPY ./docker_test/main.go .

RUN go get -d -v ./...
RUN go install -v ./...

CMD ["app"]
ENTRYPOINT ["app", "-f=7", "-s=9"]

main.go (path: gowork/src/docker_test/main.go)

package main

import (
    "docker_test/mult"
    "fmt"
)

func main() {
    fmt.Println("From different pkg")
    mult.Multiple()
}

mult.go (path: gowork/src/docker_test/mult/mult.go)

package mult

import (
    "flag"
    "fmt"
)

func Multiple() {

    first := flag.Int("f", 0, "placeholder")
    second := flag.Int("s", 0, "placeholder")

    flag.Parse()

    out := (*first) * (*second)
    fmt.Println(out)

}

Solution

  • go get trying to find the package docker_test/mult into /go path. But, you have copied into /go/src/app. That's why go get can't find the package locally and assumes the package is from remote repository, eg, github, and throws error import path does not begin with hostname. So copy the docker_test/mult inside /go path.

    Another concern is, when you use WORKDIR go/src/app, it creates go/src/app inside /go path, So finally the path becomes /go/go/src/app. So use absolute path ie, WORKDIR /go/src/app.

    Try this dockerfile:

    FROM golang:1.9.1
    COPY ./docker_test/mult /go/src/docker_test/mult
    
    WORKDIR /go/src/app
    COPY ./docker_test/main.go .
    
    RUN go get -d -v ./...
    RUN go install -v ./...
    
    CMD ["app"]
    ENTRYPOINT ["app", "-f=7", "-s=9"]