Is there any way to use the package installed globally instead of install the same when we run npm i
.
I have the following context:
I've created a docker image with one package already installed (install statement in the Dockerfile). When I run the container with the volumen which has the javascript project and I run npm i
it seems the package is installed again.
Could it be possible use the global package instead of instal it again?
CodePudding user response:
If you dont want to install again during the docker build the node_modules, you can create a base image with your node_modules.
FROM node:18-alpine3.16
WORKDIR /usr/src/app
COPY package* ./
RUN npm install
docker build -t myimage .
You can tag and push it to registry (dockerhub) Or use it locally as your new base image.
FROM myimage
WORKDIR /usr/src/app #Here are now already your node_modules
COPY . . # copy your code inside the image, or map the folder if you are in
# development
RUN npm run build # if you need a build
CMD ["mycommand","myargument"]
Note this quick, but you need to rebuild your base image if you add or update the node modules.
Consider also to use npm ci instead of npm install. In this way you keep same versions of your node modules each time you reinstall them.
Take care of security issues of the node modules as well of your base images.
run docker scan myimage
, periodically to get information of your node_modules or base images need updates.
During development, it is absolutly fine to map your code folders with the docker image. While developing is not even necessary to copy your code in the image. Just map it in your WORKDIR.
CodePudding user response:
After researching it seems the follow code solves my problem
WORKDIR /dir
RUN npm install package
RUN npm cache add package
RUN rm -rf *
WORKDIR /