skip to Main Content

I’m trying to run Nodemon package in a Docker Network with two services, NodeJs and MongoDB.

When I run the app with npm start, nodemon works: I can connect to localhost:3000 and I have the changes in real time. But as soon as I run npm run docker (docker-compose up –build), I can connect to localhost:3000 but I’m not able to see real-time changes on my application nor console.

docker-compose.yml

    version: '3.7'
services:
  app:
    container_name: NodeJs
    build: .
    volumes:
      - "./app:/usr/src/app/app"
    ports:
      - 3000:3000
  mongo_db:
    container_name: MongoDB
    image: mongo
    volumes:
      - mongo_db:/data/db
    ports:
      - 27017:27017
volumes:
  mongo_db:

dockerfile

FROM node:alpine
WORKDIR /app
COPY package.json /.
RUN npm install
COPY . /app
CMD ["npm", "run", "dev"]

package.json

{
  "name": "projectvintedapi",
  "version": "0.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node index.js",
    "dev": "nodemon index.js",
    "docker": "docker-compose up --build"
  },
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.0",
    "express": "^4.17.3",
    "mongodb": "^4.5.0",
    "nodemon": "^2.0.15"
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    Fixed it: it was for bind mount

    dockerfile

    FROM node:16.13.2
    WORKDIR /app
    COPY package.json package-lock.json ./
    RUN npm ci
    COPY . ./
    CMD ["npm", "run", "start"]
    

    docker-compose.yml

       version: '3.7'
        services:
          app:
            container_name: NodeJs
            build: .
            command: npm run dev
            volumes:
              - .:/app
            ports:
              - 3000:3000
          mongo_db:
            container_name: MongoDB
            image: mongo
            volumes:
              - mongo_db:/data/db
            ports:
              - 27017:27017
        volumes:
          mongo_db:
    
      
    

  2. docker-compose.yml tells Docker to boot a container, the Node.js application. It also tells Docker to mount a host volume:

        volumes:
          - "./app:/usr/src/app/app"
    

    As a result, Docker will mount the ./app directory on your laptop, which contains your code, into the container at /usr/src/app/app.

    Once you’ve changed your code on your laptop/desktop, nodemon detects that change and restarts the process without rebuilding the container. To make this happen, you need to tell Docker to set the entrypoint to nodemon. Do that in the Dockerfile:

    FROM node:alpine
    WORKDIR /app
    COPY . /app
    
    RUN npm install -g nodemon
    RUN npm install
    
    #Give the path of your endpoint
    ENTRYPOINT ["nodemon", "/usr/src/app/server.js"]  
    CMD ["npm", "run", "dev"]
    

    With host volumes and nodemon, your code sync is almost instantaneous.

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