Why do we need a volume option in docker-compose when we use react/next?

Viewed 1282

I have a question, why do we need to use VOLUME option in our docker-compose when we use for React/Next.js ?

If I understood, we use VOLUME to "save the data", for example when we use database.

But with React/Next.js we just use to pass the node_modules and app path, for me it does not make any sense...

If I put this:

version: '3'
services:
  nextjs-ui:
    build:
      context: ./
    ports:
      - "3000:3000"
    container_name: nextjs-ui
    volumes:
       - ./:/usr/src/app/
       - /usr/src/app/node_modules

It works..

If I put this:

version: '3'
services:
  nextjs-ui:
    build:
      context: ./
    ports:
      - "3000:3000"
    container_name: nextjs-ui

It works in the same way..

Why do we need to save node_modules and app path ?

My DOCKERFILE:

FROM node:12-alpine

WORKDIR /app

COPY package*.json ./

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001


COPY . .

EXPOSE 9000

RUN npm run build

CMD ["npm", "start"]

2 Answers

As per your Dockerfile, it's already copying your source code and does a npm run build. Finally it run npm start to start the development server (this is not recommended for production).

By mounting src/app and src/node_modules directories, you get the ability to reload your app while you make changes to the source in your host machine.

In summary, if you did not mount the source code, you have to rebuild the docker image and run it for your changes to be visible in the app. If you mounted the source and node_modules, you can leverage the live reloading capability of npm start and do development on host machine.

With the volumes included, you reflect all your local changes inside your dockerized Next application, which allows you to make use of features such as hot-reloading and not having to re-build the Docker container just to see the changes.

In production, you do not have to include these volumes.

Related