登录
首页 >  Golang >  Go问答

权限问题影响 Dockerfile 构建缓存

来源:stackoverflow

时间:2024-03-03 21:33:25 408浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《权限问题影响 Dockerfile 构建缓存》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我正在使用这样的二进制文件构建一个容器:

基本上,容器将运行一个可执行的 go 程序。

from myrepo/ubi8/go-toolset:latest as build

copy --chown=1001:0 . /build

 run cd /build && \
    go env -w go111module=auto && \
    go build

#---------------------------------------------------------------
from myrepo/ubi8/ubi-minimal:latest as runtime

run microdnf update -y --nodocs && microdnf clean all && \
    microdnf install go -y && \
    microdnf install cronie -y && \
    groupadd -g 1000 usercontainer && adduser -u 1000 -g usercontainer usercontainer && chmod 755 /home/usercontainer && \
    microdnf clean all

env xdg_cache_home=/home/usercontainer/.cache

copy executable.go /tmp/executable.go

run chmod 0555 /tmp/executable.go

user usercontainer
workdir /home/usercontainer

但是,当在 jenkins 中运行容器时,我收到此错误:

failed to initialize build cache at /.cache/go-build: mkdir /.cache: permission denied

在 kubernetes 部署中手动运行容器时,我没有遇到任何问题,但 jenkins 抛出此错误,我可以在 crashloopbackoff 中看到 pod,并且容器显示之前的权限问题。

此外,我不确定我是否正确构建了容器。也许我需要在二进制文件中包含可执行的 go 程序,然后创建运行时?

任何明确的例子将不胜感激。


正确答案


go 是一种编译语言,这意味着您实际上不需要 go 工具来运行 go 程序。在 docker 上下文中,典型的设置是使用 multi-stage build 编译应用程序,然后将构建的应用程序复制到运行它的最终映像中。最终的镜像不需要go工具链或源代码,只需要编译后的二进制文件。

我可能会将最后阶段重写为:

FROM myrepo/ubi8/go-toolset:latest AS build
# ... as you have it now ...

FROM myrepo/ubi8/ubi-minimal:latest AS runtime

# Do not install `go` in this sequence
RUN microdnf update -y --nodocs && 
    microdnf install cronie -y && \
    microdnf clean all

# Create a non-root user, but not a home directory;
# specific uid/gid doesn't matter
RUN adduser --system usercontainer

# Get the built binary out of the first container
# and put it somewhere in $PATH
COPY --from=build /build/build /usr/local/bin/myapp

# Switch to a non-root user and explain how to run the container
USER usercontainer
CMD ["myapp"]

此序列不使用 go run 或在最终映像中使用任何 go 命令,这有望解决需要 $home/.cache 目录的问题。 (它还会为您提供更小的容器和更快的启动时间。)

到这里,我们也就讲完了《权限问题影响 Dockerfile 构建缓存》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>