skip to Main Content

I tried to find solution over a long time – reloading nodemon in docker while updating e.g index.js. I’ve windows 10.
I’ve node project with docker:
proj/backend/src/index.js:

const express = require('express')
const app = express()
app.get('/', (req, res) => {
    res.send('Hello world.')
})
const port = process.env.PORT || 3001
app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

proj/backend/package.json:

{
  "scripts": {
    "start": "node ./bin/www",
    "start:legacy": "nodemon --legacy-watch -L --watch src src/index.js"
  },
  "dependencies": {
    "express": "^4.17.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}

proj/backend/dev.Dockerfile:

FROM node:lts-alpine
RUN npm install --global nodemon
WORKDIR /usr/src/app
COPY . .
RUN npm ci
EXPOSE 3001
ENV DEBUG=playground:*
CMD npm run start:legacy

proj/docker-compose.dev.yml:

version: '3.8'
services:
  backend:
    image: backend-img
    build:
      context: ./backend
      dockerfile: ./dev.Dockerfile
    ports:
      - 3001:3001
    environment:
      - PORT=3001

2

Answers


  1. If I am not wrong, the docker container is made for kill itself when the process ends. When using nodemon (and updating the code), the process will be stopped and restarted and the container will stop. You could do the npm start not be the main process, but this is not a good practice.

    Login or Signup to reply.
  2. Probably, it’s already late. But I will write.

    There are misconceptions in your configuration.

    1. In command "start:legacy". You should use only one option to run legacy --legacy-watch or -L, not both. Because these commands are equal. According to nodemon docs: Via the CLI, use either –legacy-watch or -L for short

    2. Your Dockerfile configurations seems fine. But to synchronize your local machine files and directory with docker container you should use volumes in docker-compose. So, your docker-compose file will look something like:

    version: '3.8'
    services:
      backend:
        image: backend-img
        build:
          context: ./backend
          dockerfile: ./dev.Dockerfile
        volumes:
          - ./your_project_dir:/usr/src/app
          - /usr/src/app/node_modules
        ports:
          - 3001:3001
        environment:
          - PORT=3001
    

    I believe, if you define volumes you will able to make changes locally and container also will see changes

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