如何在容器退出时将目录从容器导出到主机?

35次阅读
没有评论

问题描述

有一个包含四个容器的 yaml 文件,其中三个是 Selenium Grid 容器,最后一个包含一个 Pytest 脚本。
它的工作方式如下:
1. 使用以下命令启动 yaml 文件:docker-compose -f e2e.yaml up
2. 这将创建四个容器。
3. 当 Selenium Grid 上的测试运行完成后,Pytest 容器将退出。因此,用户希望在容器退出时将生成在 Pytest 容器内的报告和截图导出到主机机器。

用户知道可以使用 Docker 命令来实现这一点,但他想在 yaml 文件中声明这些操作。他期望的语法如下:

services:
  e2e:
    build:
      dockerfile: Dockerfile
      context: .
    command: bash run_test_page.sh
    dirs_for_export:
      - export_dir_one:dir_container_path
      - export_dir_two:dir_container_path
    export_dirs:
      - export_dir_one:export_path_on_the_host
      - export_dir_two:export_path_on_the_host

用户不确定是否能够在 yaml 文件中实现这些操作,但如果有人知道如何做到这一点,将会很有帮助。

以下是实际的 yaml 文件:

version: '3.7'
services:
  e2e:
    build:
      dockerfile: Dockerfile
      context: .
    command: bash run_test_page.sh
    depends_on:
      - 'selenium-hub'
      - 'selenium-1'
      - 'selenium-2'
  selenium-1:
    image: selenium/node-chrome:latest
    shm_size: '2gb'
    depends_on:
      - selenium-hub
    environment:
      - SE_EVENT_BUS_HOST=selenium-hub
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
  selenium-2:
    image: selenium/node-chrome:latest
    shm_size: '2gb'
    depends_on:
      - selenium-hub
    environment:
      - SE_EVENT_BUS_HOST=selenium-hub
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
  selenium-hub:
    image: selenium/hub:latest
    expose:
      - 4444

Dockerfile 内容:

FROM ubuntu:latest
FROM python:3.8
COPY requirements.txt .
RUN pip3 install --no-cache-dir --user -r requirements.txt
COPY . .

解决方案

请注意以下操作可能会涉及版本差异和风险,请谨慎执行。

使用 Docker Compose 的 Volumes 属性

你可以使用 Docker Compose 的 volumes 属性,将主机路径挂载为卷到容器中的目录。这样在容器退出时,数据将从容器复制到主机。

以下是如何在你的 docker-compose.yml 文件中实现的步骤:

  1. e2e 服务下的 volumes 属性中添加卷的定义。假设 export_path_on_the_host 是主机上的路径,dir_container_path 是容器内的路径。
version: '3.7'
services:
  e2e:
    build:
      dockerfile: Dockerfile
      context: .
    command: bash run_test_page.sh
    depends_on:
      - 'selenium-hub'
      - 'selenium-1'
      - 'selenium-2'
    volumes:
      - export_path_on_the_host:/dir_container_path
  selenium-1:
    # 其他配置...
  selenium-2:
    # 其他配置...
  selenium-hub:
    # 其他配置...

在这个示例中,volumes 属性将主机路径 export_path_on_the_host 挂载到了容器内的路径 /dir_container_path

使用脚本实现

如果你希望更精细地控制数据的导出,你可以使用一个脚本来在容器退出时执行复制操作。以下是一个简单的示例脚本:

#!/bin/bash
# 启动容器
docker-compose -f e2e.yaml up -d
# 等待容器退出
docker wait e2e
# 复制数据到主机路径
docker cp e2e:/dir_container_path export_path_on_the_host
# 停止容器
docker-compose -f e2e.yaml down

在这个示例中,脚本执行了以下操作:
1. 使用 docker-compose 启动容器。
2. 使用 docker wait 等待容器退出。
3. 使用 docker cp 将容器内的数据复制到主机路径。
4. 使用 docker-compose 停止容器。

你可以根据实际需求进行修改和扩展。

总结

无论是使用 Docker Compose 的 volumes 属性,还是使用脚本实现,都能达到将容器内的数据在容器退出时导出到主机的目的。选择适合你情况的方法并根据实际需求进行配置和调整。

正文完