Home > OS >  Docker volumes and how to copy files between local and container
Docker volumes and how to copy files between local and container

Time:01-06

I have a docker-compose file with the relevant volumes section:

my-service:
   container_name: my-container
   ...
   volumes:
     - /host-dir:/container-dir

I want the contents of container-dir (configuration files) to be copied to host-dir on deploy, but only if the relevant file does not already exist. If it does, then the copying should always be from that file in /host-dir to that file in /container-dir.

The use case is to simplify the initial deploy, so that it's fully automated from a CI/CD pipeline without the need for additional intervention.

Is this possible, ideally using only docker-compose functionality? If not, how might one accomplish it?

CodePudding user response:

You can use a named volume with bind mount options. That way you get the behavior described here: https://docs.docker.com/storage/volumes/#populate-a-volume-using-a-container

If you start a container which creates a new volume, and the container has files or directories in the directory to be mounted such as /app/, the directory’s contents are copied into the volume. The container then mounts and uses the volume, and other containers which use the volume also have access to the pre-populated content.

services:
  my-service:
     volumes:
       - my-volume:/container-dir

volumes:
  my-volume:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: /path/to/host-dir
  • Related