-
-
Save robinglen/3eea038b9f0c5e94de73f3c3482fa732 to your computer and use it in GitHub Desktop.
| const cluster = require('cluster'); | |
| const numCPUs = require('os').cpus().length; | |
| const fastify = require('fastify')(); | |
| const port = 8123; | |
| if (cluster.isMaster) { | |
| console.log(`Master ${process.pid} is running`); | |
| for (let i = 0; i < numCPUs; i++) { | |
| cluster.fork(); | |
| } | |
| cluster.on('exit', worker => { | |
| console.log(`Worker ${worker.process.pid} died`); | |
| }); | |
| } else { | |
| fastify.get('*', (req, res) => { | |
| res.send('Hello World'); | |
| }); | |
| fastify.listen(port, () => { | |
| console.log(`Fastify "Hello World" listening on port ${port}, PID: ${process.pid}`); | |
| }); | |
| } |
@matt212 so I don't know much about your setup and you're needs but from a DevOps / SRE perspective I don't recommend clustering node in production. You might get improved throughput and potentially cost savings but that will be outweighed by the complexity operating it.
So what I was suggesting was creating lightweight docker image for your service:
https://itnext.io/lightweight-and-performance-dockerfile-for-node-js-ec9eed3c5aef
However don't run node from npm in docker use node to save RAM.
https://medium.com/trendyol-tech/how-we-reduce-node-docker-image-size-in-3-steps-ff2762b51d5a
So you're using as little resource as possible, then these can be run anywhere but I was also suggesting using Kubernetes as a way to easily deploy and scale your services, I'm not sure on your infrastructure though.
Here is an article I wrote about how and why we used K8s at my old place:
https://medium.com/ynap-tech/beyond-gitops-how-we-release-our-microservices-on-kubernetes-at-ynap-683617cfd3cc
Hope this helps
@thearegee
Thanks again for detailed explanation .
to answer your question.
I currently dont have any infra setup I was researching
what is best to deploy , maintain and scale a normal b2b nodejs postgres platform and this gist came across :)
here is my nodejs postgres platform
https://github.com/matt212/Nodejs_Postgresql_VanillaJS_Fastify
i would look into docker and K8 as you have stated earlier thanks for that
that being said , Any suggestion pointers to scale the boilerplate platform is welcome :)
@thearegee
thanks for indept explanation about clustering
do you have any walkthroughs for
node single threaded and run multiple lightweight pods in K8s.thanks in advance cheers !
for time i will opt for pm2 clustering as suggested