亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 在 Docker 鏡像中找不到包

Golang 在 Docker 鏡像中找不到包

Go
慕碼人2483693 2023-07-17 14:37:02
因此,我嘗試使用包含主文件補充代碼的不同目錄對 golang 應用程序進行 dockerize。我正在使用gorilla/mux。目錄結構如下所示。$GOPATH/src/github.com/user/server  |--- Dockerfile   |--- main.go   |--- routes/          handlers.go   |--- public/          index.gohtml 它在我的主機上運行沒有問題。問題是,當我嘗試部署 docker 映像時,它不會運行并在創建后不久退出。我嘗試將dockerfile 中的WORKDIR命令更改為/go/src并將所有文件轉儲到那里,但仍然沒有成功。我還嘗試了docker hub上的官方文檔。也不行。我的 Dockerfile。FROM golang:latest  WORKDIR /go/src/github.com/user/serverCOPY . .RUN go get -d github.com/gorilla/muxEXPOSE 8000CMD ["go","run","main.go"]我的 golang main.gopackage main import (    "github.com/gorilla/mux"    "github.com/user/server/routes"    "log"    "net/http"    "time")func main(){  //... }當我檢查 docker 映像的日志時,我收到此錯誤消息。錯誤信息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)
查看完整描述

1 回答

?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

嘗試以下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"]

在這里,我們創建一個中間docker builder容器,將代碼復制到其中,在builder容器內構建代碼,然后將binary映像復制到實際的 docker。


這將有助于在最終容器中包含所有依賴項,而且最終圖像的大小將非常小


查看完整回答
反對 回復 2023-07-17
  • 1 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號