如何为Docker Alpine映像构建静态Go二进制文件? [英] How do I build a static Go binary for the Docker Alpine image?

查看:118
本文介绍了如何为Docker Alpine映像构建静态Go二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个Go 1.9.2二进制文件并在Docker Alpine映像上运行它。我编写的Go代码不会调用任何C代码。它还使用 net 软件包。不幸的是,它并没有听起来那么简单,因为Go似乎并非一直都在构建静态二进制文件。当我尝试执行二进制文件时,我经常会收到有关为什么二进制文件未执行的隐秘消息。互联网上有很多关于此的信息,但大多数最终导致人们使用试用版错误来使二进制文件正常工作。

I want to build a Go 1.9.2 binary and run it on the Docker Alpine image. The Go code I wrote doesn't call any C code. It also uses the net package. Unfortunately it hasn't been as simple as it sounds as Go doesn't seem to quite build static binaries all the time. When I try to execute the binary I often get cryptic messages for why the binary didn't execute. There's quite a bit of information on the internet about this but most of it ends up with people using trial an error to make their binaries work.

到目前为止,我已经找到了以下作品,但是我不知道为什么,是最佳选择还是可以简化。

So far I have found the following works, however I don't know why, if it is optimal or if it could be simplified.

env GOOS=linux GARCH=amd64 go install -v -a -tags netgo -installsuffix netgo -ldflags "-linkmode external -extldflags -static"

构建可以在Alpine 3.7 docker映像上运行的Go二进制文件的规范方法(如果存在)是什么?我很高兴使用 apk 将软件包安装到Alpine映像中,如果这样做会使事情更高效/更容易。 (相信我仍然需要安装 ca证书。)

What is the canonical way (if it exists) to build a Go binary that will run on the Alpine 3.7 docker image? I am happy to use apk to install packages to the Alpine image if that would make things more efficient/easier. (Believe I need to install ca-certificates anyway.)

推荐答案

是的,您经常需要添加证书之类的额外资源文件,尤其是在使用像alpine这样的最小发行版时,但是您通常可以在这样小的发行版上运行go应用程序这一事实也被视为一种优势。

Yes, you often need to add extra resource files like certificates especially when using a minimal distribution like alpine but the fact that you can run go applications on such small distributions is often also seen as an advantage.

要添加证书,这是一个很好的说明,概述了如何在临时容器上进行操作:

To add the certificates this is a really good explanation outlining how to do it on a scratch container:

https://blog.codeship.com/building-minimal-docker-containers-for-go- Applications /

如果您更喜欢高山,那么可以安装此软件包以获取它们:

If you would rather stick with alpine then you can install this package to get them:

https://pkgs.alpinelinux.org/package /v3.7/main/x86/ca-certificates

这篇关于如何为Docker Alpine映像构建静态Go二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