nodel
nodel

Reputation: 561

strange behavior from docker-compose volumes

I have a very simple directory structure:

docker-compose.yml
    - backend/
          - Dockerfile-node
          - package.json
          - my_backend.js

This is the docker-compose file. The API works fine up until I try to add a volume to the docker-compose file. When I uncomment out those lines, my app won't run since it says it can't find the dependencies I've installed. Is it not possible to have a volume set up in docker-compose where the files on the container are updated when I make a change locally? I know how to get that to happen with the docker run command, but it doesn' look possible here

version: "3.5"
services:
    node:
        build:
             context: ./backend
             dockerfile: Dockerfile-node
        ports: 
             - 5808:5808
#       volumes:
#           - ${PWD}/backend:/backend

Here are the contents of Dockerfile-node:

FROM node:8
WORKDIR /backend
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 5808
CMD ["npm", "start"]

And here is the start section of package.json:

"scripts" : {
    "start" : "nodemon my_backend.js"
 }

Upvotes: 0

Views: 185

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12089

This happens because your installed node_modules directory inside the container gets replaced when the volume is mounted.

I'd recommend changing your directory structure to put your application code inside a separate directory, e.g. app/:

docker-compose.yml
backend/
  - Dockerfile-node
  - package.json
  - app/
    - my_backend.js

You can then mount just the app/ directory as a volume:

version: "3.5"
services:
  node:
    build:
      context: ./backend
      dockerfile: Dockerfile-node
    ports: 
      - 5808:5808
    volumes:
      - ${PWD}/backend/app:/backend/app

This way, your node_modules get installed a directory up from app/ and, therefore, do not get deleted when the volume mounts.

You can now update your package.json script:

"scripts" : {
  "start" : "nodemon app/my_backend.js"
}

...and you will also need to update any import paths used in your application code to reflect the new directory structure.

I hope this helps.

Upvotes: 1

Related Questions