【问题标题】:Dockerfile for Go project of two runnables with shared packagesDockerfile for Go 项目的两个可运行的共享包
【发布时间】:2021-07-21 16:27:50
【问题描述】:

我有一个项目,其中包括一个带有多个共享文件的客户端服务器。我正在尝试为客户端和服务器创建 docker 映像,并努力编写 dockerfile。 我查看了在线资源,其中主要包括非常简单的项目或太大而对此事没有帮助的项目。

我的项目结构遵循标准项目布局:

Project
    -api
        -api.go
    -cmd
        -client
            -client.go
        -server
            -server.go
    -configs
        -configuration.yaml
    -internal
        -client_int
            -client_logic.go
        -server_int
            -server_logic.go
        -shared_int
            -shared_logic.go
    -Dockerfile
    -go.mod

有人可以就项目结构提供建议/评论或有类似的 dockerfile 作为示例吗?

谢谢。

*我查看了许多来自 google 或简单 github 关键字的教程。

【问题讨论】:

  • 不清楚你的问题是什么,你还没有分享 dockerfile 的内容。您是否面临 docker 错误?或者您对使用生成的容器有什么不便?无论如何,看起来您可以使用多阶段功能为服务器创建一个目标,为客户端创建另一个目标。
  • 为什么不是两张图片,一张用于客户端,一张用于服务器?只需将Dockerfiles 保存在单独的目录中,然后将整个项目复制到两者中即可。
  • @super 这就是我想要做的。

标签: docker go dockerfile


【解决方案1】:

有了这个(非常正常的)项目布局,有两个重要的细节:

  1. 构建映像时,上下文目录(Compose build: { context: } 或 docker build 目录参数)必须是顶级 Project 目录。
  2. 无论 Dockerfile 物理位于何处,任何COPY 指令的左侧都必须相对于Project 目录(上一点的上下文目录)。

关于如何从中构建 Docker 映像有一些选择。您可以使用客户端和服务器构建一个镜像,或者为每个镜像构建一个单独的镜像,您可以将 Dockerfile(s) 放在顶层目录或相关的cmd 子目录中;对于这样的项目,我认为没有标准的方法。

要选择一种方法(绝不是“最好的”方法,而是一种可行的方法),假设我们为每个部分创建单独的图像;但是,由于共享了这么多代码,因此您基本上需要将整个源代码树复制进去以进行映像构建。

# cmd/server/Dockerfile
# Build-time stage:
FROM golang:alpine AS build
WORKDIR /build

# First install library dependencies
# (These are expensive to download and change rarely;
# doing this once up front saves time on rebuilds)
COPY go.mod go.sum .
RUN go mod install

# Copy the whole application tree in
COPY . .

# Build the specific component we want to run
RUN go build -o server ./cmd/server

# Final runtime image:
FROM alpine
# Get the built binary
COPY --from=build /build/server /usr/bin
# And set it as the main container command
CMD ["server"]

也许你正在通过 Docker Compose 运行它:

version: '3.8'
services:
  server:
    build:
      context: .
      dockerfile: cmd/server/Dockerfile
    ports:
      - 8000:8000
  client:
    build:
      context: .
      dockerfile: cmd/client/Dockerfile
    environment:
      SERVER_URL: 'http://server:8000'

请注意,两个映像都将项目根目录指定为构建 context:,但随后为每个映像指定不同的 dockerfile:。

【讨论】:

  • 在询问之前我已经研究了很长时间,非常感谢您,稍作修改,这可能就是我想要的。
猜你喜欢
  • 2012-03-02
  • 1970-01-01
  • 2014-04-06
  • 2014-09-07
  • 2011-02-19
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
相关资源
最近更新 更多