This is the fourth day of my participation in the August Text Challenge.More challenges in August

This article is a record of testing updates to the ecosystem configuration file at run time.

The source code

The service side

// /const log = require('.. /lib/log.js'); const http = require('http'); const express = require('express'); var cluster = require('cluster'); var os = require('os'); // const g_port = 4000; const g_port = process.env["SERVER_PORT"]; const g_name = process.env["NODE_ENV"]; function test1() { app = express(); const server = http.createServer(app); Server.listen (g_port, () => {console.log(' 111Express is listening on ${g_port} '); }); Get ('/', function (req, res) {console.log('111 got request from... ', req.url); str = 'Hello World! now is: <br>'; myDate = new Date(); myDate.toLocaleString(); str += myDate; res.send(str); }); process.on('SIGINT', () => { console.log('111 got sigint... \n'); const cleanUp = () => { }; Close (() => {// Stop after 10 secs setTimeout(() => {cleanUp(); process.exit(); }, 2000); }); // Force close server after 15 secs setTimeout((e) => { console.log('Forcing server close !!! ', e); cleanUp(); process.exit(1); }, 3000); }); } var g_cnt = 0; // Is it necessary to create the worker? Function test2() {var numCPUs = 2; //os.cpus().length; if (cluster.isMaster) { // Master: // Let's fork as many workers as you have CPU cores for (var i = 0; i < numCPUs; ++i) { cluster.fork(); } } else { // Worker: // Let's spawn a HTTP server // (Workers can share any TCP connection. // In this case its a HTTP server) console.log(`111 httpserver is listening on ${g_port}`); http.createServer(function(req, res) { res.writeHead(200); console.log('got request from ... ', req.url); str = 'here is my voice: Hello World! now is: \n'; myDate = new Date(); myDate.toLocaleString(); str += myDate; g_cnt++; var cnt = ' cnt: ' + g_cnt.toString() + '\n'; str += cnt; res.end(str); }).listen(g_port); Function test3() {console.log(' httpServer [${g_name}] is listening on ${g_port} '); function test3() {console.log(' httpServer [${g_name}] is listening on ${g_port} '); http.createServer(function(req, res) { res.writeHead(200); console.log('111 got request from ... ', req.url); str = '111 here is my voice: Hello World! now is: \n'; myDate = new Date(); myDate.toLocaleString(); str += myDate; g_cnt++; var cnt = ' cnt: ' + g_cnt.toString() + '\n'; str += cnt; res.end(str); }).listen(g_port); Function main() {//test1(); //test2(); test3(); } main();Copy the code

The client

Err */ var request = require('request'); err */ var request = require('request'); const log = require('.. /lib/log.js'); const g_port = 4000; function httpGet(url, requestData) { var head = { url: url, method: "GET", json: true, headers: { "content-type": "application/json", 'User-Agent': 'git-oschina-hook', 'X-Gitee-Token': 'webhook password', 'X-Gitee-Event': 'Push Hook' }, body: requestData // body: JSON.stringify(requestData) }; request(head, function fn(error, response, body) { if (! Error && response. StatusCode = = 200) {the print (" = = = = = = = = = = = = = GET content: \ n ', body) / / success} else {the print (" err "); }}); } function getHttp() {var url = 'http://127.0.0.1:'+ g_port; var msg = new Object(); msg['devid'] = '123456798'; msg['station'] = '01'; msg['stateCode']=='501'; //log.print('will get the http.'); httpGet(url, msg); } var g_loopId = null; function startLoop() { g_loopId = setInterval(loopFunc, 500); } function stopLoop() { clearInterval(g_loopId); } function loopFunc() { getHttp(); } function main() { log.print('start looping... '); startLoop(); } main();Copy the code

Configuration file file.config.js

Module. Exports = {/ / APP is an array, you can have multiple / / parameter reference: https://pm2.io/doc/en/runtime/reference/ecosystem-file/ apps: [{name: 'app', script: 'server.js', args: 'null', instances: 1, //exec_mode: "cluster", // If not specified, default to fork autorestart: false, min_uptime: "60s", max_restarts: 3, watch: false, //error_file: "./logs/app-err.log", //out_file: "./logs/app-out.log", log: "./logs/app.log", //log_date_format: "Yyyy-mm-dd HH: MM Z", // pm2 log Add date max_memory_restart: '1G', //listen_timeout: 3000, kill_timeout: 3000, // wait_ready: true, env: { NODE_ENV: 'development', SERVER_PORT: "4000", }, env_production: { NODE_ENV: 'production1', SERVER_PORT: "4000", } } ] };Copy the code

use

Start the server:

pm2 start
Copy the code

Use the client connection and watch the output log:

node client.js
Copy the code

The command used in the test:

Pm2 reload file.config. js pm2 reload <ID>Copy the code

The test item

The following are different tests, most of which only write the conclusion.

Update field values in env

Is feasible.

If env_production is modified then:

pm2 reload ecosystem.config.js --env production
Copy the code

Add –update-env to the end of the command.

Update fields that are not ENV

Pm2 reload, no effect, no success.

New instance

Originally, there was only one app, plus one app, but to change the name and port number, the other can be the same. Using pm2 Reload, you can see that a new instance is running.

Reduce the instances

I had 2 apps, so I’m going to subtract one. Pm2 reload, no effect, no success.

Instance name

App name changed, port not changed: a new instance will be started, but the message that the port is occupied (because it is not changed). Conclusion: As long as the name is different, PM2 is considered a new instance to start. [PM2][WARN] Applications APP1 not running, starting… And so on. So, while MP2 is running, there is a way to “update” the instance by stopping the old instance (otherwise it will prompt you to occupy the port number), making a copy of the configuration parameters of the old instance, and changing the instance name to the new one. Reload the configuration file. For a better approach, see the following example.

Delete the instance and start again

Pm2 del 1 (instance ID: 1) pm2 reload server.config.jsCopy the code

In this case, the instance ID of the server is 2. 1 does not exist, but the service name is the same.

Delete the instance, modify the instance, and start again

You can modify the PM2 configuration file, which takes effect.

conclusion

1. Pm2 can add a new instance on the original basis, and directly reload server.config. js to start the new instance. 2. Pm2 DEL and pm2 Reload can change everything about an instance (note: this is just theory, I focus on log, port, etc.). 3. If you want to recover everything, the ultimate solution is to use pM2 kill.