Start Node application with different process manager based on ENV
Nodejs application often depended on Environment variables and in normal cases it is fine but in case of Docker, I will not recommend to the run container and change behaviour of the container based on environment variables.
Docker tag should be defined for each environment, like
FROM node:alpine ENV NODE_ENV=stage # Rest of thing for staging environment
So now we can build the image and tag it accordingly.
docker build -t node-application:stage .
Normally if there is only `NODE_ENV` then it can also be mange with ARGS, but in today article we will focus on starting node application with the different process manager.
The crazy idea does not come easily and we are stick to our own approach but if you are part of 10 Million community then definitely you will see crazy ideas and approach, sometimes it more then the question or a problem. We are supposed to answer the problem plus we should also convince them that this the solution but this is not the practice and blah blah to guide them in right direction.
During my research study, one of my Best Teacher Ghazanfar Farooq always used to say
So the question was good so that make impels to write an article and share with the community.
Dockerfie
FROM node:alpine RUN npm install pm2 -g WORKDIR /app COPY package.json package-lock.json /app RUN npm install COPY . /app ENV NODE_ENV=development RUN chmod +x docker-entrypoint.sh ENTRYPOINT ["sh","docker-entrypoint.sh"]
docker-entrypoint.sh
#!bin/sh # :docker-entrypoint.sh #description :This script will run process with PM based on ENV #author : AdilM #date :20190930 #version :0.1 #usage :ENTRYPOINT ["sh","docker-entrypoint.sh"] if [ $NODE_ENV = "development" ]; then # start process with pm2 in development environment to restart application on change pm2-runtime /app/server.js else # start process with node in production or any other environment node /app/server.js fi #Replacing pm2-runtime with pm2-dev will enable the watch and restart features. This is quite interesting in a development container when the host files are exposed to the container as a VOLUME.
Based on the Dockerfile the application will start with pm2 but you can override this behaviour based ENV, so we can pass the NODE_ENV to docker run command. Now the tag does not matter, whatever tag of the image is, it will be modified the NODE_ENV and the behaviour starting application will be changed accordingly.
docker run --env NODE_ENV=production -it --rm node-application:tag
Thanks for reading, and please do comment and share the article. Will come again with something crazy in next article ;)
If you like the idea please visit the link below for more detail and do not forget to credit the question and answer on stack-overflow.
https://stackoverflow.com/a/58158414/3288890
It was quite an informative article. Thanks for sharing!
Perfect 👌