Docker 构建上下文拼图
Docker build context puzzle
我的项目结构:
projectRoot/
- service/
- data.json
- Dockerfile
在那 Dockerfile
:
FROM node:16.14-alpine3.14
ENV THE_DATA=/tmp/data.json
COPY data.json /tmp/data.json
在项目根目录下,如果我构建镜像:
docker build -t service:data_tmp -f service/Dockerfile .
我收到错误:
=> ERROR [2/2] COPY data.json /tmp/data.json
...
failed to compute cache key: "/data.json" not found: not found
我猜错误是由于最后一个 .
表示构建上下文是项目根目录,这就是为什么 data.json
无法定位的原因。
(我的第二次尝试) 然后,我将 Dockerfile
更改为:
FROM node:16.14-alpine3.14
ENV THE_DATA=/tmp/data.json
COPY ./service/data.json /tmp/data.json
但是报错:
=> ERROR [2/2] COPY ./service/data.json /tmp/data.json
...
failed to compute cache key: "/service/data.json" not found: not found
(我的第三次尝试 成功) 我设法通过将构建上下文更改为 /service/
:
使其最终成功构建
docker build -t service:data_tmp -f service/Dockerfile /service/
但我不明白为什么上面的 第二次尝试 不起作用?我的意思是在我的第二次尝试中,即使构建上下文仍然是 .
表示当前目录,表示项目根目录,那么 ./service/data.json
的路径 COPY
应该是正确的。为什么我仍然在那里出错?
如果在 COPY
步骤中找不到文件系统上存在的文件,请检查两件事:
- 你的上下文,这是在这里完成的。那是构建命令末尾的
.
表示上下文是当前目录。如果你传递一个不同的目录,那是 COPY
步骤的来源(至少那些不使用 --from
改变源的步骤)。
- 一个
.dockerignore
文件。这是上下文的根,语法类似于 .gitignore
。更改上下文时,您更改 docker 检查 .dockerignore
文件的位置。
最小 docker 构建的常见模式是指定 .dockerignore
文件:
*
!src
# ...
这告诉 docker 排除第一行的所有内容,然后在第二行重新包含 src
。您将添加额外的行以使用 !service
.
在此处重新包含文件夹
我的项目结构:
projectRoot/
- service/
- data.json
- Dockerfile
在那 Dockerfile
:
FROM node:16.14-alpine3.14
ENV THE_DATA=/tmp/data.json
COPY data.json /tmp/data.json
在项目根目录下,如果我构建镜像:
docker build -t service:data_tmp -f service/Dockerfile .
我收到错误:
=> ERROR [2/2] COPY data.json /tmp/data.json
...
failed to compute cache key: "/data.json" not found: not found
我猜错误是由于最后一个 .
表示构建上下文是项目根目录,这就是为什么 data.json
无法定位的原因。
(我的第二次尝试) 然后,我将 Dockerfile
更改为:
FROM node:16.14-alpine3.14
ENV THE_DATA=/tmp/data.json
COPY ./service/data.json /tmp/data.json
但是报错:
=> ERROR [2/2] COPY ./service/data.json /tmp/data.json
...
failed to compute cache key: "/service/data.json" not found: not found
(我的第三次尝试 成功) 我设法通过将构建上下文更改为 /service/
:
docker build -t service:data_tmp -f service/Dockerfile /service/
但我不明白为什么上面的 第二次尝试 不起作用?我的意思是在我的第二次尝试中,即使构建上下文仍然是 .
表示当前目录,表示项目根目录,那么 ./service/data.json
的路径 COPY
应该是正确的。为什么我仍然在那里出错?
如果在 COPY
步骤中找不到文件系统上存在的文件,请检查两件事:
- 你的上下文,这是在这里完成的。那是构建命令末尾的
.
表示上下文是当前目录。如果你传递一个不同的目录,那是COPY
步骤的来源(至少那些不使用--from
改变源的步骤)。 - 一个
.dockerignore
文件。这是上下文的根,语法类似于.gitignore
。更改上下文时,您更改 docker 检查.dockerignore
文件的位置。
最小 docker 构建的常见模式是指定 .dockerignore
文件:
*
!src
# ...
这告诉 docker 排除第一行的所有内容,然后在第二行重新包含 src
。您将添加额外的行以使用 !service
.