skip to Main Content

I’m working on a Node.js backend project, and I’m using Docker with Docker Compose for my setup. My folder structure looks like this:

project-root/
│
├── server/
│   ├── Controllers/
│   ├── db/
│   ├── node_modules/
│   ├── Routers/
│   ├── server.js
│   ├── Dockerfile
│   ├── package.json
│   └── package-lock.json
├── docker-compose.yml
└── Client/

Despite using volumes in my docker-compose.yml to map my local server folder to the container, every time I make a change in server.js, I need to rebuild the Docker container for the changes to take effect. My expectation is that changes should be immediately reflected in the running container without a rebuild, especially since I’m using nodemon to watch for file changes.

docker-compose.yml:

version: '3.8'

services:
  api:
    build:
      context: ./server
      dockerfile: Dockerfile
    volumes:
      - ./server:/app
      - /app/node_modules
    ports:
      - "5000:5000"
    environment:
      - NODE_ENV=development
    command: npm start

Dockerfile

FROM node:16

WORKDIR /app

COPY package.json package-lock.json ./

RUN npm install

COPY . .

CMD ["npm", "start"]

Package.json

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

I want changes in my server.js file (and others) to be automatically picked up by the container without needing to rebuild. How can I achieve this? Is there something wrong with my volume setup, or am I missing something else?

2

Answers


  1. Chosen as BEST ANSWER

    I’m not sure if I implemented this correctly, but I modified my script to use

    “start”: “nodemon --legacy-watch server.js” 
    

    and it seems to be working! Now, I don't have to rebuild my Docker container whenever I make changes to my code.


  2. Try to correctly mount - /app/node_modules. You are missing either host or client by defining the other path with :. Just like you did with - ./server:/app.

    I think you are missing - ./server/node_modules:/app/node_modules

    In addition, to save "build time", you can try to use layers which allows you to utilize caching with docker.

    FROM node:16 AS dependencies
    
    WORKDIR /app
    
    COPY package.json package-lock.json ./
    
    RUN npm install
    
    FROM dependencies AS sourcecode
    
    COPY . .
    
    FROM sourcecode AS startblock
    
    CMD ["npm", "start"]
    

    Cached layers will not be rebuild unless they have changed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search