Chapter 11: Application Hosting — WordPress, Flask and Express
11.3 Express application with pm2 + Nginx
Express runs inside Node.js and handles HTTP requests. PM2 can supervise that Node process. The private app listener and Nginx frontend follow a familiar hosting pattern. Node and PM2 have different roles.
Express हे Node.js मध्ये चालतं आणि HTTP requests हाताळतं. PM2 त्या Node process वर देखरेख करू शकतो. Private app listener आणि Nginx frontend यांची कामं वेगळी असतात.
Express Node.js में चलता है और HTTP requests संभालता है. PM2 उस Node process की देखरेख कर सकता है. Private app listener और Nginx frontend के काम अलग हैं.
Why pm2?
A Node process started interactively has no deployment supervision by that command alone. PM2 can run a named service independently and restart it according to its configured lifecycle policy.
Terminal मध्ये Node चालवल्याने त्यावर आपोआप service देखरेख सुरू होत नाही. योग्य policy दिल्यास PM2 त्या नावाच्या service ला चालवू शकतो आणि गरज पडल्यास पुन्हा सुरू करू शकतो.
Terminal में Node चलाने से service की निगरानी अपने आप शुरू नहीं होती. सही policy के साथ PM2 उस नाम की service चला सकता है और ज़रूरत पर फिर शुरू कर सकता है.
Plan the app process’s lifetime, logging and recovery independently from an interactive SSH session. PM2 can provide that supervision for the intended account and app name. Verify a representative response in addition to its process status.
Step 1 — Install Node.js, pm2 and Nginx
Choose a supported Node LTS release compatible with the chosen packages and approved installer for the host. Check which Node binary the intended service uses. The isolated local lab installs pinned versions of Express and PM2 in its working directory and uses no global npm installation.
Step 2 — Create the Express app
Build the candidate in an isolated release directory with the intended runtime and reviewed dependencies. Validate incoming request data and choose safe text rendering for any browser content. The local lab below contains a complete Express lookup route and checks successful and deliberate invalid requests.
Step 3 — pm2 ecosystem file (cluster mode)
This example identifies one app, its directory, and its starting process model. Use it only for the approved deployment identity and a release whose server reads the intended port. Cluster mode is a separate capacity choice. Test it under representative load and keep durable state outside worker memory.
module.exports = {
apps: [{
name: "dairy-api",
script: "./server.cjs",
cwd: "/opt/dairy-express/current",
instances: 1,
exec_mode: "fork",
env: { NODE_ENV: "production", PORT: "18001" }
}]
};Useful pm2 commands
| Command | Purpose |
|---|---|
pm2 list / pm2 status |
Show processes |
pm2 logs dairy-api |
Stream logs (--lines 100) |
pm2 monit |
Live CPU/memory dashboard |
pm2 restart dairy-api |
Restart the named app. A single instance can have a gap. |
pm2 reload dairy-api |
Attempt a cluster reload. PM2 can fall back to restart. |
pm2 stop dairy-api / pm2 delete dairy-api |
Stop / remove from list |
pm2 save |
Save the current account’s intended process list. Boot startup requires separate integration. |
pm2 logs dairy-api --lines 100 --nostream |
Read recent logs for the intended app without following the stream. |
Step 4 — Nginx reverse proxy
This Nginx configuration excerpt illustrates one loopback frontend and one private app, assuming the example ports are available. It sets the headers for a simple single trusted proxy case. A production deployment needs its own approved named listener, TLS and proxy policy. Do not change the default site or unverified host security policy.
server {
listen 127.0.0.1:18081;
server_name pickup.dairy.example.test;
location / {
proxy_pass http://127.0.0.1:18001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
}
}Check that the intended private listener responds with a known app marker. Then check the named frontend path for the expected JSON status and content. A few refreshes with different process IDs do not prove distribution or correct application behavior.
Step 5 — Deploying updates
Build a candidate under the intended Node runtime from the approved source and lockfile. Run npm ci in that candidate directory as appropriate. Choose runtime dependencies after considering the build step. Switch only the named app under the approved procedure, and verify the private and public paths before retiring the previous release.
Ravindra Bagale's Tip
PM2 startup integration and its saved process list are separate parts of boot recovery. Verify both under the intended account and Node runtime. A release change also needs a tested availability and rollback plan.
Ravindra Bagale's Tip – मराठी
PM2 ची startup व्यवस्था आणि save केलेली process list या boot recovery च्या वेगळ्या गोष्टी आहेत. योग्य खाते आणि Node runtime वापरून दोन्ही तपासा. Release बदलासाठी availability आणि rollback चा सराव करा.
Ravindra Bagale's Tip – हिंदी
PM2 की startup व्यवस्था और saved process list, boot recovery के अलग हिस्से हैं. सही खाते और Node runtime के लिए दोनों जाँचो. Release बदलने से पहले availability और rollback की योजना जाँचो.
Lab
Run the isolated local Express and PM2 fixture below. Compare one real lookup, multiple deliberate client errors, and a revised release marker after a named restart. The lab uses its own PM2 instance and performs no reboot.
Serve a pickup lookup that keeps working after you log out
Mauli Dairy’s rider selects a collection point on a web form. The page asks a server for the next departure time and displays it without requiring someone to change an HTML file. The first version returns the correct time during a developer’s test. People will eventually use it from their phones, so the dairy also needs to know which app version is serving the request and how to restart or recover it when the person who wrote it is away.
Node.js runs JavaScript outside a browser. Express is a web framework that runs inside Node and helps the program parse requests and match them to handlers. PM2 is a process manager that can run the Node program and supervise and log it according to configuration. Nginx can accept a site’s public connections, serve selected static files and forward application requests to the private Node endpoint. Node and Express themselves handle HTTP. PM2 does not become the HTTP server or take the place of a Python WSGI interface.
We will use three observable results. A request for the existing east collection point returns its departure time and a harmless release marker. A malformed request obtains a controlled client error. Restarting the named service with a different release marker changes what clients observe, without starting a daemon under someone else’s PM2 account. Draw these expectations before copying a command. A process list entry is a start, but the test still needs to prove what the application tells the rider.
There are several ways to host Node applications. This lesson uses a Linux-style reverse-proxy and process-manager design and a separate local exercise. Managed platforms or containers can already perform supervision, so they may not need PM2. Choose responsibilities once for a deployment. Two supervisors independently attempting to own the same application can disagree about lifecycle or restart behavior if you do not design their relationship deliberately.
Trace a browser request through Node and Express
A public web request begins with the exact advertised name and path. The browser resolves the name and connects to the intended listener. When using HTTPS, it verifies the server identity before sending an ordinary HTTP request across that connection. The public frontend can identify the configured site and forward a specific application path, such as /schedule-lookup, to the Node process. The browser does not see the private address on which Node listens.
Express consults its ordered configuration of middleware and routes. Middleware is code that can inspect or transform a request, stop it with a response, or hand it to the next step. In our app a JSON parser runs before the route. JSON is a structured text format. It can express a value such as an object holding the collection point. The parser reads the body and attempts to turn it into usable JavaScript data. The application still needs to decide whether the parsed shape and values are allowed.
A route pairs a method such as GET or POST with a path. GET can retrieve a simple readiness response. The exercise’s POST example accepts a structured lookup request and does not write an actual order. After parsing, it checks that the supplied point is a string. Then it decides whether the point is recognized and returns the planned body. Type validation is separate from syntax: well-formed JSON can contain a number even though the application expects a word naming a pickup point.
Try to say where each status comes from. Invalid JSON is rejected before the lookup handler can interpret the request. An existing handler can return 400 for the wrong input shape. A supported request for an unknown known category of resource can return 404 to indicate no matching collection point. A valid match returns 200 and the expected value. If Nginx cannot contact the intended backend at all, the app does not get to perform any of those decisions.
The handler does not need to send a page for every request. The JSON response carries structured fields that a browser page or another service can read. For the same deployment, Nginx could serve an approved CSS or JavaScript file from its release path while forwarding the API request separately. Keep a status and a meaningful response marker for each. A styled page can still appear when a JavaScript fetch of the schedule fails.
Prepare a supported Node runtime and repeatable project
Start with the officially supported Node release lines and the required application package versions. Production work should select an active or maintenance LTS line that the dependencies support. LTS means the release line receives long-term support under the upstream lifecycle. A package might run on Node 18 according to its minimum runtime, while that Node line is no longer appropriate for a new public deployment. Verify both the upstream lifecycle and your application requirements.
Record which executable the service actually uses. Running node --version in your login shell only identifies that shell’s selected Node. A PM2 startup integration or system service can start under a different environment after reboot. This matters when new syntax, built-in modules or package binaries expect a different runtime. Choose an explicit and supported setup for the service and record how it is put on the intended path. Avoid piping a third-party install script directly into a privileged shell just because an older recipe did so.
Keep the application’s package manifest and reviewed lockfile under version control. The manifest identifies direct dependencies and scripts. The lockfile records the resolved dependency set. In a fresh candidate checkout, npm ci installs from the committed lockfile and expects it to agree with the manifest. It removes an existing node_modules in the directory where it operates, so use a candidate release path. Requirements such as build tooling may depend on packages classified as development dependencies. Build first according to your project and only omit packages that are not needed for the runtime artifact.
The local lab installs pinned direct versions of Express and PM2 in a disposable directory. Its install records a lockfile for that run. In a real release workflow, take the further step of reusing the reviewed dependency tree and candidate artifact across environments. Keep secrets out of package.json, source and arguments, and do not generate or restore arbitrary project files that your approved release does not need.
Write a small release inventory before testing. Include the Node version, package lock identifier, service identity, working directory, the startup entry point, environment settings and any persistent data dependencies. Changing a healthy service requires a reversible plan that accounts for all those choices. A checked-out old JavaScript file can still run with incompatible new packages or a changed database contract. The release is the collection of compatible pieces that serves the expected behavior.
Make the behavior visible without exposing private information
Give the app a readiness route with a scope you can name in a sentence. In this lab it confirms the new process initialized its listener and has the expected release marker. An actual readiness check might also need to reflect a critical dependency when its absence would make the instance unsuitable for traffic. Think about how the load-balancing layer uses readiness and how frequently it checks. A successful lightweight route and a completed pickup workflow can have very different meanings.
Validate the shape and size of input. The lab sets a small body limit suitable for short lookup data. The frontend can also have a limit. If a request is rejected by Nginx before reaching Node, the downstream app will not emit its usual payload for that error. If Express parses the body, distinguish syntax failure from a structurally valid value with the wrong type. When debugging, preserve the sample input class and response category without including customer data in logs.
Express 5 handles certain asynchronous errors through its error flow. A rejected promise returned by a route or middleware can reach an error handler. A callback started outside that promise needs its own deliberate error handling. Unexpected errors should have safe public responses and useful protected diagnostics. Avoid sending stack traces, credentials, or full customer request content to browsers. Treat the lab’s small error handler as an illustration of controlled HTTP outcomes.
The event loop coordinates work as Node waits for things such as network or file operations. A route that performs long CPU-bound synchronous work in the same process can delay other request handling. PM2 process counts and worker modes can change capacity, but an extra process also uses more memory and may open more connections to a shared database. A sound design measures relevant operations and considers how the application behaves at its actual bottleneck before adjusting counts.
Keep content in a durable location when the workflow involves persistent state. The lab’s schedule is a constant so it cannot lose a customer record. A production booking application needs an approved durable store. Several processes do not share ordinary JavaScript objects in memory, so writing a booking or session to one worker’s global array will not automatically make it available to another. A load balancer and a supervisor cannot replicate business records for you.
Manage an application by name and define expected lifecycle
PM2 can start a script, use a selected working directory and save its process configuration. A named entry gives you a way to inspect or change just the intended service. Decide which operating-system account owns that process list. Using a different user or storage location can show a different list even on the same machine. Knowing the account and store is part of understanding what any cleanup or restart command controls.
Configuration can specify a script, working directory, instance count, environment selection and process mode. Fork mode commonly runs a standalone app process for one configured instance. Cluster mode uses Node’s cluster approach to run multiple workers and share service connections according to the runtime and mode. Changing instance count does not make memory state shared across workers, and one browser refresh sequence is an unreliable capacity or distribution test.
A restart and a reload are not an automatic promise of continuous service. A restart replaces selected process instances, and simple single-process services may experience a gap. PM2’s reload feature aims for overlap in supported clustered configurations and may fall back to restart in some conditions. Readiness, signal handling, capacity, long connections and compatibility of persistent state all matter. Test the expected behavior for your exact production setup instead of repeating a generic zero-downtime promise.
An app can handle a shutdown signal by stopping acceptance of new work and closing existing resources according to its design. PM2 can send a signal and wait for some configured time before forcing termination. The service should decide which operations can complete, how to handle slow requests and what a client should do if a connection was interrupted. The local lab uses a shutdown handler only for its short practice connections. It does not demonstrate the behavior of long in-flight production jobs.
Startup after a machine restart has two parts. Install or configure the approved service-manager integration for the intended account and runtime. Save the intended process list when the design uses PM2’s save and restore workflow. A command that reports processes saved does not by itself install a boot service. Conversely, a startup integration can exist while the saved list names an old artifact. Inspect and test the exact startup configuration in an approved environment. The practice lab changes no boot settings and performs no reboot.
Connect the public service to the intended Node listener
Decide where the public TLS connection ends. On a direct small server, Nginx can be the public HTTPS endpoint and the site’s certificate is configured there. In a load-balanced or CDN-backed deployment, the public connection can end earlier. The private Node listener might receive HTTP over a deliberate local path. Make sure the configuration and access rules reflect that design; avoid binding the demo to a public interface just to work around a failed proxy.
Use the actual listener address and port selected for that app. A process can be marked online without being reachable at the destination Nginx currently uses. A useful test first asks the app’s own private endpoint for a real schedule. The public test then uses the exact external hostname and path. If the private test passes and the named path fails, compare the configured upstream mapping, network and TLS path before replacing app dependencies.
The frontend and application must agree on paths and request methods. If the browser sends POST /api/schedule-lookup and Node expects POST /schedule-lookup, decide whether the frontend removes the prefix or the application registers that prefix. A request forwarded with the original prefix might produce a correct 404 from your app, which is evidence that something reached it. Check the frontend’s selected location and the actual request path reported at the backend. Examine the response body and any redirect before assuming a DNS fault.
Determine whether Express needs the original scheme, hostname or client address. Express’s trust proxy setting changes how certain API values are interpreted. Choose the proxy addresses or hop conditions based on the real deployment, and configure trusted proxies to set or clear incoming forwarded values as needed. Arbitrary forwarded headers from a direct client do not provide trusted identity. If the public path has an edge and Nginx, write which layer is authoritative for each value. Avoid changing settings for every app simply because one route generates a wrong link.
Limit Nginx’s static configuration to the known public folder of the intended release. Build assets from the same candidate if the page expects a particular API. Watch for differences in the proxy’s body limit and Express’s parser limit. When a request sends too much data, check which component returned a 413 and whether it matches the correct policy. Sending an arbitrarily large file to test a production limit is unnecessary. Use a controlled small sample close to the intended limit in a practice environment.
Rehearse a loopback Express service with its own PM2 instance
Use a local shell with Node, npm, Python 3 and curl. The verified classroom combination was Node 24.22.3, npm 11.16.0, Express 5.3.0 and PM2 7.1.2. These are example versions for the lab. Check current support and dependency guidance before choosing a public deployment. npm needs access to the approved package index for installation. This exercise uses a temporary project, npm cache and PM2 home, so it does not install a global process manager.
Predict the request results before running the code. The east lookup has the expected departure and release marker. A numeric pickup field produces a controlled 400. A syntactically invalid JSON request also produces 400, with a different response body. A well-formed lookup for west gets 404. A request larger than the app’s small approved limit gets 413. After the named restart with a revised environment setting, the same east lookup returns the original departure time and the new release marker.
The Node listener asks the local operating system for a free port and binds only to loopback. It writes the selected port and process identity into a temporary readiness file. The harness waits for the file and checks that the listener actually serves the expected release. The distinction is important. A file could be leftover evidence from the previous process, or the port might no longer be active. During a restart, require a new process marker and successful response rather than relying on the presence of a stale file.
(
set -eu
umask 077
lab=$(mktemp -d "${TMPDIR:-/tmp}/dairy-express.XXXXXX")
export PM2_HOME="$lab/pm2-home"
pm2="$lab/node_modules/.bin/pm2"
cleanup() {
if [ -x "$pm2" ] && [ -S "$PM2_HOME/rpc.sock" ]; then
"$pm2" kill >/dev/null
fi
rm -rf -- "$lab"
}
trap cleanup EXIT
cd "$lab"
printf '%s\n' '{"name":"dairy-classroom","private":true}' > package.json
npm --cache "$lab/npm-cache" install --save-exact \
--ignore-scripts --no-audit --no-fund express@5.3.0 pm2@7.1.2
cat > server.cjs <<'JS'
const express = require("express");
const fs = require("node:fs");
const app = express();
const release = process.env.DAIRY_LAB_RELEASE;
app.use(express.json({ limit: "8kb" }));
app.get("/ready", (req, res) => {
res.json({ release });
});
app.post("/schedule-lookup", (req, res) => {
const point = req.body?.point;
if (typeof point !== "string") {
return res.status(400).json({ error: "point must be text" });
}
if (point !== "east") {
return res.status(404).json({ error: "unknown pickup point" });
}
return res.json({ point, departure: "16:00", release });
});
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
if (err.type === "entity.parse.failed") {
return res.status(400).json({ error: "invalid JSON" });
}
if (err.type === "entity.too.large") {
return res.status(413).json({ error: "request body too large" });
}
return res.status(500).json({ error: "server error" });
});
const server = app.listen(0, "127.0.0.1", () => {
const state = { pid: process.pid, port: server.address().port, release };
fs.writeFileSync("ready.tmp", JSON.stringify(state));
fs.renameSync("ready.tmp", "ready.json");
});
function stop() {
server.close(() => process.exit(0));
}
process.on("SIGINT", stop);
process.on("SIGTERM", stop);
JS
DAIRY_LAB_RELEASE=v1 "$pm2" start server.cjs --name dairy-classroom --cwd "$lab"
python3 - "$pm2" <<'PY'
import json
import os
from pathlib import Path
import subprocess
import sys
import time
def request(state, path, data=None):
args = ["curl", "-q", "-sS", "--noproxy", "*", "--max-time", "2",
"--write-out", "\n%{http_code}"]
if data is not None:
args += ["--header", "Content-Type: application/json", "--data", data]
args.append("http://127.0.0.1:" + str(state["port"]) + path)
result = subprocess.run(args, capture_output=True, check=True, text=True, timeout=3)
body, status = result.stdout.rsplit("\n", 1)
return int(status), json.loads(body)
def ready_for(release, previous=None):
until = time.monotonic() + 12
while time.monotonic() < until:
try:
state = json.loads(Path("ready.json").read_text())
if state["release"] == release and state["pid"] != previous:
if request(state, "/ready") == (200, {"release": release}):
return state
except (FileNotFoundError, subprocess.CalledProcessError,
subprocess.TimeoutExpired, json.JSONDecodeError):
pass
time.sleep(0.1)
raise RuntimeError("Expected release did not become ready")
first = ready_for("v1")
assert request(first, "/schedule-lookup", '{"point":"east"}') == (
200, {"point": "east", "departure": "16:00", "release": "v1"}
)
assert request(first, "/schedule-lookup", '{"point":42}') == (
400, {"error": "point must be text"}
)
assert request(first, "/schedule-lookup", '{"point":') == (
400, {"error": "invalid JSON"}
)
assert request(first, "/schedule-lookup", '{"point":"west"}') == (
404, {"error": "unknown pickup point"}
)
assert request(first, "/schedule-lookup", json.dumps({"point": "x" * 8200})) == (
413, {"error": "request body too large"}
)
print("Version one: expected schedule, two 400s, an unknown-point 404 and a size-limit 413.")
env = os.environ.copy()
env["DAIRY_LAB_RELEASE"] = "v2"
subprocess.run([sys.argv[1], "restart", "dairy-classroom", "--update-env"],
env=env, check=True, capture_output=True, timeout=20)
second = ready_for("v2", previous=first["pid"])
assert request(second, "/schedule-lookup", '{"point":"east"}') == (
200, {"point": "east", "departure": "16:00", "release": "v2"}
)
print("Named restart reached a new process and the intended v2 marker.")
PY
"$pm2" delete dairy-classroom
"$pm2" kill
test ! -S "$PM2_HOME/rpc.sock"
printf '%s\n' 'The dedicated PM2 instance and its control socket closed.'
)
Read the first success line and connect it with the route’s logic. The tests compare the contents and status codes, not the order in which the process manager prints its status lines. The deliberate invalid examples represent separate stages. Express’s body parser produces one error for invalid JSON and a later handler returns a different 400 for a correctly parsed but inappropriate field. The size limit prevents the larger body from being handled like an ordinary lookup. The west value reaches the route and is simply absent from the toy schedule.
In the next stage the harness asks PM2 to restart only the named app with a different non-secret environment value. The --update-env flag updates the process environment for this chosen operation. The new response demonstrates that the application read the expected revised value. We do not assume a successful process-management command alone changed application behavior. The exercise uses one process and makes no claim about the requests that would arrive during the transition.
At the end the shell deletes the practice app from the isolated process list, stops that dedicated PM2 daemon, verifies the RPC control socket is no longer present, and removes the temporary workspace. RPC means remote procedure call. Here the socket is local to the temporary process-control setup. Never reproduce the broad daemon stop against a shared PM2 process list. The script sets a unique PM2 home before it begins and cleans only that workspace.
If an expected outcome is missing, identify the step. A package-download failure precedes service testing. If the readiness file appears but the harness cannot obtain the marker, compare the app process and its loopback listener. If an input test fails, inspect the difference between transfer failure, returned status, and JSON response fields. Consider whether the method and Content-Type match the route. Save the small lesson output rather than an unredacted process environment or an entire log archive.
Test process status, application behavior and delivery as separate evidence
Imagine that version one’s app runs correctly on the candidate host and a new release changes only the successful lookup display. Stage the candidate in its own directory with the right runtime and reviewed package tree. Identify the exact supervisor account and app name before changing its startup configuration. Then request the named operation through the actual delivery path. Check the prior expected error response too, because a working happy path can hide accidental routing or validation changes.
Use an explicit procedure for service configuration and data changes. Choose how the process obtains its environment, who can change it, and at which step the new process sees the change. A setting put into a login shell does not necessarily affect the already-running managed process. Compare the intended process configuration and application marker. Keep private values out of diagnostics. Versioned config and environment delivery can make a more complete recovery plan than swapping a single JavaScript file.
Separate data safety from process life. If a release adds writes to a durable schedule or order store, test schema compatibility and define the return path before the switch. A restart can interrupt active operations. Decide how requests and background tasks drain, and keep business operations safe if a client retries. Rolling back the app should not discard new records unless the data owner explicitly chooses a recovery policy with an acceptable loss window.
When a supervisor needs startup after reboot, rehearse the service and rollback on an approved training VM or controlled staging environment. Verify the actual configured OS service under the expected account, its selected Node path, process list and public response. A reboot of an unrelated shared host would interrupt more than the exercise is meant to test. The evidence you need is that the intended process and app return under a specifically configured environment.
Investigate scope before triggering another restart. If a static asset comes from the wrong directory, inspect the frontend’s release path. If a private JSON request works and the public call gets 502, compare Nginx’s selected private port or socket and the matching permissions. If both reach the app and show the old marker, verify the managed process’s working directory, release and environment. These distinct symptoms do not all require rebuilding packages or changing the listener.
Connect an actual form to the intended JSON response
Imagine a frontend with a select field for the collection point and one text area for the departure time. When the rider chooses east, the browser sends a request to the same site. The request needs the correct method and path, plus a content type that says the value is JSON. The frontend then interprets the response status and checks the relevant fields. A program that tries to display a success message before checking the result can turn any error response into confusing output for the rider.
Sketch the frontend behavior for the cases used in the lab. Show the time only for a successful response with the planned schedule fields. Show a clear validation message for the wrong type and a useful missing-collection message for an unknown point. A body that arrives as malformed JSON may indicate an integration bug, so record a small non-sensitive example and reproduce it in the controlled environment. Keep the examples separate so someone can tell which branch of handling the browser and server each used.
If a user-provided value is ever displayed, render it as text using the browser’s appropriate safe text API or a framework’s normal escaping. Avoid building HTML fragments by concatenating raw request data. That matters when a response includes something an untrusted user wrote, such as a free-text note. The lab deliberately uses a fixed response and typed inputs. It has no need to accept arbitrary rich text. Treat content rendering and backend validation as complementary decisions rather than assuming one process manager option can address both.
Compare a supported page load with a direct request to the endpoint. The page may download its code from the correct Nginx path, then send its API call to the wrong route. Conversely, a direct local JSON response can succeed while the browser path fails because the frontend uses an unintended prefix. Use the browser network view to check the exact URL, method, content type and status when verifying the actual delivery. Use a controlled harmless marker to compare which release served each request.
For a deployment, decide which response data is intended for public clients. The readiness route can often return a small marker or a simple status. Keep detailed process diagnostics, host information and monitoring credentials in authorized internal logs. A public customer does not usually need the process ID of the worker that returned tomorrow’s departure time. Make diagnostic details a deliberate choice by audience and scope.
Work through a restart and an operating-system startup plan
A team member updates the script in their development terminal and sees it work there. They close that terminal and later ask why PM2 did not show the new release. Write down where the old service was started, which script it manages, and from what working directory. A managed process has its own lifetime and environment. Seeing an edited file in one checkout is not evidence that the actual Node process has loaded it. The service configuration and process metadata should point to the intended release artifact.
Now imagine the app rests under a dedicated service identity named dairy-app. The deployment account can stage a versioned artifact with its reviewed package lock. In the intended PM2 configuration, record the exact script location, working directory, required Node binary and service name. When PM2 gets a fresh process or acts on a restart, it must read those intended values. If you plan to start PM2 with the operating system, review the installed integration’s account and executable path before saving a process list for that user.
Test your startup plan in a separately approved environment. Start with a known service and predictable response marker. Simulate the relevant service-manager restart first if the goal is to verify the service definition. If machine startup itself is part of the approved test, use a dedicated practice host that can be interrupted. Observe which account restored the app and what it actually serves. If startup is defined but no process returns, compare the saved list and selected runtime before redefining the app under another account.
If the PM2 app appears twice after a setup, write down the selected store, daemon and account for each observation. Different instances can each maintain a process with the same human-readable name. Avoid deleting one because its name alone matches an old deployment note. Inspect its actual release, listener, dependency and owner. Stop or remove only the specific process covered by the authorized change. In the lesson, the fresh temporary instance gives us a process-control boundary we can identify precisely.
Compare two candidate update methods. A clean build in a new directory can use the approved lockfile and retain a complete previous release. Editing the live files and rebuilding dependencies there leaves little room to inspect the original state if something fails halfway. The first method still needs a deliberate process switch and data compatibility. The larger point is that your recovery plan should restore a known working combination. Capture what was switched, under what process owner, and which operation confirmed the result.
Compare normal lookup, malformed input and a real dependency failure
Use a service board with three example failures and one working control. The normal east lookup should return JSON with the known time. The malformed body should receive the app’s intended client error. The expected path with a simulated failure in a production data dependency should fail in a controlled way appropriate to your design. In another row, an intentionally unknown pickup should remain an application-level 404. These observations make your logs and route tests interpretable. They also avoid treating every error status as evidence of a failed deployment.
Follow the lookup across each log boundary only as far as needed. Nginx can show the external request status and whether it talked to an upstream. PM2 can show that a Node process started, restarted or emitted script output. The application can show a controlled validation decision or a dependency failure. Use a shared timing window or an approved request reference to connect those observations. Record only a safe class of input and result. Copying the whole process environment or real order body is rarely necessary to explain an error in a support note.
Think through a release marker that changes while the actual schedule remains wrong. A marker can tell you which code version and configuration label produced a response, while the database or cached data may still deliver the older value. To verify a data change, compare an approved known input and expected business output. Compare a current release marker only when it has a defined source and someone maintains it. An incorrect manually set marker can create its own troubleshooting confusion.
For a final practical task, add a safe branch to your local working copy that reports a known second pickup. Predict which existing negative test would fail, then intentionally revise the test to reflect a changed requirement. Keep another unknown point as a negative control. Document the expected request body, status and response fields. Run one controlled restart and verify the new and old permitted cases. When the lab ends, remove only its process and workspace. Another student should be able to repeat the same assertions without knowing which browser happened to refresh first.
Write a fallback check before adopting a bigger instance count. If a second process is present and can return the readiness marker, summarize whether a representative lookup still succeeds across the actual arrival pattern. If the service is expected to restart under load, use a separate test environment and record incomplete requests, accepted results and actual data state. A process table may show several available workers while one still returns outdated configuration. Representative operations with deliberate markers can distinguish that from normal variation.
In your handoff, record which supervisor operation you practiced and the scope it controlled. The classroom result establishes that a named restart created a new local process and loaded the expected environment. It does not supply evidence of multiple workers, a durable restore, a public certificate, or recovery after an operating-system reboot. For an actual hosting plan, give each of those necessary outcomes its own owner and evidence. This makes the lab a specific building block within the plans you can test later.
Practice explaining the runtime and its supervisor
Does PM2 handle Express routes?
No. The Node process runs Express, defines routes and returns responses. PM2 supervises the process and provides lifecycle tools and logs. An upstream frontend can select the site and forward traffic. I would use a concrete request to verify the part of the app the customer needs.
What is the difference between a syntax error and a validation error in a JSON API?
A JSON parser cannot produce usable request data from malformed text. A valid JSON object can still contain the wrong field type or unacceptable value. I would test those separately and make the emitted errors clear to callers without revealing internals.
Is PM2 reload always free of interruption?
Its behavior depends on mode, application readiness, signal handling and the real workload. Cluster reload aims at continuity for compatible setups and can fall back to restart. I would measure the intended requests during the transition and check long-lived connections and shared state separately.
Why would you use a lockfile and the exact Node version for a candidate?
I want a repeatable process and dependency tree that match the reviewed artifact. A fresh candidate can run npm ci against the committed lockfile, then test the same runtime and dependency set I will promote. An older code commit paired with a different runtime may not be equivalent.
When is it reasonable to interpret an Express forwarded address?
When the application is reached only through the intended trusted forwarding path and the proxy and app settings agree about which addresses and headers can be trusted. I would first draw the actual chain, verify what each hop sets and test controlled cases before using the value in logging or policy.
Predict the outcome at the first relevant layer
The process is online, but the user says the API returns stale data. What would a better test inspect?
Answer and reasoning
Use the exact named API operation and compare status, returned value and expected release marker. Supervisor state cannot tell whether the running code and configuration provide the correct business result.
The sample request is valid JSON but
pointis a number. Which stage can reject it?Answer and reasoning
The application’s field validation can reject it after parsing. The syntax itself is valid JSON. This is the controlled wrong-type 400 in the fixture.
The app logs show no requests and the public frontend gives an upstream error. Should your first fix be changing the Express branch condition?
Answer and reasoning
First verify the selected frontend route and actual expected private listener. An upstream connection failure can stop the request before the condition ever runs.
Why does the lab use a temporary dedicated PM2 home?
Answer and reasoning
PM2 stores its process state and control sockets for that instance there. Starting and stopping the exercise remains scoped to its own processes instead of affecting a shared process manager.
What can startup integration and a saved process list establish before you check the site?
Answer and reasoning
They show how the process should be restored under the selected account after startup. The application still needs to start, listen and return the right result through the intended frontend.
Cards for an Express release checklist
Express in Node
Node runs the application. Express maps requests to middleware, validates the incoming shape with app code and returns statuses and data.
Named supervision
PM2 controls configured apps within an intended process-manager instance. Check the name, owner, runtime path and current behavior.
Local routing evidence
Test the actual private address and meaningful response, then verify the named public TLS and frontend path separately.
A restart has a scope
Use the intended service, configuration and release. Availability and durable state require their own checks during a transition.
Status plus body
Use the expected HTTP status and a stable response marker. Syntax errors, wrong field types and missing resources can require different changes.
Official references
- Node.js support and LTS release policy
- Node.js event loop and long-running work
- Express routing
- Express error handling
- Express trusted forwarding settings
- npm clean installs using a lockfile
- PM2 process management
- PM2 cluster mode and reload
- PM2 startup and process restore
- PM2 runtime reference
- PM2 graceful start and shutdown
- Nginx path forwarding and proxy headers