Néha elgondolkodom azon, hogy tudok-e egyáltalán sokat.
Néhány hete beszéltem egy barátommal, aki kézenfekvő módon említette, hogy „soha nem futtatna közvetlenül Node-ot a gyártásban.
Bólintottam erőteljesen jelzi, hogy én is soha nem botlott ellen Node a termelés, mert ... hahaha ... .everyone tudja. De ezt nem tudtam! Tudtam volna ezt?! ?? MÉG MEGHAGYOK PROGRAMOZNI?
Ha Venn-diagramot rajzolnék arról, amit tudok, és amit úgy érzem, mint mindenki más, akkor ez így nézne ki ...

Egyébként ez az apró pont annál kisebb lesz, minél idősebb vagyok.
Van egy jobb diagram, amelyet Alicia Liu készített, és ez megváltoztatta az életemet. Azt mondja, hogy ez inkább ilyen ...

Nagyon szeretem ezt a diagramot, mert azt akarom, hogy igaz legyen. Nem akarom életem hátralévő részét a jelentéktelenség apró, zsugorodó kék pontjaként tölteni.
SO DRAMATIC. Pandorát hibáztatni. A cikk írása közben nem szabályozom, hogy mi következik a következő lejátszás, és a Dashboard Confessional egy helluva gyógyszer.
Nos, feltételezve, hogy Alicia diagramja igaz, szeretném megosztani veletek, mit tudok most a Node-alkalmazások futtatásáról a gyártásban. Talán rokon Venn-diagramjaink nem fedik egymást ebben a témában.
Először is foglalkozzunk azzal a kijelentéssel, hogy „soha ne futtassunk alkalmazásokat közvetlenül a Node ellen a gyártásban”.
Soha ne futtasson közvetlenül a Node ellen a gyártásban
Talán. De talán nem. Beszéljünk a kijelentés mögött meghúzódó érvelésről. Először nézzük meg, miért nem.
Tegyük fel, hogy van egy egyszerű Express szerverünk. A legegyszerűbb Express szerver, amire gondolok ...
const express = require("express"); const app = express(); const port = process.env.PORT || 3000; // viewed at //localhost:3000 app.get("/", function(req, res) { res.send("Again I Go Unnoticed"); }); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Ezt futtatnánk egy start szkriptel a package.json
fájlban.
"scripts": { "dev": "npx supervisor index.js", "start": "node index.js" }

Valahogy két probléma van itt. Az első fejlesztési, a második pedig a termelési probléma.
A fejlesztési probléma az, hogy amikor megváltoztatjuk a kódot, le kell állnunk és el kell indítanunk az alkalmazást, hogy a változásainkat felvegyék.
Ennek megoldására általában valamilyen Node folyamatkezelőt használunk, mint például supervisor
vagy nodemon
. Ezek a csomagok figyelik a projektünket és újraindítják a szerverünket, valahányszor változtatásokat hajtunk végre. Általában így csinálom ...
"scripts": { "dev": "npx supervisor index.js", "start": "node index.js"}
Aztán futok npm run dev
. Ne feledje, hogy npx supervisor
itt futok , amely lehetővé teszi, hogy a supervisor
csomagot telepítés nélkül használjam . I ❤️ 2019. Leginkább.
A másik problémánk az, hogy még mindig közvetlenül a Node ellen futunk, és azt már mondtuk, hogy ez rossz volt, és most kiderítjük, miért.
Hozzá fogok adni egy másik útvonalat, amely megkísérel egy olyan fájlt olvasni a lemezről, amely nem létezik. Ez egy olyan hiba, amely könnyen megjelenhet bármely valós alkalmazásban.
const express = require("express"); const app = express(); const fs = require("fs"); const port = process.env.PORT || 3000; // viewed at //localhost:3000 app.get("/", function(req, res) { res.send("Again I Go Unnoticed"); }); app.get("/read", function(req, res) { // this does not exist fs.createReadStream("my-self-esteem.txt"); }); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Ha ezt közvetlenül a Node ellen futtatjuk npm start
és a read
végpontig navigálunk, hibát kapunk, mert az a fájl nem létezik.

Melyik - nem nagy baj, igaz? Ez egy hiba. Megtörténik.
NEM. Nagy ügy. Ha visszamegy a terminálhoz, látni fogja, hogy az alkalmazás teljesen leállt.

