How to watch file changes developing in NestJs app inside Docker container
I have it working now :)
The key is to create a volume in docker-compose with the local machine root folder of your microservice folder, in this case ./services/c2c-server-messages as the root of the app in the container :/api/messages
In this way, you are using your local files to run the app and not the files copied to the container, so you can watch for the changes when you save a file.
Example:
messages: image: c2c/messages:v1 volumes: - ./services/c2c-server-messages:/api/messages command: npm run start:dev build: context: ./services/c2c-server-messages dockerfile: Dockerfile container_name: c2c_server_messages depends_on: - postgres - nginx networks: c2c_net: ipv4_address: 172.28.1.5
When you run docker-compose ...
, it looks for a matching image (c2c/messages:v1
) and if it...
- finds the image locally, it runs it
- doesn't find it, your
docker-compose.yaml
will cause docker-compose to build the image.
Once running, one way to change the running process, is to change the files within the container image and then trigger to process to reload them. But, it is considered good practice to have 'immutable' (don't change) containers.
One way you may address this is to:
- add your sources to source control
- use some unique identifier of your source to detect changes.
(commonly a hash of your sources e.g. with git git --rev-parse HEAD
)
If your sources change, the hash will change and you can use this to trigger a rebuild of the image when docker-compose next starts. A simple way to do this would to be to:
TAG=$(git rev-parse HEAD)
- then use the hash as the tag for your image (instead of
v1
), e.g.c2c/messages:${TAG}
Your workflow would become:
- change your sources
- calculate the hash
docker-compose up...
referencing the image tagged with the hash to force rebuild
Using source control gives you a history of your sources.
Using image tags of your source's hashes allows you to match images to commits