Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 895
pBuch Avatar asked Mar 18 '17 17:03

pBuch


People also ask

How do you communicate with Docker compose?

Create an external network with docker network create <network name> In each of your docker-compose. yml configure the default network to use your externally created network with the networks top-level key. You can use either the service name or container name to connect between containers.

How do you connect a container to a container?

To connect to a container using plain docker commands, you can use docker exec and docker attach . docker exec is a lot more popular because you can run a new command that allows you to spawn a new shell. You can check processes, files and operate like in your local environment.


1 Answers

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
like image 156
Ayman Nedjmeddine Avatar answered Sep 19 '22 20:09

Ayman Nedjmeddine