如何解决使用Docker的标准Go项目布局会导致构建上下文问题
我正在遵循似乎有冲突的两个指南
Go的Standard Go Project Layout推荐一个/build
目录,其使用方式为described,
包装和持续集成。
放入您的云(AMI),容器(Docker),操作系统(deb,rpm,pkg)软件包 / build / package目录中的配置和脚本。
在Google Cloud Endpoints Sample for Go using gRPC之后,我有一个Dockerfile,该文件复制应用程序源代码并使用go get
安装所有依赖项。
# /build/Dockerfile
FROM golang:alpine
# Alpine Linux package management
RUN apk update
RUN apk add git
COPY ../ /go/src/github.com/username/repository
# Downloads the packages named by the import paths,along with their
# dependencies. It then installs the named packages,like 'go install'.
# ****Don't do this in production! Use vendoring instead.****
RUN go get -v github.com/username/repository/foo-module
# Compiles and installs the packages named by the import paths.
RUN go install github.com/username/repository/foo-module
ENTRYPOINT ["/go/bin/foo-module"]
在Standard Go Project Layout之后,我将上述Dockerfile放置在/build
中。
由于Dockerfile现在位于/build
目录中,因此我修改了COPY
命令以复制 parent 目录以查找应用程序源代码(COPY ../ /go/src/github.com/username/repository
)。
Docker build
命令不是不直接运行,而是以Google Cloud Build
cloud-build-local --config=build/cloudbuild.yaml .
cloudbuild.yaml
文件非常简单,并且刚刚启动了Docker构建。由于Cloud Build命令是从项目根目录而不是从--file
开始的,因此build/Dockerfile
标志指向/build
# /build/cloudbuild.yaml
steps:
- id: Build
name: "gcr.io/cloud-builders/docker"
dir: ${_SOURCE}
args:
[
"build","--file build/Dockerfile",".",]
按预期,这将失败
COPY failed: Forbidden path outside the build context: ../ ()
How to include files outside of Docker's build context?建议使用--file
标志,但是,这假定构建是从根上下文开始的。使用Google的Cloud Build时,该构建是从cloudbuild.yaml
开始的,该/build
也位于cloudbuild.yaml
中。
我可以将Docker文件放置在go模块的根目录中,但我想遵循最佳实践,并将Dockerfile
和/build
保留在<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
中。
遵循Standard Go Project Layout时实现此目标的正确方法是什么?
解决方法
这是一个相当长的问题,所以让我们关注遇到的问题:
COPY ../ /go/src/github.com/username/repository
导致
COPY failed: Forbidden path outside the build context: ../ ()
您不要在上下文之外包括文件,docker不允许这样做。相反,您可以更改上下文以包括构建映像所需的文件,并在COPY / ADD命令中创建相对于该上下文的路径。确保重新阅读,这些路径不是相对于Dockerfile的位置。
因此,使用docker build
,如果您拥有build/Dockerfile
,则可以使用以下命令从父目录进行构建:
docker build -f build/Dockerfile .
该尾随点是构建上下文的路径,该上下文被发送到docker引擎以执行构建。它不会直接在客户端上访问文件,这就是为什么您不能包含来自上下文外部的文件的原因(再加上您不希望恶意Dockerfile从构建服务器中提取数据)。
然后在Dockerfile内定义相对于该上下文的路径:
COPY . /go/src/github.com/username/repository
如果由于某种原因由于工具原因您无法从该父目录进行构建,则使上下文成为具有相对路径的父文件夹:
docker build -f Dockerfile ..
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。