首页 > 解决方案 > Docker 多阶段构建与不同的项目

问题描述

我们目前正在处理两个项目:

1个基于C++的项目

2 基于Nodejs的项目

这两个项目是分开的,这意味着它们具有不同的代码库(git repository)和工作目录。

C++ 项目将生成一个节点绑定文件.node,Nodejs 项目将使用该文件。

我们尝试为 Nodejs 项目构建一个多阶段的 docker 镜像,如下所示:

from ubuntu:18.04 as u
WORKDIR /app
RUN apt-get........  
copy (?) .  #1 copy the c++ source codes
RUN make  

from node:10
WORKDIR /app
copy (?) .  #1 copy the nodejs cource codes
RUN npm install
copy --from=u /app/dist/xx.node ./lib/
node index.js

我将通过docker build -t xx (?) #2.

但是,正如 dockerfile 和命令中所评论的那样,如何设置context目录(参见评论 #2)?因为它会影响 dockerfile 中的路径(参见注释 #1)。

另外,我应该为上述项目放入哪个项目dockerfile

标签: dockerdocker-multi-stage-build

解决方案


您将有两个选项,因为限制因素是 Docker 只允许从与 Dockerfile 相同的目录复制

创建一个新的存储库

您可以创建一个新的存储库并将您的存储库用作子模块或仅用于 Dockerfile(而不是在构建时将两个存储库复制到根文件夹中)。最后,您要实现的是以下结构:

/ (root)
|-- C-plus-plus-Repo
|-- |-- <Files>
|-- Node-Repo
|-- |-- <Files>
|-- Dockerfile

比你可以构建你的项目:

from ubuntu:18.04 as u
WORKDIR /app
RUN apt-get........  
#1 copy the c++ source files
copy ./C-plus-plus-Repo .
RUN make  

from node:10
WORKDIR /app
#1 copy the nodejs cource codes
copy ./Node-Repo .  
RUN npm install
copy --from=u /app/dist/xx.node ./lib/
node index.js   

在根目录执行:

docker build -t xx . 

额外构建暂存容器

Docker 允许从外部容器复制为 stage

因此,您可以在 C++ 存储库根目录中构建 C++ 容器

from ubuntu:18.04 as u
WORKDIR /app
RUN apt-get........  
#1 copy the c++ source files
copy . .  
RUN make  

并标记它:

# Build your C++ Container in root of the c++ repo
docker build . -t c-stage

然后使用标签复制其中的文件(在您的节点回购根目录中):

from node:10
WORKDIR /app
#1 copy the nodejs source files
copy . .  
RUN npm install
# Use the Tag-Name of the already build container "c-stage"
copy --from=c-stage /app/dist/xx.node ./lib/
node index.js

两个构建步骤都可以从它们各自的 repo 根目录执行。


推荐阅读