To containerize React application I've created Dockerfile.frontend & docker-compose.yml with the following contents:
Dockerfile.frontend:
FROM node:16
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install; \
# NOTE: Something change in Node v.16 and after 'npm install'
# it throws out the error "EACCES: permission denied,
# mkdir '/usr/app/node_modules/.cache'". Changing ownership
# of /node_modules folder solves the problem.
chown -R node:node ./node_modules;
EXPOSE 3000
docker-compose.yml:
version: '3.8'
services:
frontend:
container_name: front
build:
context: ./
dockerfile: Dockerfile.frontend
volumes:
# NOTE: Protect the 'node_modules' folder from being erased
- '/usr/src/app/node_modules'
- './:/usr/src/app'
ports:
- '3000:3000'
environment:
- NODE_ENV=development
command: npm start
NOTE : You can clone entire project for tests from GitHub
As you can see in the docker-compose.yml there are two volumes:
- ./:/usr/src/app - mapping to my project_root directory
- /usr/src/app/node_modules - anonymous volume to prevent node_modules from being erased when './:/usr/src/app' volume maps (to get more details see - Docker Compose: volumes without colon (:)).
And everything works like a charm, but after the first launch of the container, an empty node_modules directory appears in the project_root with the owner root:root. I am trying to delete this folder but it reappears after running the container. If I change the order in which the volumes are bound, nothing changes in the behavior.
I'm assuming this is because the both volume bindings overlap in the /usr/src/app/ directory. But I don't want node_modules full of the modules to be installed in the root of my project and I don't want to see an empty node_modules folder there. How to prevent an empty node_modules directory from appearing?
NOTE : There is an other answer to question like this, but the order of volume bindings in docer-compose.yml is different, although the result is the same! This means that the reason is not the order of volume bindings, like mentioned answer suggest.