Categories
Docker

How to add hot reloading with docker-compose?

Spread the love

Sometimes, we want to add hot reloading with docker-compose

In this article, we’ll look at how to add hot reloading with docker-compose

How to use docker-compose to build multiple services?

To use docker-compose to build multiple services, we can create a Dockerfile for each service.

Then we create a docker-compose.yml to build each service with the Dockerfile for each service.

For instance, if we have the frontend and backend service in the frontend and backend folder respectively, then we create a docker-compose.yml in the root folder with

version: "3"
services:
  frontend:
    build: ./frontend
    ports:
      - "8091:8091"
  backend:
    build: ./backend
    ports:
      - "8090:8090"
    volumes:
      - ./backend:/usr/src/app

We set build to the folder with the Dockerfile we want to run.

ports map the port from the Docker container to the port exposed to the outside.

volumes map the folder in the project to the folder in the Docker container.

Mapping the volumes with volumes lets us add hot reloading.

In the frontend folder, we add a Dockerfile by writing

FROM node:lts-alpine
RUN npm install -g http-server
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

EXPOSE 8091
CMD [ "http-server", "dist", "-p 8091"]

to build the frontend container.

And in the backend folder, we add a Dockerfile by writing

FROM node:16

WORKDIR /usr/src/app
COPY package*.json ./

RUN npm install
RUN npm i -g nodemon
COPY . .

EXPOSE 8090
CMD [ "nodemon", "-L", "server.js" ]

to build the backend container.

We use the -L option when running nodemon to let it watch for changes in mapped volumes.

And then we run docker-compose up to build both containers.

Conclusion

To use docker-compose to build multiple services, we can create a Dockerfile for each service.

Then we create a docker-compose.yml to build each service with the Dockerfile for each service.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *