Overwrite files with `docker run`

2020-06-23 08:07发布

问题:

Maybe I'm missing this when reading the docs, but is there a way to overwrite files on the container's file system when issuing a docker run command?

Something akin to the Dockerfile COPY command? The key desire here is to be able to take a particular Docker image, and spin several of the same image up, but with different configuration files. (I'd prefer to do this with environment variables, but the application that I'm Dockerizing is not partial to that.)

回答1:

You have a few options. Using something like docker-compose, you could automatically build a unique image for each container using your base image as a template. For example, if you had a docker-compose.yml that look liked:

container0:
  build: container0

container1:
  build: container1

And then inside container0/Dockerfile you had:

FROM larsks/thttpd
COPY index.html /index.html

And inside container0/index.html you had whatever content you wanted, then running docker-compose build would generate unique images for each entry (and running docker-compose up would start everything up).

I've put together an example of the above here.

Using just the Docker command line, you can use host volume mounts, which allow you to mount files into a container as well as directories. Using my thttpd as an example again, you could use the following -v argument to override /index.html in the container with the content of your choice:

docker run -v index.html:/index.html larsks/thttpd

And you could accomplish the same thing with docker-compose via the volume entry:

container0:
  image: larsks/thttpd
  volumes:
    - ./container0/index.html:/index.html

container1:
  image: larsks/thttpd
  volumes:
    - ./container1/index.html:/index.html

I would suggest that using the build mechanism makes more sense if you are trying to override many files, while using volumes is fine for one or two files.

A key difference between the two mechanisms is that when building images, each container will have a copy of the files, while using volume mounts, changes made to the file within the image will be reflected on the host filesystem.



标签: docker