I am building a Node.JS application using Postgres as the database. I am using Docker/Docker compose for the development environment. I could dockerise my environment. However there is one issue remain which is the project is not refreshing or showing the latest changes using Nodemon. Basically it is not detecting the code changes.
I have a docker-compose.yaml file with the following code.
version: '3.8'
services:
web:
container_name: web-server
build: .
ports:
- 4000:4000
restart: always
This is my Dockerfile.
FROM node:14-alpine
RUN apk update && apk upgrade
RUN apk add nodejs
RUN rm -rf /var/cache/apk/*
COPY . /
RUN cd /; npm install;
RUN npm install -g nodemon
EXPOSE 4000
CMD ["npm", "run", "docker-dev"]
This is my docker-dev script in package.json file
"docker-dev": "nodemon -L --inspect=0.0.0.0 index.js"
When I spin up the environment running docker-compose up -d
and go to the localhost:4000 on the browser, I can see my application up and running there. But when I make the changes to the code and refresh the page, the new changes are not there. It seems like Nodemon is not working. I had to remove Docker images and spin up the environment again to see the latest changes.
How can I fix it?
2
Answers
You are doing your changes in your local file system and not in the docker container file system.
You need to use a volume of you want to see your changes reflecting real time.
During development, I often use a raw node image and run it like this
The different parts of the command do the following
--rm
remove the container when it exits-d
run detached-v $(pwd):/app
map the current directory to /app in the container--workdir /app
set the working directory in the container to /app-u $(id -u):$(id -g)
run the container with my UID and GID so any files created in the host directory will be owned by me-p 3000:3000
map port 3000 to the host--entrypoint /bin/bash
set the entrypoint to bashnode
run the official node image-c "npm install && npm start"
on container start, install npm packages and start the appYou can do something similar. If we replace a few things, this should match your project
I’ve changed the entrypoint because Alpine doesn’t have bash installed. The image is node:14-alpine. The port is 4000. And on start, you want it to install nodemon and run the docker-dev script.
I put the command in a shell script so I don’t have to type it all out every time.