在docker build期间不能“获得”依赖关系

时间:2018-01-03 15:21:59

标签: docker go

我对Docker都很新,所以这可能是显而易见的事情,但我的谷歌搜索却找不到任何东西。

我正在尝试使用docker构建一个简单的go程序,但是我对依赖项造成了麻烦。

go file:

package main

import (
    "fmt"
    "log"
    "html"
    "net/http"

    "github.com/gorilla/mux"
)

func hello(writer http.ResponseWriter, r *http.Request) {
    path := mux.Vars(r)["rest"]
    fmt.Fprintf(writer, "Hello, %q", html.EscapeString(path))
}

func main() {
    router := mux.NewRouter().StrictSlash(true)

    router.HandleFunc("/{rest:.*}", hello)

    log.Println("Listening...")
    log.Fatal(http.ListenAndServe(":8080", router))
}

Docker文件:

FROM golang:latest
RUN mkdir /app
ADD ./HelloWorld.go /app/
WORKDIR /app
RUN go get ./*.go
RUN go build -o main .
CMD ["/app/main"]

错误:

Sending build context to Docker daemon  6.482MB
Step 1/7 : FROM golang:latest
 ---> 138bd936fa29
...
Step 5/7 : RUN go get ./*.go
 ---> Running in 1e29844961a2
HelloWorld.go:9:5: cannot find package "github.com/gorilla/mux" in any of:
        /usr/local/go/src/github.com/gorilla/mux (from $GOROOT)
        /go/src/github.com/gorilla/mux (from $GOPATH)
The command '/bin/sh -c go get ./*.go' returned a non-zero code: 1

2 个答案:

答案 0 :(得分:0)

您可以使用我的Dockerfile作为基础。第一阶段产生工作形象。这对许多情况来说已经足够了。 https://github.com/lisitsky/go-site-search-string/blob/light-docker/Dockerfile

如果你想将图像尺寸缩小到约800MB到约10-20MB,也可以使用第二阶段。

答案 1 :(得分:0)

只需在路径中的任何地方使用$GOPATH即可构建图像,例如$GOPATH/src/app代替/app

完整的多阶段构建示例:

FROM golang:alpine as builder

RUN apk add --update git

RUN mkdir -p $GOPATH/src/build

ADD . $GOPATH/src/build/

WORKDIR $GOPATH/src/build

RUN go get ./...

RUN go build -o main .

FROM alpine

RUN adduser -S -D -H -h /app appuser

USER appuser

COPY --from=builder /go/src/build/main /app/

WORKDIR /app

CMD ["./main"]