dongyuqi3808 2019-07-18 14:34
浏览 55
已采纳

Golang内置了docker和requirements.txt

I am aware of Golang requirements.txt equivalent , but the context of the question is rather different.

I am trying to optimize builds of golang programs inside a docker container. My dockerfile looks something like this:

FROM golang:1.12.5 as builder

WORKDIR $GOPATH/src/test-ldap/

COPY main.go .

RUN go get -d -v ./...
...

while my main.go looks like

package main

import (
  "log"
  "fmt"
  "gopkg.in/ldap.v3"
)

func main() {
...

Of course, every time I make a change in the source code, the docker layer
COPY main.go . is changed, hence the go get command needs to be re-run and cannot be reused from the docker build cache even though the import block is unchanged.

Now of course I could type something like

RUN go get -d -v log fmt gopkg.in/ldap.v3

and place this before the COPY statement, but this violates the so-called single source of truth principle. I would then have to change the same thing in two different places in my codebase if I will ever wish to add extra imports.

How can I store my import requirements in a separate file? What is an idiomatic way to do this in go development?

  • 写回答

1条回答 默认 最新

  • drtwqc3744 2019-07-18 21:29
    关注

    Use Go modules. Then, treat the resulting go.mod file just as you would a requirements.txt:

    FROM golang:1.12.5 as builder
    
    # NOT in $GOPATH (or explicitly set GO111MODULES=on)
    WORKDIR /usr/src/test-ldap/
    
    COPY go.mod .
    RUN go mod download  # alternatively: "go mod vendor" to build a vendor/ dir instead
    
    COPY main.go .
    # ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站