在构建Docker容器时,在已挂载的卷上创建文件

4

我正在尝试在构建docker容器时创建一个文件,构建过程中没有出现任何错误,看起来文件已经成功写入,但是当我通过ssh登录到容器时,发现文件并不存在。

  • I write the file by doing RUN echo "Some line to add to a file" >> /var/www/public/text.txt on Dockerfile

  • My docker-compose.yml looks like:

    version: '2'
    
    services:
    web:
        build: web/
        ports:
            - "8080:80"
        volumes:
            - ./web/:/var/www/
        env_file:
            - web/.env
    
  • I execute docker-compose up --build

  • I then do docker exec -it <container id> bash
  • I cd to the folder /var/www/public and the file text.txt is not there
有什么想法吗?
2个回答

3

卷挂载在运行时应用,而不是在构建期间应用。构建的输出是一个可移植的镜像,而不是镜像和一些需要单独传输的持久化数据。该文件应该存在于您的镜像中,取决于 Dockerfile 的其余部分。

当您在运行时挂载主机卷时,构建图像内部的任何内容都被主机挂载隐藏。您只能看到主机上实际存在的文件(以及权限、UID 和 GID)。

然而,如果您切换到命名卷,docker 将使用该位置的镜像内容在它是新/空的时候初始化该卷。


0
你应该在 docker-compose.yml 文件中运行以下命令 - version: '2'
services:
web:
    build: web/
    ports:
        - "8080:80"
    volumes:
        - ./web/:/var/www/
    env_file:
        - web/.env
    command:"echo "Some line to add to a file" >> /var/www/public/text.txt "

由于您是在构建镜像后挂载卷。


但我希望文件在构建时创建。 - human

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