dongsutao8921 2017-05-19 04:50
浏览 187
已采纳

开发可在Docker容器中运行的Golang应用程序的最佳实践/方法

Basically what the title says... Is there a best practice or an efficient way to develop a Golang app that will be Dockerized? I know you can mount volumes to point to your source code, and it works great for languages like PHP where you don't need to compile your code. But for Go, it seems like it would be a pain to develop alongside Docker since you pretty much only have two options I guess.

First would be to have a Dockerfile that is just onbuild so it starts the go app when a container is run, thus having to build a new image on every change (whether it be small or not). Or, you do mount your source code dir to the container dir, then attach to the container itself and do the manual go build/run yourself as if you would normally.

Those two ways are really the only way that I see it happening unless you just don't develop your Go app in a docker container. Just develop it as normal, then use the scratch image method where you pre build the Go into a binary then copy that into your container when you are ready to run it. I assume that is probably the way to go, but I wanted to ask more professional people on the subject and maybe get some feedback on the topic.

  • 写回答

3条回答 默认 最新

  • douwo1517 2017-05-19 07:45
    关注

    Not sure it's the best pratice but here is my way.

    1. Makefile is MANDATORY
    2. Use my local machine and my go tools for small iterations
    3. Use a dedicated build container based on golang:{1.X,latest}, mount code directory to build a release, mainly to ensure that my code will build correctly on the CI. (Tips, here is my standard go build command for release build : CGO_ENABLED=0 GOGC=off go build -ldflags -s -w)
    4. Test code
    5. Then use a FROM scratch to build a release container (copy the bin + entrypoint)
    6. Push you image to your registry

    Steps 3 to 6 are tasks for the CI.

    Important note : this is changing due to the new multistage builds feature : https://docs.docker.com/engine/userguide/eng-image/multistage-build/, no more build vs release containers.

    Build container and release container will be merged in one multistage build so one Dockerfile with (not sure about the correct syntax but, you will get the idea) :

    FROM golang:latest as build
    WORKDIR /go/src/myrepos/myproject
    RUN go build -o mybin
    
    FROM scratch
    COPY --from=build /go/src/myrepos/myproject/mybin /usr/local/bin/mybin
    ENTRYPOINT [ "/usr/local/bin/mybin" ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办