Docker没有看到main.go

问题描述

我对Docker有一些问题。我的dockerfile看不到main.go。
我有那个结构项目

docker-compose.yml  
go.mod
frontend-microservice  
  -cmd  
    -app
      -main.go
  -internal
    -some folders

当我尝试启动docker-compose时,会出现该错误

ERROR: Service 'frontend-microservice' Failed to build: The command '/bin/sh -c CGO_ENABLED=0 GOOS=linux go build -a -installsuffix nocgo -o /frontend-microservice .' returned a non-zero code: 1

通过dockerfile给出与go.mod相关的错误

我的docker-compose

version: "3"
services:
    frontend-microservice:
        build:    
            context: ./frontend-microservice/
            dockerfile: Dockerfile
        ports:
            - 80:80

那个我的dockerfile

# golang image where workspace (GOPATH) configured at /go.
FROM golang:alpine as builder

ADD . /go/src/frontend-microservice
workdir /go/src/frontend-microservice
RUN go mod download

copY . ./

RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix nocgo -o /frontend-microservice .

FROM alpine:latest
RUN apk --no-cache add ca-certificates
 
copY --from=builder /frontend-microservice ./frontend-microservice
RUN mkdir ./configs 
copY ./configs/config.json ./configs
 
EXPOSE 8080
 
ENTRYPOINT ["./frontend-microservice"]

在此先感谢您的帮助

解决方法

定义了main()函数的文件位于cmd/app中。 不用将当前工作目录更改为cmd/app,而是将cmd/app/main.go附加到go build命令中。

您的Dockerfile如下所示:

# golang image where workspace (GOPATH) configured at /go.
FROM golang:alpine as builder

ADD . /go/src/frontend-microservice
WORKDIR /go/src/frontend-microservice
RUN go mod download

COPY . ./

RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix nocgo -o /frontend-microservice cmd/app/main.go

FROM alpine:latest
RUN apk --no-cache add ca-certificates
 
COPY --from=builder /frontend-microservice ./frontend-microservice
RUN mkdir ./configs 
COPY ./configs/config.json ./configs
 
EXPOSE 8080
 
ENTRYPOINT ["./frontend-microservice"]