gpt4 book ai didi

Go 编译的二进制文件不会在 Ubuntu 主机上的 alpine docker 容器中运行

转载 作者:IT老高 更新时间:2023-10-28 12:58:43 27 4
gpt4 key购买 nike

给定一个二进制文件,使用 Go 编译,使用 GOOS=linuxGOARCH=amd64,部署到基于 docker 容器alpine:3.3,如果docker引擎主机是Ubuntu(15.10),二进制将不会运行:

sh: /bin/artisan: not found

如果 docker 引擎主机是 busybox(这是 alpine 的基础) 部署在 Mac OS X 上的 VirtualBox VM 中。

如果容器基于 Ubuntu 镜像之一,同样的二进制文件也可以正常运行。

知道这个二进制文件缺少什么吗?

这是我为重现所做的(未显示在 OS X 上的 VirtualBox/busybox 中成功运行):

构建(使用标志显式构建,即使拱门匹配):

➜  artisan git:(master) ✗ GOOS=linux GOARCH=amd64 go build

检查它是否可以在主机上运行:

➜  artisan git:(master) ✗ ./artisan 
10:14:04.925 [ERROR] artisan: need a command, one of server, provision or build

复制到 docker 目录,构建,运行:

➜  artisan git:(master) ✗ cp artisan docker/build/bin/        
➜ artisan git:(master) ✗ cd docker
➜ docker git:(master) ✗ cat Dockerfile
FROM docker:1.10
COPY build/ /
➜ docker git:(master) ✗ docker build -t artisan .
Sending build context to Docker daemon 10.15 MB
Step 1 : FROM docker:1.10
...
➜ docker git:(master) ✗ docker run -it artisan sh
/ # /bin/artisan
sh: /bin/artisan: not found

现在将图像库更改为 phusion/baseimage:

➜  docker git:(master) ✗ cat Dockerfile 
#FROM docker:1.10
FROM phusion/baseimage
COPY build/ /
➜ docker git:(master) ✗ docker build -t artisan .
Sending build context to Docker daemon 10.15 MB
Step 1 : FROM phusion/baseimage
...
➜ docker git:(master) ✗ docker run -it artisan sh
# /bin/artisan
08:16:39.424 [ERROR] artisan: need a command, one of server, provision or build

最佳答案

默认情况下,如果使用 net 包,构建可能会生成带有一些动态链接的二进制文件,例如到 libc。您可以通过查看 ldd output.bin

的结果来检查动态链接和静态链接

我遇到过两种解决方案:

  • 通过 CGO_ENABLED=0
  • 禁用 CGO
  • 强制使用net依赖的Go实现,netgo通过go build -tags netgo -a -v,这是针对某些平台实现的

来自 https://golang.org/doc/go1.2 :

The net package requires cgo by default because the host operating system must in general mediate network call setup. On some systems, though, it is possible to use the network without cgo, and useful to do so, for instance to avoid dynamic linking. The new build tag netgo (off by default) allows the construction of a net package in pure Go on those systems where it is possible.

以上假设唯一的 CGO 依赖是标准库的 net 包。

关于Go 编译的二进制文件不会在 Ubuntu 主机上的 alpine docker 容器中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36279253/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com