Volumes are not mounting properly with docker-compose

I’m looking to mount a local directory on my host machine to my docker container.

Here is my current docker-compose.yml:

    version: '2'
    services:
      my-service:
        build: .
        ports:
          - "8080:8080"
        volumes:
          - .:/code

It gives no errors when I docker-compose build but when I docker-compose run, I’m expecting ./code to be populated with the contents of . on my local machine. In my Dockerfile, if I RUN ls /code, I get the following:

ls: cannot access '/code': No such file or directory

Can anyone spot what I’m doing wrong?

1 Like

I think I have a poor understanding of how docker-compose works… adding command: ls /code to docker-compose.yml gives me the expected result. It just seems that within the Dockerfile, I can’t reference those host files unless I copy them with ADD or COPY.

It effectively runs

docker build -t something .
docker run -v .:/code something

But notice in these two commands that the volume mount (docker run -v) option isn’t available in the docker build step, only afterwards.

If you’re fine rebuilding your container when your code changes (this is usually a pretty quick process) then you might add a line to your Dockerfile like

COPY . /code

and remove the “volumes” block in the docker-compose.yml. This will build the code into your image.