尝试运行 docker-compose up -d 时出现错误

我刚刚开始使用 Golang 并尝试使用 docker-compose 构建 go gin。这是我的 Dockerfile


FROM golang:1.18


WORKDIR /docker-go


# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change

# COPY all file go ./


COPY ./app/main.go ./

COPY . /docker-go

# To initialize a project with go module, create go.mod


RUN go mod init shipping-go


# Add missing and/or remove unused modules

RUN go mod tidy


# This will bring all the vendors to your projects /vendor directory so that 

# you don't need to get the modules again if working from another machine on this project.

RUN go mod vendor


RUN go mod download && go mod verify


COPY . .

RUN go build -v -o /docker-go/app .


RUN chmod +x /docker-go

USER root

和我的 docker-compose


version: "3.7"

services:

  go-web:

    build:     

      context: ./

      dockerfile: Dockerfile

    restart: 'no'

    working_dir: /docker-go

    ports:

      - "8080:8080"

    entrypoint: ["./start.sh"]

    volumes:

      - ./:/docker-go

当我用命令检查日志容器时出现错误


docker logs learn-docker-go_go-web_1


/docker-go

go: cannot find main module, but found .git/config in /docker-go

    to create a module there, run:

    go mod init

/docker-go

它似乎找不到模块文件,但我已经安装在 Dockerfile 中。对于详细信息,我将代码推送到我的存储库中 https://github.com/duyanh1904/learn-docker-go


蛊毒传说
浏览 290回答 1
1回答

不负相思意

您有多个问题,Dockerfile我docker-compose.yml无法复制您所看到的问题(但您的设置对我也不起作用)。我看到的一些问题是:COPY . /docker-go会将当前文件夹(包括子文件夹)复制到图像中/docker-go/。这将产生一个文件夹/docker-go/app。该文件夹的存在意味着go build -v -o /docker-go/app .将可执行文件存储为/docker-go/app/shipping-go(您正在尝试执行文件夹)。您的意图是让可执行文件位于其中,/docker-go但您随后使用挂载 ( ./:/docker-go) 隐藏了该文件夹。根据文档“如果您绑定挂载到容器上的非空目录中,该目录的现有内容将被绑定挂载遮盖。”。您的start.sh(问题中未显示)没有启动可执行文件(请参阅文档)。在main.go(问题中也未显示)替换router.Run("127.0.0.1:8080")为router.Run(":8080"). 监听127.0.0.1意味着只接受本地连接;在容器内,这意味着仅来自容器本身的连接。这是一个可以让你继续前进的工作设置(这可能不是最佳的,但应该提供一个起点,使你能够进一步试验)。请注意,您需要先进行上述更改main.go。文件FROM golang:1.18WORKDIR /docker-go# Note: A better solution would be to copy an existing go.mod into the imageRUN go mod init shipping-goCOPY ./app/main.go ./# Determine required modules and download themRUN go mod tidyRUN go build -v -o /docker-go/appRUN chmod +x /docker-go/appdocker-compose.ymlversion: "3.7"services:  go-web:    build:           dockerfile: Dockerfile    restart: 'no'    ports:      - "8080:8080"    command: ["./app"]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go