Asia Piazza
Asia Piazza

Reputation: 95

Running Nodemon in Docker Container

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"
  }
}

Upvotes: 4

Views: 13309

Answers (2)

ahsan
ahsan

Reputation: 372

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.

Upvotes: 9

Asia Piazza
Asia Piazza

Reputation: 95

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:

  

Upvotes: 2

Related Questions