【问题标题】:sync files between docker container and host machine在 docker 容器和主机之间同步文件
【发布时间】:2017-07-23 04:52:28
【问题描述】:

场景是;我有一个文件夹 static ,它包含一个名为 sample_old.txt 的文件,并使用 docker-compose.ymlstatic 安装到容器中。然后我使用docker-compose up 启动我的docker 服务。然后调用一个函数在static文件夹内创建一个名为sample_new.txt的新文件。结果,它在静态内部生成了新文件(通过使用sudo docker exec -it container_id bash进入容器进行验证)但问题是,新生成的文件仅在容器中可用,不在主机操作系统中。

如何使容器内新生成的文件可用以托管?我可以一直同步目录吗?我不知道这是否可能。如果可能,请提供解决方案。

docker-compose.yml

version: "3"
services:

  web:
    build:
      context: .
      dockerfile: Dockerfile
    command: "python my_celery.py"
    ports:
      - "8000:8000"
    networks:
      - webnet
    volumes:
      - .:/celery_sample
      - /static:/celery_sample/static

networks:
  webnet:

目录结构-宿主操作系统

.
├── docker-compose.yml
├── Dockerfile
├── __init__.py
├── my_celery.py 
├── README.md
├── requirements.txt
└── static
    └── sample_old.txt

目录结构-容器

.
    ├── docker-compose.yml
    ├── Dockerfile
    ├── __init__.py
    ├── my_celery.py 
    ├── README.md
    ├── requirements.txt
    └── static
        └── sample_old.txt
        └── sample_new.txt

用于文件生成的烧瓶函数

@flask_app.route('/text')
def generate_file():
    file_dir_path = os.path.join(os.getcwd(), "static")
    if not os.path.exists(file_dir_path):
        os.mkdir(file_dir_path)
    with open(os.path.join(file_dir_path, "sample_new.txt"), "wb+") as fo:
        fo.write("This is just s test".encode())
    return "Writed to file"

【问题讨论】:

    标签: python-3.x docker flask docker-compose docker-volume


    【解决方案1】:

    问题出在docker-compose.yml文件定义不明确;您在static 挂载点的定义中缺少.,它应该是./static,因为它位于当前工作目录中。

    services:
      web:
        ...
        - ./static:/celery_sample/static
    

    【讨论】:

      【解决方案2】:

      我在工作中使用了很棒的 docker-sync 库,我喜欢它用于开发和双向数据同步。它使用Unison 在容器和本地文件之间快速同步文件。

      【讨论】:

      • 有没有其他方法可以通过 Dockerfiledocker-compose.yml 完成?
      猜你喜欢
      • 2017-08-10
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 2020-01-07
      • 2013-09-23
      相关资源
      最近更新 更多