Ami azt jelenti, hogy ha visszamész a böngészőbe, és megpróbálsz a webhely gyökér URL-jére menni, akkor ugyanazt a hibaoldalt kapod. Egy hiba egy módszerben mindenki számára lerombolta az alkalmazást .
Ez rossz. Mint nagyon rossz. Ez az egyik fő oka annak, hogy az emberek azt mondják, hogy „soha ne fuss közvetlenül a Node ellen a gyártásban” .
RENDBEN. Tehát, ha nem tudunk a Node ellen futni a gyártásban, mi a helyes módja a Node futtatásának a gyártásban?
A gyártási csomópont beállításai
Van néhány lehetőségünk.
Az egyik az lenne, ha egyszerűen használnánk valami hasonlót supervisor
vagy nodemon
a gyártást, ugyanúgy, ahogyan a dev-ben is. Ez működne, de ezek az eszközök egy kicsit a könnyű oldalon állnak. Jobb lehetőség a pm2 nevű valami.
pm2 a mentés
A pm2 egy csomópont folyamatkezelő, amely sok harangot és sípot tartalmaz. Csakúgy, mint minden más „JavaScript”, itt is telepíti (globálisan) innen npm
- vagy csak npx
újra használhatja . Nem akarom elmondani, hogyan éld az életed.
Nagyon sokféleképpen futtathatja az alkalmazását a pm2-vel. A legegyszerűbb módszer, ha csak felhívja pm2 start
a belépési pontot.
"scripts": { "start": "pm2 start index.js", "dev": "npx supervisor index.js" },
És látni fog valami ilyesmit a terminálon ...

Ez a folyamatunk a háttérben fut, amelyet pm2 figyel. Ha meglátogatja a read
végpontot, és összeomlik az alkalmazás, a pm2 automatikusan újraindítja. Ilyet nem fog látni a terminálon, mert a háttérben fut. Ha azt akarod nézni, hogy a pm2 megteszi a dolgát, akkor futnod kell pm2 log 0
. Ez 0
annak a folyamatnak az azonosítója, amelynek naplóit meg akarjuk tekinteni.

Tessék! Láthatja, hogy a pm2 újraindítja az alkalmazást, amikor leáll a kezeletlen hibánk miatt.
Kihúzhatjuk a dev parancsunkat, és rendelkezhetünk pm2 figyelő fájlokkal, és újraindíthatjuk az esetleges változásokat.
"scripts": { "start": "pm2 start index.js --watch", "dev": "npx supervisor index.js" },
Ne feledje, hogy mivel a pm2 a háttérben futtatja a dolgokat, nem csak ctrl+c
kiléphet a futó pm2 folyamatból. Meg kell állítania az azonosító vagy a név átadásával.
pm2 stop 0
pm2 stop index
Vegye figyelembe azt is, hogy a pm2 megőrzi a folyamatra való hivatkozást, így újraindíthatja.

If you want to delete that process reference, you need to run pm2 delete
. You can stop and delete a process in one command with delete
.
pm2 delete index
We can also use pm2 to run multiple processes of our application. pm2 will automatically balance the load across those instances.
Multiple processes with pm2 fork mode
pm2 has a ton of configuration options and those are contained in an “ecosystem” file. To create one, run pm2 init
. You’ll get something like this…
module.exports = { apps: [ { name: "Express App", script: "index.js", instances: 4, autorestart: true, watch: true, max_memory_restart: "1G", env: { NODE_ENV: "development" }, env_production: { NODE_ENV: "production" } } ] };
I’m going to ignore the “deploy” section in this article because I have no idea what it does.
The “apps” section is where you define the apps you want pm2 to run and monitor. You can run more than one. A lot of these configuration settings are probably self-explanatory. The one that I want to focus on here is the instances setting.
pm2 can run multiple instances of your application. You can pass in a number of instances that you want to run and pm2 will spin up that many. So if we wanted to run 4 instances, we could have the following configuration file.
module.exports = { apps: [ { name: "Express App", script: "index.js", instances: 4, autorestart: true, watch: true, max_memory_restart: "1G", env: { NODE_ENV: "development" }, env_production: { NODE_ENV: "production" } } ] };
Then we just run it with pm2 start
.

