我们目前正在处理两个项目:
1 个基于 C++ 的项目
2 基于 Nodejs 的项目
这两个项目是分开的,这意味着它们有不同的代码库(git repository)和工作目录。
C++ 项目会生成一个节点绑定(bind)文件 .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
放入哪个项目?
最佳答案
您将有两种选择,因为限制因素是 Docker 只允许 copying from the same directory as the 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 允许 copy from an external container as 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
然后使用标签(在您的节点 Repo 根目录中)从中复制文件:
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 根目录执行。
关于Docker 多阶段构建与不同的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997002/