如何使用main.go在文件夹内使用本地包构建docker镜像?

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)

}

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"]

Make sure you set the GOPATH, in your example import uses docker_test/mult, so in order compiler to resolve it place it into $GOPATH/docker_test/mult,

I have tweaked your Dockerfile, so you should be able to buld it

Dockerfile

FROM golang:1.9.1

ENV GOPATH /go

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

WORKDIR /go/src/app

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


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