如何构建一个 docker 镜像,并将其父文件夹作为 workdir?

tha*_*ter 1 docker dockerfile workdir

这可能是一个愚蠢的问题,但我是 Docker 的新手,我正在努力解决这个问题。我有一个包含许多子文件夹的项目,如下例所示:

project-folder:
       folder_1:
           code1.py
           Dockerfile
           requirements.txt
       folder_2:
           code2.py
           Dockerfile
           requirements.txt
       folder_data:
           file1
           file2
           file3
Run Code Online (Sandbox Code Playgroud)

然后,我想这样做:

  1. project-folder维护所有容器的工作目录;
  2. 在每个容器内,我应该能够访问folder_data- 我知道我必须指定一个卷,我只是不知道如何在不保留我的project-folderas workdir 的情况下执行此操作;
  3. 我需要将我的 workdir ( project-folder) 传递给我的 code1.py

注意:只有当我在每个子文件夹中创建图像时,图像才成功创建,如下 Dockerfile:

FROM python:3.6-slim
COPY . /folder_1
WORKDIR /folder_1
RUN pip install -r requirements.txt
CMD ["python3", "code1.py", "$(pwd)"]
Run Code Online (Sandbox Code Playgroud)

图像创建命令:

docker build -t image_folder1 .
Run Code Online (Sandbox Code Playgroud)

我目前正在 的上下文中创建图像folder_1,因为我无法在 的上下文中正确创建图像project-folder

Dav*_*aze 7

.命令末尾的参数是docker build上下文目录;您COPY进入图像的任何内容都必须在此子树内。如果您需要在图像中包含其直接子树之外的内容,则需要使用祖先目录作为构建上下文,但您可以使用该选项docker build -f来命名子目录中的文件。

cd project-folder
docker build -t image_folder1 -f folder_1/Dockerfile .
Run Code Online (Sandbox Code Playgroud)

在 Dockerfile 中,由于您从父目录开始,因此需要包含您COPY所在的任何文件的相对路径;但是,现在允许包含以前的同级目录。

FROM python:3.6-slim
WORKDIR /app

# Good practice to copy just dependencies first; this helps
# layer caching when you repeat `docker build`.
# COPY source path is relative to the `docker build` directory,
# which we've set up to be the parent of the application source.
COPY folder_1/requirements.txt .
RUN pip install -r requirements.txt

# Now copy in the rest of the application
COPY folder_1 .

# And also copy the shared data
COPY folder_data ./folder_data

# And have ordinary container startup metadata
CMD ["./code1.py"]
Run Code Online (Sandbox Code Playgroud)

不要在这里使用卷。Docker 有一个诱人的行为,即从映像内容填充命名卷,但如果重建,旧卷内容将优先于更新的映像内容,并且这只适用于本机 Docker 卷(不适用于主机目录绑定安装,根本不适用于在 Kubernetes 中)。最好的做法是拥有一个包含应用程序需要运行的所有内容的独立映像,而不是拥有需要从外部注入关键内容的部分映像。