[英]Golang cannot find package in Docker image
So, I am trying to dockerize a golang application with different directories containing supplementary code for my main file. 因此,我正在尝试对具有不同目录的golang应用程序进行docker化,该目录包含主文件的补充代码。 I am using gorilla/mux .
我正在使用大猩猩/木浆 。 The directory structure looks like this.
目录结构如下所示。
$GOPATH/src/github.com/user/server
|--- Dockerfile
|--- main.go
|--- routes/
handlers.go
|--- public/
index.gohtml
It works on my host machine with no problem. 它可以在我的主机上正常工作。 The problem is that when I try to deploy the docker image it does not run and exits shortly after creation.
问题是,当我尝试部署Docker映像时,它无法运行并在创建后不久退出。 I have tried changing the WORKDIR command in my dockerfile to /go/src and dump all my files there, but still no luck.
我尝试将dockerfile中的WORKDIR命令更改为/ go / src并将所有文件转储到那里,但是仍然没有运气。 I have also tried the official documentation on docker hub .
我还尝试了docker hub上的官方文档。 Doesn't work either.
也不起作用。
My Dockerfile. 我的Dockerfile
FROM golang:latest
WORKDIR /go/src/github.com/user/server
COPY . .
RUN go get -d github.com/gorilla/mux
EXPOSE 8000
CMD ["go","run","main.go"]
My golang main.go 我的golang main.go
package main
import (
"github.com/gorilla/mux"
"github.com/user/server/routes"
"log"
"net/http"
"time"
)
func main(){
//...
}
I get this error message when I check the logs of my docker image. 当我检查Docker映像的日志时收到此错误消息。
Error Message 错误信息
main.go:5:2: cannot find package "github.com/user/server/routes" in any of:
/usr/local/go/src/github.com/user/server/routes (from $GOROOT)
/go/src/github.com/user/server/routes (from $GOPATH)
Try the following Docker
file: 尝试以下
Docker
文件:
# GO Repo base repo
FROM golang:1.12.0-alpine3.9 as builder
RUN apk add git
# Add Maintainer Info
LABEL maintainer="<>"
RUN mkdir /app
ADD . /app
WORKDIR /app
COPY go.mod go.sum ./
# Download all the dependencies
RUN go mod download
COPY . .
# Build the Go app
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
# GO Repo base repo
FROM alpine:latest
RUN apk --no-cache add ca-certificates curl
RUN mkdir /app
WORKDIR /app/
# Copy the Pre-built binary file from the previous stage
COPY --from=builder /app/main .
# Expose port 8000
EXPOSE 8000
# Run Executable
CMD ["./main"]
Here, we are creating an intermediate docker builder
container, copying the code into it, build the code inside the builder
container and then copy the binary
image to the actual docker. 在这里,我们正在创建一个中间
docker builder
容器,将代码复制到其中,在builder
容器中构建代码,然后将binary
映像复制到实际的docker。
This will help in both having all the dependencies in the final container and also, the size of the final image will be very small 这将有助于使所有依赖项都包含在最终容器中,并且最终映像的大小将非常小
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.