pm2 is now running in “cluster” mode. Each of these processes is running on a different CPU on my machine, depending on how many cores I have. If we wanted to run a process for each core without knowing how many cores we have, we can just pass the max
parameter to the instances
value.
{ ... instances: "max", ... }
Let’s find out how many cores I’ve got in this machine.

8 CORES! Holy crap. I’m gonna install Subnautica on my Microsoft issued machine. Don’t tell them I said that.
The good thing about running processes on separate CPU’s is that if you have a process that runs amok and takes up 100% of the CPU, the others will still function. If you pass in more instances than you have cores, pm2 will double up processes on CPU’s as necessary.
You can do a WHOLE lot more with pm2, including monitoring and otherwise wrangling those pesky environment variables.
One other item of note: if for some reason you want pm2 to run your npm start
script, you can do that by running npm as the process and passing the -- start
. The space before the “start” is super important here.
pm2 start npm -- start
In Azure AppService, we include pm2 by default in the background. If you want to use pm2 in Azure, you don’t need to include it in your package.json
file. You can just add an ecosystem file and you’re good to go.

OK! Now that we’ve learned all about pm2, let’s talk about why you may not want to use it and it might indeed be ok to run directly against Node.
Running directly against Node in production
I had some questions on this so I reached out to Tierney Cyren who is part of the enormous orange circle of knowledge, especially when it comes to Node.
Tierney pointed out a few drawbacks to using Node based process managers like pm2.
The main reason is that you shouldn’t use Node to monitor Node. You don’t want to use the thing that you are monitoring to monitor that thing. It’s kind of like you asking my teenage son to supervise himself on a Friday night: Will that end badly? It might, and it might not. But you’re about to find out the hard way.
Tierney recommends that you not have a Node process manager running your application at all. Instead, have something at a higher level which watches multiple separate instances of your application. For example, an ideal setup would be if you had a Kubernetes cluster with your app running on separate containers. Kubernetes can then monitor those containers and if any of them go down, it can bring them back and report on their health.
In this case, you can run directly against Node because you are monitoring at a higher level.
As it turns out, Azure is already doing this. If we don’t push a pm2 ecosystem file to Azure, it will start the application with our package.json
file start script and we can run directly against Node.
"scripts": { "start": "node index.js" }
In this case, we are running directly against Node and it’s OK. If the application were to crash, you’ll notice that it comes back. That’s because in Azure, your app runs in a container. Azure is orchestrating the container in which your app is running and knows when it faceplants.

But you still only have one instance here. It takes the container a second to come back online after it crashes meaning that there could be a few seconds of downtime for your users.
Ideally, you would want more than one container running. The solution to this would be to deploy multiple instances of your application to multiple Azure AppService sites and then use Azure Front Door to load balance the apps behind a single IP address. Front Door will know when a container is down and will route traffic to other healthy instances of your application.
Azure Front Door Service | Microsoft Azure
Deliver, protect and track the performance of your globally distributed microservice applications with Azure Front Door…azure.microsoft.com
systemd
Another suggestion that Tierney had is to run Node with systemd
. I don’t understand too much (or anything at all) about systemd
and I’ve already messed this phrasing up once already, so I’ll let Tierney say it in his own words…
A Node.js alkalmazás futtatása a Systemd-vel - 1. rész
Megírta a következő nagyszerű alkalmazást a Node-ban, és készen áll arra, hogy felszabadítsa azt a világon. Ami azt jelenti, hogy… nodesource.com
Node.js munkásszálak
Tierney also wants you to know that Worker Threads are coming in Node. This will allow you to start your app on multiple “workers” (threads) thusly negating the need for something like pm2. Maybe. I don’t know. I didn’t really read the article.
Node.js v11.14.0 Documentation
The worker_threads module enables the use of threads that execute JavaScript in parallel. To access it: const worker =…nodejs.org
Be an Adult
Tierney’s last suggestion was to just handle the error and write some tests like an adult. But who has time for that?
The tiny circle abides
Now you know most of what is in the tiny blue circle. The rest is just useless facts about emo bands and beer.
For more information on pm2, Node and Azure, check out the following resources…
- //pm2.keymetrics.io/
- Node.js deployment on VS Code
- Deploy a simple Node site to Azure