如何使用 docker composer 更改 Dockerfile 的上下文?



我正在开发一个CMake项目,该项目使用Docker在Linux上进行构建。它是 2 个库和一个可执行文件。其中一个库仅以源格式提供,我必须自己提供 CMakeLists.txt 文件。

我无法将该目录移动或复制到我的项目文件夹树中,该树的根目录是我的 Dockerfile,因此我需要找到一种方法,在每次构建项目时可靠地将该目录添加到我的容器中。谷歌返回的解决方案是使用 docker composer 来做到这一点,但我无法让它工作。

这是我的docker-composer.yml:

version: '3.8'
services:
dlstreamer:
build:
context: ../
dockerfile: ./PrivacyContainer/Dockerfile

context所示,我想要的源位于与我的项目目录同一级别的目录中。

然而,当我使用 Visual Studio 代码在容器中打开我的文件夹时,该文件夹永远不会被复制。我应该寻找什么?

构建上下文中的文件夹不会默认位于最终映像中,您应该在Dockerfile中显式指定COPY

假设下一个文件夹结构来模拟你的方案:

$ tree trial
trial
├── OneLibrary
│   └── main.c
└── PrivacyContainer
├── CMakeLists.txt
├── docker-compose.yaml
└── Dockerfile

所以,我认为你的目标是在最终图像中看到main.cCMakeLists.txt,然后你可以做下一步:

选项 1:仅使用 Dockerfile:

Dockerfile:

FROM debian
COPY OneLibrary /tmp
COPY PrivacyContainer/CMakeLists.txt /tmp
RUN ls /tmp

PrivacyContainer的目录中执行下一个命令:

pie@pie:~/trial/PrivacyContainer$ docker build -t abc:1 -f Dockerfile .. --no-cache
Sending build context to Docker daemon   5.12kB
Step 1/4 : FROM debian
---> 5890f8ba95f6
Step 2/4 : COPY OneLibrary /tmp
---> 9200efffeba0
Step 3/4 : COPY PrivacyContainer/CMakeLists.txt /tmp
---> 33874c7e6be1
Step 4/4 : RUN ls /tmp
---> Running in ff9dde40251c
CMakeLists.txt
main.c
Removing intermediate container ff9dde40251c
---> d7640c75b197
Successfully built d7640c75b197
Successfully tagged abc:1

您现在可以在图像中看到main.cCMakeLists.txt

选项 2:使用 compose + Above Dockerfile:

docker-compose.yaml

version: '3'
services:
dlstreamer:
build:
context: ../
dockerfile: ./PrivacyContainer/Dockerfile

从隐私容器的目录中执行下一个命令:

pie@pie:~/trial/PrivacyContainer$ docker-compose build --no-cache
Building dlstreamer
Step 1/4 : FROM debian
---> 5890f8ba95f6
Step 2/4 : COPY OneLibrary /tmp
---> f100c69d7e87
Step 3/4 : COPY PrivacyContainer/CMakeLists.txt /tmp
---> fffafba2ceaf
Step 4/4 : RUN ls /tmp
---> Running in 139cfb9be5f9
CMakeLists.txt
main.c
Removing intermediate container 139cfb9be5f9
---> 0aba679e4e33
Successfully built 0aba679e4e33
Successfully tagged privacycontainer_dlstreamer:latest

您现在还可以在图像中看到main.cCMakeLists.txt

docker 构建文档页面指示以下内容:

出于安全原因,上下文仅限于当前目录(及其子目录),并确保在远程 Docker 主机上可重复构建。

这可以解释为什么将../设置为上下文不起作用。

所以我认为您应该从包含源代码的父目录中启动 docker 构建命令(../),使用 -f 指定 dockerFile 的路径,并将上下文 Path 指示为.如下所示:

docker build -f PrivacyContainer/Dockerfile .

这样,您的上下文包括您想要的目录,您将可以访问 COPY 等所需的文件。

最好是为库创建存储库,并在容器中git clone获取它。这样,您就可以控制构建中输入的内容

此外,如果您的项目已经在 git 存储库中,您可以使用git submodule将其包含在项目中要构建它的位置,并在构建期间从存储库中获取整个项目并初始化子模块(这将获取库)

最新更新