在Docker容器和主机之间同步文件

4
场景是这样的:我有一个名为static的文件夹,其中包含一个名为sample_old.txt的文件,并使用docker-compose.yml将其挂载到容器中的static。然后我使用docker-compose up启动我的docker服务。接着调用一个函数在static文件夹中创建一个名为sample_new.txt的新文件。结果,它在static文件夹内生成了新文件(通过使用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函数

@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"
2个回答

3
问题在于`docker-compose.yml`文件定义不够清晰;你没有在`static`挂载点的定义中加入一个.,应该是./static,因为它在当前工作目录下。
services:
  web:
    ...
    - ./static:/celery_sample/static

0

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


3
有没有其他的方式可以通过 Dockerfile 或者 docker-compose.yml 文件来完成? - JPG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接