user1016265
user1016265

Reputation: 2397

Docker for local NodeJS development

What is the right way to develop app locally in the container, when it is possible to have node_modules on my laptop file system.

Currently I have following settings in the Dockerfile

COPY package.json /app/
RUN npm install
COPY . /app/

And the following docker-compose

 volumes:
    - "/app/node_modules"

In that case I'm able to run npm commands in the container, and changes in the package.json are reflected in my local source tree. Which is good. But one thing is missing: I don't have locally node_modules folder and it means my IDE can't see these files.

Is it possible to fix somehow?

Upvotes: 1

Views: 526

Answers (1)

Jan Grz
Jan Grz

Reputation: 1471

You can copy all your local environment to the container:

COPY ./package.json /app/package.json
WORKDIR /app/
RUN npm install
COPY ./src/ /app/src/
CMD ["npm","run","start"]

This approach will literally copy your local environment to the image. Everytime you would make a change to your sources - you would have to rebuild the image and restart the container.

I recommend that you mount your project folder as a volume to the container - with all dependencies, and every change in the sources/dependencies would require just restarting the container (or you can use a supervisor inside the container):

VOLUME /app/
WORKDIR /app/
CMD ["npm","run","start"]

When running the container - remember to connect your project directory to the container:

And the docker-compose.yml file

version: '2'

services:
  app:
    build: .
    image: app
    volumes: [".:/app/"]

(I assumed that the Dockerfile for your Node.js app is in the same directory as sources, node_modules and docker-compose.yml )


EDIT: The solution posted above is good for local development. If you want to dockerize and deploy your application there are two approaches:

Copy your local node_modules and all sources to the container:

COPY ./node_modules /app/
COPY ./src /app/
COPY ./package.json /app/
WORKDIR /app/
CMD ["npm","run","start"]

Or to use the template from the top of my answer(it will install all the node_modules during the build - when package.json changes) this build is way slower.

Upvotes: 1

Related Questions