Hot Reloading with Docker-compose in NodeJs

Viewed 2643

I have seen a lot of codebase on Docker-compose + Nodejs but none of them are simple or basic enough to understand the flow of commands from docker-compose. I have created a very basic nodejs app which I intend to enable hot-reloading with containers.

My package.json looks like:

{
"name": "docker_web_app",
"version": "1.0.0",
"description": "Node.js on Docker",
"author": "First Last <first.last@example.com>",
"main": "server.js",
"scripts": {
    "start": "node server.js",
    "watch": "nodemon"
},
"dependencies": {
    "express": "^4.16.1",
    "nodemon": "^2.0.7"
}
}

Dockerfile looks like:

FROM node:14 as base

WORKDIR /home/node/app

COPY package*.json ./

RUN npm install -g nodemon && npm install

# Bundle app source
COPY . .

EXPOSE 4000
# RUN npm run start
CMD [ "npm", "start" ]

FROM node:14 as dev

WORKDIR /home/node/app

EXPOSE 4000

CMD ["npm", "watch"]

and the docker-compose.yml file looks like:

version: '3.7'
services:
  ts-node-docker:
    build:
      context: .
      dockerfile: Dockerfile
      target: base
    volumes:
      - ./:/home/node/app/
    container_name: ts-node-docker
    expose:
      - '4000'
    ports:
      - '4000:4000'
    command: npm run watch

What changes should I do to enable hot reloading in this codebase? Thanks!

1 Answers

Considering you are using this only for development.

You should not use volume

volumes:
      - ./:/home/node/app/

and COPY the source

# Bundle app source
COPY . .

together.

Just change your Dockerfile to

FROM node:14 as dev

WORKDIR /home/node/app

EXPOSE 4000

CMD ["npm", "watch"]

and modify package.json

"scripts": {
    "watch": "nodemon src/index.js'"
  },
Related