当将Go服务器作为Docker容器运行时,出现Permission denied错误

3
我想将我的Go服务器部署到Google Cloud Run上。我从这个指南中复制了Dockerfile。请帮我将其翻译成中文。
FROM golang:1.13 as builder

WORKDIR /app

COPY go.* ./
RUN go mod download

COPY . ./

RUN CGO_ENABLED=0 GOOS=linux go build -v -o server
RUN chmod a+x server

FROM alpine:3
RUN apk add --no-cache ca-certificates

COPY --from=builder /app/server /server

CMD ["/server"]

在将它部署到Cloud Run之前,我想通过使用docker build -t server .命令构建映像并使用docker run server命令运行容器来在本地测试它。
但是,它会出现以下错误:
docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"/server\": permission denied": unknown.

感谢您的帮助。

我正在使用最新的Mac电脑。在构建Docker镜像时,这会有什么影响吗? - undefined
1
启动容器时遇到了问题。构建镜像应该是相同的。似乎权限出了问题。尝试将RUN chmod a+x server这行代码移到复制文件之后(但别忘了/)。 - undefined
你还可以执行 docker container run --rm -it server /bin/sh 然后执行 ls -l server 来查看该文件的权限。 - undefined
我在Mac上完成了这个任务,并且它正常工作。$ go version go version go1.12.5 darwin/amd64$ docker -v Docker version 19.03.4, build 9013bf5 - undefined
一些 Go 二进制文件在进入第二个 "alpine" 阶段时出现问题。也许可以尝试使用 Cloud Run Pub/Sub 教程中的这个 Dockerfile,在两个阶段都使用 ubuntu?https://github.com/GoogleCloudPlatform/golang-samples/blob/master/run/pubsub/Dockerfile - undefined
显示剩余6条评论
3个回答

1

我在使用Firebase教程中提供的GoLang on Cloud Run的Dockerfile后,也遇到了权限被拒绝的错误。

显然,这可能是因为Alpine Linux太过精简,缺少容器构建或运行所需的关键软件包。

对于我的情况,缺少了git。我在ca-certificates之后的RUN行添加了git以确保它被安装。在此更改后,我的Cloud Run实例正常工作。

有关详细信息,请参见Docker Library GoLang Github上的此评论

# Use the official Golang image to create a build artifact.
# This is based on Debian and sets the GOPATH to /go.
FROM golang:1.19 as builder

# Create and change to the app directory.
WORKDIR /app

# Retrieve application dependencies using go modules.
# Allows container builds to reuse downloaded dependencies.
COPY go.* ./
RUN go mod download

# Copy local code to the container image.
COPY . ./

# Build the binary.
# -mod=readonly ensures immutable go.mod and go.sum in container builds.
RUN CGO_ENABLED=0 GOOS=linux go build -mod=readonly -v -o server

# Use the official Alpine image for a lean production container.
# https://hub.docker.com/_/alpine
# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
FROM alpine:3
RUN apk add --no-cache ca-certificates git

# Copy the binary to the production image from the builder stage.
COPY --from=builder /app/server /server

# Run the web service on container startup.
CMD ["/server"]

1

潜在问题 1

如果将alpine更改为debian可解决问题,则说明这是一个交叉编译问题。

golang镜像基于debian,并使用glibc,alpine镜像使用musl libc。有时它们之间存在不兼容性,并以最糟糕的错误消息形式暴露出来。

因此,我怀疑这不是Cloud Run的问题,而是之前的问题。为了验证,您还可以在本地运行容器,就像它正在运行Cloud Run一样https://cloud.google.com/run/docs/testing/local


潜在问题2

我曾经遇到过类似的情况,结果发现我正在构建的包不是 package main。因此,我生成的是目标文件 (.o),而不是可执行二进制文件,无论我如何尝试 "chmod +x",都无法启动。

请验证您正在构建的Go包路径实际上是一个 package main


1

尝试在最终构建中添加RUN chmod a+x

COPY --from=builder /app/server /server
RUN chmod a+x /server
CMD ["/server"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接