Golang可执行文件未在多阶段dockerfile中运行

发布于 2025-01-23 07:14:21 字数 933 浏览 3 评论 0原文

我有以下dockerfile:

FROM golang:1.18 as build

WORKDIR /app

COPY . .

RUN CGO_ENABLED=0 go build -o server

# PRODUCTION build
FROM golang:1.18-alpine as prd

COPY --from=build /app/server /app/server

CMD ["/app/server"]

构建成功,当我将图像运行在容器中时,它立即存在。我尝试使用cmd [“ Sleep”,“ 100000”],将SSH运行到容器中,并在内部手动运行可执行文件 - 同样发生 - 立即退出与任何输出。

当我求助于Dockerfile的一个阶段时,它运行得可以:

FROM golang:1.18 as build

WORKDIR /app

COPY . .

RUN CGO_ENABLED=0 go build -o server

CMD ["./server"]

但是我​​想从Alpine构建最终图像,因此它较小。不幸的是,当我尝试在Alpine图像中构建GO应用程序时:

FROM golang:1.18-alpine as build

WORKDIR /app

COPY . .

RUN CGO_ENABLED=0 go build -o server

我会收到以下错误:

cgo: C compiler "gcc" not found: exec: "gcc": executable file not found in $PATH

因此,我求助于多阶段构建。

如果这很重要,我在Mac上。

I have the following Dockerfile:

FROM golang:1.18 as build

WORKDIR /app

COPY . .

RUN CGO_ENABLED=0 go build -o server

# PRODUCTION build
FROM golang:1.18-alpine as prd

COPY --from=build /app/server /app/server

CMD ["/app/server"]

The build is successful and when I run the image in a container, it exists immediately. I tried to run the image with CMD ["sleep", "100000"] , ssh into the container and run the executable manually inside - the same same happens - immediate exit w/o any output.

When I resort to a single stage for the Dockerfile it runs alright:

FROM golang:1.18 as build

WORKDIR /app

COPY . .

RUN CGO_ENABLED=0 go build -o server

CMD ["./server"]

But I want to build the final image from alpine, so it's smaller. Unfortunately, when I try to build the go app within alpine image:

FROM golang:1.18-alpine as build

WORKDIR /app

COPY . .

RUN CGO_ENABLED=0 go build -o server

I get the following error:

cgo: C compiler "gcc" not found: exec: "gcc": executable file not found in $PATH

So, I resorted to a multistage build.

I'm on a Mac, if that's relevant.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十年不长 2025-01-30 07:14:21

问题可能是跨平台编译构建go可执行的。

例如,要为Linux构建可执行文件,您可能需要设置鹅环境变量。

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=on \
 GOOS=linux go build main.go

The issue may be cross platform compilation building a GO executable.

For example, to build an executable for linux, you may require to set the GOOS environment variable.

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=on \
 GOOS=linux go build main.go
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文