14

Until now, I have used a local LAMP stack to develop my web projects and deploy them manually to the server. For the next project I want to use docker and docker-compose to create a mariaDB, NGINX and a project container for easy developing and deploying.

When developing I want my code directory on the host machine to be synchronised with the docker container. I know that could be achieved by running

docker run -dt --name containerName -v /path/on/host:/path/in/container

in the cli as stated here, but I want to do that within a docker-compose v2 file.

I am as far as having a docker-composer.yml file looking like this:

version: '2'

services:
    db:
        #[...]
    myProj:
        build: ./myProj
        image: myProj
        depends_on:
            - db
        volumes:
            myCodeVolume:/var/www
volumes:
    myCodeVolume:

How can I synchronise my /var/www directory in the container with my host machine (Ubuntu desktop, macos or Windows machine)?

Thank you for your help.

Community
  • 1
  • 1
pBuch
  • 986
  • 1
  • 6
  • 20
  • Just checking; You wrote `docker-composer.yml` instead of `docker-compose.yml`. Not sure if that was a typo or not (other thing might not have worked if you had really run the former), but thought I'd check. – metasoarous Jul 08 '21 at 00:44

1 Answers1

10

It is pretty much the same way, you do the host:container mapping directly under the services.myProj.volumes key in your compose file:

version: '2'
services:
    ...
    myProj:
        ...
        volumes:
            /path/to/file/on/host:/var/www

Note that the top-level volumes key is removed.

This file could be translated into:

docker create --links db -v /path/to/file/on/host:/var/www myProj

When docker-compose finds the top-level volumes section it tries to docker volume create the keys under it first before creating any other container. Those volumes could be then used to hold the data you want to be persistent across containers. So, if I take your file for an example, it would translate into something like this:

docker volume create myCodeVolume
docker create --links db -v myCodeVoume:/var/www myProj
Ayman Nedjmeddine
  • 11,521
  • 1
  • 20
  • 31
  • 1
    Thank you! So if I understand you right, I can use the top-level volumes for sharing files between containers and the inside-services volumes for container-host sharing? – pBuch Mar 18 '17 at 20:30
  • Yes. But to complete the answer, inside-services volumes can still be used the same way as it would via the CLI :) – Ayman Nedjmeddine Mar 18 '17 at 20:53