This is the second day of my participation in Gwen Challenge
Pm2 is mentioned in a post about the background startup process of multiple postures. It is like a big butler, managing and coordinating multiple micro services efficiently. It’s amazing.
This article will move from simple use to microservice management.
So let’s try a Web service to get familiar with it. Then, around a very simple micro service platform, using PM2 to manage, so as to get familiar with and even master the essence of micro service management operation and maintenance! Good book recommendations at the end of the article!
Installation and use
Global installation
npm install -g pm2
View the application process
pm2 ls
Copy the code
No services are currently started by the PM2 manager, so an empty list is shown above.
First simple Web application effect
The web homepage is displayed on the left, and the nodeJS startup terminal is displayed on the right
The application code shown above can be copied and saved as:simpleweb.js
Run the startup command directly:node simpleweb.js
const pid = require('process').pid
const server = require('http').createServer((req,res) = >{
console.log(new Date() + ' - visiting app')
res.write("Levin - PM2 DEMO - ProcessId: "+pid)
res.end()
})
server.listen(8000.() = >{console.log('listening at 8000, pid:',pid)})
Copy the code
This code uses the NodeJS built-in HTTP module to create a server that listens on port 8000. Open a browser and see the process number.
And then it’s all pM2
To stop the process, run the pm2 start simpleweb.js command
View application processes and logs
Once the application is in pM2 management, we can use the following command
pm2 ls # check the process
pm2 logs simpleweb Pm2 logs is the first column returned by pm2 ls
pm2 monit # Monitor Displays logs of the current application
Copy the code
The effect is as follows: See simpleWeb, pM2 manages it for us.
Pm2 start simpleWeb. js –watch
— watch is added, which listens to the default current working directory.
Try modifying the file, such as moving the file in the middle terminal. Pm2 detects the change and restarts the Web application. A new process ID is printed on the web page of the browser on the left.
Pm2 ensures application process residency
You can try the kill -9 command to kill the process (along with the process ID displayed in the browser). After refreshing the Web page, the new process ID is printed. At this time, PM2 found that the program hung, automatic recovery.
Here’s a quick look at how PM2 works
After the pm2 command is executed, a new Daemon” pm2 v4.5.6: God Daemon” is added to the system.
It maintains some process information in the.pm2 directory under the current user’s home directory.
When we killed the process, all services used by PM2 were stopped. Restart the Pm2 daemon only after it is started.
Other commands can be viewed using pm2 -h.
To clean up the application, use pM2 delete SimpleWeb.
Now enter several service management scenarios, a little more complex, with a little patience after watching it can learn a micro service and master its operation and maintenance management.
Manage a mini micro service platform
Just a quick word about microservices
If you think of the human body as a microservice platform, the eye is a dedicated microservice that accesses image data, the brain is a microservice that performs data calculations, and some of them come in pairs (bithermal instances).
Product display micro-service platform
The image above shows two microservices
- LevinUIApp Front Desk service: Used to display product inventory data.
- BackendApp back-end product service: Provides product inventory data to the front service but has two worker child processes.
Start the UI service
Pm2 start uI-app /app.js --name uiappCopy the code
Start backend processes
The backend service starts two worker threads (-i) :
The process name is Levinbapp and two worker threads are started to use more CPU to improve efficiency. pm2 start backend-app/app.js --name levinbapp -i 2Copy the code
The result is that there are now two applications.
Here, more workers can be easily expanded horizontally through -i. To play more of the service, readers can try it after reading it.
See the effect and micro service log:
# Thunder committee demo code pM2 MonitCopy the code
Run the code above and open both browser pages at the same time.
Refresh the front end application (leftmost window), call the back end interface (middle window), and the Monit console switches services to view the logs.
If the back-end interface is refreshed, the Monit console prints logs in real time.
Use the following command to kill the middle backend service, refresh the leftmost UIApp application, and the middle backend service window in one go. The display service is offline.
And in the right monit window, it is convenient to switch the service log in real time, and view the service status, which is very good.
pm2 stop levinbapp
Copy the code
Simple to use, pM2 Butler override supports application logging, start/stop service recovery, and more.
Then the following configuration management, let us more simple professional management micro-service platform.
Configure management to start/stop service groups
Use pm2 ecosystem to generate a file.config.js file like the one below. Readers can create a foreground app.js and a background app.js without using the blogger’s code.
module.exports = {
apps : [{
name: 'uiapp'.script: './ui-app/app.js'.watch: ['./ui-app'] {},name: 'levinbapp'.script: './backend-app/app.js'.watch: ['./backend-app']}],deploy : {// Use SSH to attach microservices to the production server!
production : {
user : 'root'.host : 'alicloudtx'.// Ali cloud host
ref : 'origin/master'.repo : 'GIT_REPOSITORY'.path : '/demo/levin-demo-msa'.'pre-deploy-local': ' '.'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production'.'pre-setup': ' '}}};Copy the code
To recap: The Apps property configudes service groups that require PM2 management. The Deploy attribute then enables users to directly deploy multiple service clusters to Aliyun using PM2.
Then use: pm2 start file.config.js
Deploy to the cloud, which is not shown here. You can deploy to any cloud platform if SSH is configured.
conclusion
Microservice platform is always characterized by multiple services and distributed operation of multiple machines, expanded resources and computing power, and improved management complexity.
While it may be easy for two services to log on to different machines, the problem becomes apparent when the number of services reaches hundreds or thousands.
So, we need tools like PM2 that provide the following convenience:
Convenience in development and operation and maintenance
- Seamless access to service management
Almost a miracle for NodeJS applications, PM2 natively supports application management and provides command management to view user applications.
Taking the micro-service platform developed by Springboot as an example, students who develop applications need to introduce SpringCloud and other components to discover services and register in the registry. I have also used the spring family bucket to make micro service platform, and then simplify also have to customize a general SpringBoot Starter, the concept is similar!
- Unified management of log workbench
Especially in microservice environments, multiple services, using PM2 Monit, can easily switch microservice logs in a Monit workbench. Large platforms need to do log search, and it is not practical to switch between hundreds of services in the PM2 Monit window, which is what PM2 lacks!
However, PM2 also has an online version of Keymetics as a monitoring and management platform for professional micro services (for a fee).
- Easier application of elastic expansion
When the background service is started above, a -i parameter is added, and the specified number can start the multi-worker service. While NodeJS is still single-process and multi-threaded, this parameterized instance extension is instructive!
- Encapsulation of service start/restore operations, atomicity
We can use pm2 start/stop appname instead of developing into multiple application directories and manually typing Node app.js. Also, pM2 will live in the application to ensure that the application does not drop, so this design is also worth considering.
For example, the following command:
# remember to add -i 2 otherwise start a worker single thread processing UI request. pm2 start levinbapp -i 2Copy the code
Overall orchestration and deployment configuration management
One configuration manages multiple services and instances of the entire microservice, and can be quickly deployed to the cloud!
Speaking of which, readers will not feel that there are some similar places with K8S (Kubernetes), seamless, configuration orchestration, elastic scaling and so on. Pm2 is almost lightweight in NodeJS applications and does not require as much configuration as K8S.
This paper mainly shows the management operation and maintenance of micro-service application through the use of PM2, pointing out a better direction, so as to guide readers to grasp and optimize the operation and maintenance and management of micro-service platform towards these perspectives!
Take a look at the microservices around you and think about better and more convenient location-based logging, service deployment, start/stop/lateral scaling, etc.?
As for the books
If you want to do microservices, be sure to finish reading this book, Microservices Design.
This is very helpful for the implementation of architecture and operation of micro services, is a classic book in the field of micro services, read more than two times!
Also see the Microservice Platform site at the link for examples.
As an aside, those who are familiar with NodeJS can take a look at its source code, such as service resident/hot load update/seamless access management. These excellent implementations are worth exploring, and can lead to excellent operation and maintenance monitoring platform development.
Code and reference links
Of the above service code: blog.csdn.net/geeklevin/a… Pm2 website: https://pm2.keymetrics.io/docs/usage/quick-start/ books: book.douban.com/subject/267… Micro service web site: https://microservices.io/patterns/microservices.html