Create files / folders on docker-compose build or

2019-04-19 01:46发布

问题:

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 build to create the image, and docker-compose-up to run the server. But I get no file index.html or folder images.

This is my Dockerfile:

FROM php:apache
MAINTAINER brent@dropsolid.com

WORKDIR /var/www/html

RUN touch index.html \
    && mkdir images

And this is my docker-compose.yml

version: '2'
services:
  web:
    build: .docker/web
    ports:
      - "80:80"
    volumes:
      - ./docroot:/var/www/html

I would expect that this would create a docroot folder with an image directory and an index.html, but I only get the docroot.

回答1:

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.