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 .
    # ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效