I have a basic NodeJS webpage set up in Docker. It works fine, except for when I add an npm
dependency. The initial setup works just fine, but when I have built the container once, and then want to add a dependency using npm install
, it installs fine, but it simply doesn't show up in my container.
Looking around, it seems like the issue is that the mounted volume is overwriting the data that npm install
created.
So, the question: Is it possible to use a mounted volume, like .LogServer:/app
without overwriting the node_modules
folder each time the container is built?
Here's my docker-compose.yaml
:
Log-Server:
container_name: Log-Server
image: node/logserver
build:
context: ./LogServer
restart: unless-stopped
ports:
- "3004:3000" # Webpage
- "3005:3005" # Websocket
environment:
PORT: 3000
volumes:
- logserver_node_modules:/app/node_modules/
- ./LogServer:/app
- ./Node-RED/data/logs:/logs/Node-RED/:ro
networks:
- docker-lan
# command: npm start
command: npm test
Dockerfile
:
FROM node:17-alpine3.15
WORKDIR /app
COPY package*.json ./
RUN npm ci
Edit after question was closed.
If you look at the linked question, the answers provided there are things I have already implemented, specifically this approach, because I want the npm modules to be persistent. Obviously, linking something that I am already doing will not answer my question.
Maybe my issue wasn't described clearly enough. I indeed want the node_modules
folder to be persistent in my container, but non-existent on my development machine. That's achieved by the line logserver_node_modules:/app/node_modules/
. That's not the issue I'm having, that works fine. The issue I'm having is that newly added dependencies don't show up in the container. I'm pretty sure this is due to the mounted volume overwriting what is installed from the Dockerfile
.
Simply put:
Dockerfile
correctly installs all dependencies into/app/node_modules/
docker-compose
mountslogserver_node_modules
on/app/node_modules/
, overwriting what was put there by theDockerfile
.
This is confirmed by the fact that changing the package.json
file prevents docker-compose up
from using cache on the last two steps (copying package*.json
and npm install
).
So the real question is: How can I have a persistent node_modules
volume, yet also be able to easily update my dependencies if required?
As a workaround I changed my package.json
file's test command to
"scripts": {
"test": "npm i && nodemon server.js",
"start": "node server.js"
},
This works just fine, and I think it's only a bit slower when nothing has changed, but it seems like a hack. Any other, better solutions would be nice, if they exist.