How to sync code between container and host using docker-compose?

pBuch picture pBuch · Mar 18, 2017 · Viewed 12.9k times · Source

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.

Answer

Ayman Nedjmeddine picture Ayman Nedjmeddine · Mar 18, 2017

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