Create files / folders on docker-compose build or docker-compose up

前端 未结 1 556
囚心锁ツ
囚心锁ツ 2021-02-18 19:40

I\'m trying my first steps into Docker, so I tried making a Dockerfile that creates a simple index.html and a directory images (See code below)

Then I run docker-compose

相关标签:
1条回答
  • 2021-02-18 20:01

    The image does contain those files

    The Dockerfile contains instructions on how to build an image. The image you built from that Dockerfile does contain index.html and images/.

    But, you over-rode them in the container

    At runtime, you created a container from the image you built. In that container, you mounted the external directory ./docroot as /var/www/html.

    A mount will hide whatever was at that path before, so this mount will hide the prior contents of /var/www/html, replacing them with whatever is in ./docroot.

    Putting stuff in your mount

    In the comments you asked

    is there a possibility then to first mount and then create files or something? Or is that impossible?

    The way you have done things, you mounted over your original files, so they are no longer accessible once the container is created.

    There are a couple of ways you can handle this.

    Change their path in the image

    If you put these files in a different path in your image, then they will not be overwritten by the mount.

    WORKDIR /var/www/alternate-html
    
    RUN touch index.html \
        && mkdir images
    
    WORKDIR /var/www/html
    

    Now, at runtime you will still have this mount at /var/www/html, which will contain the contents from the external directory. Which may or may not be an empty directory. You can tell the container on startup to run a script and copy things there, if that's what you want.

    COPY entrypoint.sh /entrypoint.sh
    RUN chmod 0755 /entrypoint.sh
    ENTRYPOINT ["/entrypoint.sh"]
    

    (This is assuming you do not have a defined entrypoint - if you do, you'll maybe just need to adjust your existing script instead.)

    entrypoint.sh:

    #!/bin/sh
    
    cp -r /var/www/alternate-html/* /var/www/html
    exec "$@"
    

    This will run the cp command, and then hand control over to whatever the CMD for this image is.

    Handling it externally

    You also have the option of simply pre-populating the files you want into ./docroot externally. Then they will just be there when the container starts and adds the directory mount.

    0 讨论(0)
提交回复
热议问题