Ravindra BagaleCourses & study guides मराठी Track your progress

Chapter 10: Dynamic Website Hosting (PHP, Python, Node.js with MySQL)

AWS Cloud

10.5 Node.js (Express) with MySQL

Friends, run the Express app on its assigned loopback port, then give one launch path ownership of its restarts. Choose PM2 or a direct systemd unit for this exercise.

Select a supported Node.js and npm runtime

Choose the approved runtime first. Check the version and executable paths before installing project dependencies.

node --version
npm --version
command -v node
command -v npm

Interactive Node versions and managed services

A per-user Node version manager can select the project runtime in your terminal. A managed service may not inherit that shell setup. Verify the actual executable and supported release for both.

Create the Express app

Use the exercise source under the Express routes. Create it in an owned workspace, with the assigned runtime and database role. Launch the read-only mode first.

node --check app.cjs
npm ls express mysql2 --depth=0

Option A — keep it running with pm2

In an approved PM2 project, inspect the assigned app after configuring it as shown below. A boot configuration is a separate reviewed deployment step.

./node_modules/.bin/pm2 show student-express-lab
./node_modules/.bin/pm2 logs student-express-lab --lines 20

Option B — run it as a systemd service

After preparing the assigned direct unit, inspect it under the approved host procedure. The managed example later in this lesson uses a separate account and a private credential.

systemctl status student-express-lab.service
journalctl -u student-express-lab.service -n 20 --no-pager

Assign one launch path to the listener. A PM2 daemon can itself be supervised by systemd when the deployment plan uses that arrangement.

Ravindra Bagale's Tip

If the connection error names ::1, the request attempted IPv6 loopback. Match the address or hostname to the actual database listener. This local exercise uses 127.0.0.1 for its IPv4 listener.

Lab

Start the assigned copy with its approved owner. Check its health, readiness and student list before and after a controlled restart of that app. A whole-machine reboot is unnecessary for this exercise.

Serve the practice records through Node.js, Express and MySQL

A campus group wants its synthetic student list in a web table and a JSON response used by another learner's client. The team expects the server to read the database when the request arrives. When practicing locally, the group also needs one controlled way to insert a synthetic row and observe the saved result. Node.js runs the server-side JavaScript. Express chooses handlers for the requested paths and methods. The MySQL driver independently opens connections and executes the approved SQL. Those responsibilities make it possible to test the interface before configuring its managed front door.

Use the appdb.students table and fields from the database setup lesson. A local write exercise uses its limited read and insert account. The default deployment mode is read-only. A long-lived read-only service should also use its own appropriate read-only database grant. This sample stores no real personal data and does not implement a public registration identity. Exercise writes belong only to the explicitly launched loopback practice with its own temporary token and separately authorized database.

The important difference from the Flask example is the process lifecycle of the database pool. A pool can hold several ready connections and lend one to each query. A request that awaits a query lets the JavaScript runtime handle other tasks while waiting. It does not grant unlimited database capacity. Read the code for the pool's lifetime, queue bounds and shutdown, then verify results with actual node and database requests rather than inferring them from the process's running status.

Check which Node runtime and installed libraries the service will use

Use an approved supported Node LTS release and a matching npm for this exercise. LTS means long-term support and release support changes over time. Check the current Node release schedule and compatibility of the chosen packages rather than copying a fixed repository setup command from an older lesson. A distribution package, official project release or an approved organization repository can supply the runtime, depending on the operating system and site policy. Run read-only version checks before making changes.

node --version
npm --version
command -v node
command -v npm

Node and npm have different roles. The runtime executes the program, and npm installs project dependencies. Their version numbers can differ. A shell configured by a user-level version manager can find a different executable from the one a managed service sees. Record the exact runtime path for systemd or the approved process manager. Use a dedicated project directory and inspect its package files before installing dependencies. Do not run an unreviewed vendor shell command with administrator privileges or make a global package change to serve this one exercise.

# Run from a new approved practice project directory.
npm init -y
npm install express@5 mysql2
npm ls express mysql2
node --check app.cjs

Run the syntax check after saving the source below. This example uses Express 5 so promise rejections from asynchronous route handlers can be forwarded to its error logic. The .cjs extension selects CommonJS, the module arrangement with require used below. The generated lock file records resolved dependency versions. Keep the reviewed package manifest and lock with the release. For a repeatable installation in a fresh release, npm ci uses the existing matching lock and can replace that project's installed dependency directory. Use it in the intended stage, not directly inside another application's working directory.

Keep database credentials separate from the package and source files. The practice process receives a password through its local shell. A managed service can read the named db-password file from the credential directory supplied by its service manager. The configuration's host, port and schema defaults describe the local training setup. A private cross-host service requires its actual authorized TLS and transport settings. Use the driver's supported options and inspect its connection behavior rather than assuming a local success proves remote database identity.

Write the Express routes and create the pool only when needed

Save this as app.cjs in the project root. Running it normally makes the read handlers available on the approved loopback port and refuses writes. Launching with --local-lab enables only the practice write operation, and only when a new temporary token is present. The exercise sends the token to the local process using its own test client. It provides no reusable production identity or authentication system. Do not route a front proxy to a write-enabled practice process.

"use strict";
const express = require("express");
const mysql = require("mysql2/promise");
const { readFileSync } = require("node:fs");
const { join } = require("node:path");
const { timingSafeEqual } = require("node:crypto");

const app = express();
app.disable("x-powered-by");
const localLab = process.argv.includes("--local-lab");
const token = process.env.LOCAL_LAB_TOKEN || "";
const port = Number(process.env.APP_PORT || "18806");
if (!Number.isInteger(port) || port < 1024 || port > 65535) {
  throw new Error("Use an approved unprivileged HTTP port");
}
if (localLab && !/^[a-f0-9]{48}$/.test(token)) {
  throw new Error("Set the temporary local lab token before starting");
}

let pool;
class DatabaseUnavailable extends Error {}

function getPool() {
  if (pool) return pool;
  const credentialDirectory = process.env.CREDENTIALS_DIRECTORY;
  const password = credentialDirectory
    ? readFileSync(join(credentialDirectory, "db-password"), "utf8").replace(/\r?\n$/, "")
    : process.env.DB_PASSWORD;
  const user = process.env.DB_USER;
  const dbPort = Number(process.env.DB_PORT || "3306");
  if (!user || !password || !Number.isInteger(dbPort) || dbPort < 1 || dbPort > 65535) {
    throw new Error("Database connection settings are incomplete");
  }
  pool = mysql.createPool({
    host: process.env.DB_HOST || "127.0.0.1",
    port: dbPort,
    user,
    password,
    database: process.env.DB_NAME || "appdb",
    charset: "utf8mb4",
    connectTimeout: 4000,
    waitForConnections: true,
    connectionLimit: 4,
    queueLimit: 8,
  });
  return pool;
}

async function sql(statement, values = []) {
  try {
    const [result] = await getPool().execute(statement, values);
    return result;
  } catch {
    throw new DatabaseUnavailable("Student data temporarily unavailable");
  }
}

const list = () => sql("SELECT id, name, city FROM students ORDER BY id");
const safeText = (value) => String(value).replace(/[&<>"']/g,
  (character) => "&#" + character.charCodeAt(0) + ";");

app.use((request, response, next) => {
  response.set("Cache-Control", "no-store");
  next();
});

app.get("/", async (request, response) => {
  const rows = await list();
  const entries = rows.map((row) =>
    "<tr><td>" + safeText(row.id) + "</td><td>" + safeText(row.name) +
    "</td><td>" + safeText(row.city) + "</td></tr>"
  ).join("");
  response.type("html").send(
    '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
    "<title>Express practice list</title></head><body>" +
    "<h1>Express practice students</h1><table>" +
    "<caption>Synthetic records from the practice database</caption>" +
    '<thead><tr><th scope="col">ID</th><th scope="col">Name</th>' +
    '<th scope="col">City</th></tr></thead><tbody>' + entries +
    "</tbody></table></body></html>"
  );
});
app.get("/api/students", async (request, response) => response.json(await list()));
app.get("/health", (request, response) => response.json({ status: "ok" }));
app.get("/ready", async (request, response) => {
  await sql("SELECT id FROM students LIMIT 1");
  response.json({ status: "ready" });
});

function allowLab(request, response, next) {
  const supplied = request.get("X-Lab-Token") || "";
  if (!localLab || !/^[a-f0-9]{48}$/.test(supplied) ||
      !timingSafeEqual(Buffer.from(token), Buffer.from(supplied))) {
    return response.status(403).json({ error: "Local write operation unavailable" });
  }
  return next();
}

function field(value, maximum) {
  if (typeof value !== "string") return null;
  const clean = value.trim();
  return clean && [...clean].length <= maximum ? clean : null;
}

app.post("/api/students", allowLab, express.json({ limit: "4kb" }),
  async (request, response) => {
    const name = field(request.body?.name, 100);
    const city = field(request.body?.city, 50);
    if (!name || !city) {
      return response.status(422).json({ error: "Name and city must be valid text" });
    }
    const result = await sql("INSERT INTO students (name, city) VALUES (?, ?)", [name, city]);
    return response.status(201).json({ id: result.insertId, name, city });
  });

app.use((request, response) => response.status(404).json({ error: "Unknown route" }));
app.use((error, request, response, next) => {
  if (response.headersSent) return next(error);
  if (error instanceof DatabaseUnavailable) {
    console.error("Student list: database request unavailable");
    return response.status(503).json({ error: error.message });
  }
  if (error.status === 400 || error.status === 413) {
    return response.status(error.status).json({ error: "Invalid practice request body" });
  }
  console.error("Student list: unexpected request error");
  return response.status(500).json({ error: "Request could not be completed" });
});

const listener = app.listen(port, "127.0.0.1", () => {
  console.log("Student list listening on loopback port " + port);
});
listener.on("error", (error) => {
  console.error("Student list: listen failed (" + error.code + ")");
  process.exitCode = 1;
});

let closing = false;
function shutdown() {
  if (closing) return;
  closing = true;
  const deadline = setTimeout(() => process.exit(1), 8000);
  listener.close(async () => {
    try {
      if (pool) await pool.end();
    } catch {
      process.exitCode = 1;
    } finally {
      clearTimeout(deadline);
    }
  });
}
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);

Look at the separate language and storage decisions. The code keeps one lazily initialized pool per process. Four bounds the pool's configured connections and eight bounds waiting requests for a connection under the driver's policy. Calling pool.execute borrows and returns a connection for the single operation. A deliberate transaction spanning multiple statements would need to retain the same checked-out connection and release it in every outcome. Do not assemble such a transaction using several unrelated pool calls. The local example performs one insert with the database's normal autocommit setting.

Express runs middleware in the order registered. The write route checks its explicit local mode and token before parsing the bounded JSON body. It validates the field types and lengths before giving them to the prepared statement. The result's generated ID can help identify the new row. That single insert and returned ID do not define a production duplicate policy if a client repeats the same operation. The HTML rendering encodes each text value independently of SQL parameter handling. The JSON endpoint uses the service's serializer for the agreed fields.

The error middleware treats the driver or settings failure as a limited 503 without sending its internal exception. This sample collects a concise operator event. Production diagnostics should capture sufficient approved context to distinguish transport, authentication and query issues without recording secrets or personal data. A body parser can reject a syntactically invalid or oversized request before form validation. The default unknown route has its own 404. These different outcomes help the learner see which code path produced the response.

Lab one. Submit one synthetic JSON record to the isolated local process

You need the fresh Node project, the installed dependencies, a compatible dedicated database for practice and the restricted app role. Work from the directory containing app.cjs. In the shell below replace the approved settings if its local database uses another port. This exercise starts one child on a loopback-only HTTP address and keeps its temporary token in the shell. The token identifies the scoped development exercise and should not be reused as a production credential.

(
set -eu
export DB_HOST=127.0.0.1 DB_PORT=3306 DB_NAME=appdb DB_USER=appuser
export APP_PORT=18807
printf '%s' 'Practice DB password: ' >&2
IFS= read -r -s DB_PASSWORD
printf '\n' >&2
export DB_PASSWORD
LOCAL_LAB_TOKEN=$(node -e 'process.stdout.write(require("node:crypto").randomBytes(24).toString("hex"))')
export LOCAL_LAB_TOKEN
node app.cjs --local-lab &
app_pid=$!
trap 'kill -TERM "$app_pid" 2>/dev/null || true; wait "$app_pid" 2>/dev/null || true' EXIT
for attempt in 1 2 3 4 5; do
  if curl --noproxy '*' --silent --show-error --fail --max-time 2 \
      http://127.0.0.1:18807/health; then
    break
  fi
  kill -0 "$app_pid"
  sleep 1
done
curl --noproxy '*' --silent --show-error --fail --max-time 9 \
  --include http://127.0.0.1:18807/ready
curl --noproxy '*' --silent --show-error --fail --max-time 9 \
  --include http://127.0.0.1:18807/api/students
curl --noproxy '*' --silent --show-error --fail --max-time 9 --include \
  --header "X-Lab-Token: $LOCAL_LAB_TOKEN" \
  --header 'Content-Type: application/json' \
  --data '{"name":"Express rehearsal & proof","city":"Pune"}' \
  http://127.0.0.1:18807/api/students
curl --noproxy '*' --silent --show-error --fail --max-time 9 \
  --include http://127.0.0.1:18807/api/students
)

Choose an unused local port before starting if 18807 is occupied and update all requests consistently. The start loop waits briefly for the practice listener and checks that the child still exists. The first API response should contain the three seeded records from the setup exercise. The POST should show status 201 and the server-assigned ID for its synthetic name. The final GET should include the same ID, name and city. Compare the insert and new listing to demonstrate a persisted row. A normal browser visit to the local root should show the ampersand as visible text after rendering.

For a local rejection test change the data to a blank name in a fresh copy of the exercise, or run one scoped request without its expected token. Check that you get the intended 422 or 403 without a changed row count. When examining the normal JSON flow distinguish a media type error or malformed body from an invalid field. The JSON parser can produce a 400 before code looks for the individual field. In ordinary managed read-only mode the server denies the write path before parsing its data. Keep all rejected-input exercises within your assigned private sample.

Only the process launched by this practice is signaled when the shell exits. The main callback stops accepting new work and closes the pool when work is drained. Verify the practice listener no longer responds. The database is separate from the short-lived HTTP process and still contains the inserted synthetic data if it belongs to another continuing lab. Arrange scoped removal with the database owner or retire the dedicated scratch database. The app account cannot delete arbitrary rows. Record the unique ID if the practice table will be reused.

Decide which process manager owns the hosted lifecycle

A managed process benefits from a single clear owner for start, restart, logs and shutdown. PM2 is a process manager that can supervise Node applications. Systemd provides service management on many Linux distributions. They can be used together deliberately when systemd owns the PM2 daemon and PM2 owns the application. They should not independently launch duplicate copies of the same app on the same socket. Choose a managed deployment plan and confirm the port owner before applying it.

With PM2 use the approved installed manager and project path configured for that user. A locally installed PM2 binary can be run without changing a global npm library. The following lifecycle example assumes the owner has already configured the approved runtime environment and PM2 account for this app. Do not pass the --local-lab option. Review the manager's scope and any boot setup before applying startup instructions. A command printed by a process manager can change what starts at boot and whose environment it uses.

# In the approved project with the reviewed local PM2 already installed:
./node_modules/.bin/pm2 start app.cjs --name student-express-lab
./node_modules/.bin/pm2 show student-express-lab
./node_modules/.bin/pm2 logs student-express-lab --lines 20

The displayed PM2 state is process evidence. It does not establish that the database pool can accept a query. Run the app's read probes and inspect the exact port. PM2 can retain environment and process state in managed files, so use the deployment's approved secret integration and access policy. Avoid persisting the temporary exercise token or unredacted connection material in a general process inventory. Use managed startup and process list persistence only for the assigned retained service. When retiring just this exercise remove its owned process entry rather than stopping the entire PM2 daemon used by other apps.

A direct systemd service is another choice. Supply a dedicated account and vetted executable because a unit may not inherit the interpreter installed by a terminal's version manager. Put the code and locked dependencies in the approved root. The unit below enables the same read-only startup, with a private credential projection on systemd versions supporting it. Confirm the actual executable path and prepare the source credential through the lab owner. The named credential's contents do not belong to the unit body.

[Unit]
Description=Practice Express student list
After=network.target

[Service]
Type=exec
User=studentexpress
Group=studentexpress
WorkingDirectory=/opt/student-express-lab
Environment=NODE_ENV=production
Environment=APP_PORT=18806
Environment=DB_HOST=127.0.0.1
Environment=DB_PORT=3306
Environment=DB_USER=appuser
Environment=DB_NAME=appdb
LoadCredential=db-password:/etc/student-express-lab/db-password
ExecStart=/usr/bin/node /opt/student-express-lab/app.cjs
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Apply a new unit only in the assigned managed scope, after confirming no existing file or instance belongs to someone else. Validate the unit and reload systemd's configuration before starting the approved unit. Test active state, logs and locally assigned address. Boot enablement is separate from the current process status. A reboot is unnecessary for an ordinary deployment test. Keep any approved full lifecycle test to a disposable host that was explicitly assigned to it. Run the same first user read after activation or restart to prove the process has the expected database settings.

Lab two. Verify the managed read route independently of startup

Use a foreground node app.cjs process without the local flag, or use the owned managed unit. Match its settings to the dedicated sample database and actual loopback port. Open a second terminal and send the requests below. Health should pass before the pool needs to be created. Readiness will borrow a database connection and exercise the expected table. The real browser and API paths then verify the synthetic records. If your assignment includes the front proxy, repeat the real routed request through the approved site hostname after the local app check.

curl --noproxy '*' --include http://127.0.0.1:18806/health
curl --noproxy '*' --include http://127.0.0.1:18806/ready
curl --noproxy '*' --include http://127.0.0.1:18806/api/students
curl --noproxy '*' --include http://127.0.0.1:18806/

Expect 200 and the planned content type or markers. Read the particular count expected for your seeded database. The same test input sent as a POST to a normal managed process should return 403 and leave the count unchanged. The named website's HTML page can still show all approved synthetic fields. This verifies that the write boundary is enforced by the server and not merely omitted from the controls on the page. In a real read-only deployment the matching SQL role should enforce the same scope independently.

A healthy status and a failed API request can indicate a missing credential, unreachable network or schema failure. Inspect the service command, runtime identity and private connection settings. Verify the matched role and table with a targeted query. If the app works on loopback but the public request gives a proxy error, inspect the front server's target address, route and listening service. Avoid changing the database to repair a request that never reached Express. Use a fresh wrong-setting local copy to demonstrate the dependency failure rather than altering a shared database.

To close out, stop only the foreground process or assigned managed app using its ownership procedure. After a normal SIGTERM the server stops accepting calls and closes its pool after serving work already in progress. The sample sets a bounded fallback if that does not finish. Test that its private port is released. Retain or retire the seed data according to the database setup plan. The process's working copy and any approved managed credential can be retired only once no deployment depends on them. Verify any existing app controls after restoring shared state.

Trace three requests through the same application

Suppose Neha maintains a small equipment-training club. The club adds synthetic student records in the practice database. After her first demonstration, her teammate opens the app and says the list still contains three names. Before changing anything, write down what that teammate actually requested. Were they looking at the original static screenshot, the browser's current HTML report, or the JSON response? The three may display similar words while following different paths. Ask for the precise URL, method, response status and the ID that was expected. A recognizable record ID connects the learner's observation to the evidence returned by the insert.

First trace GET /health. The Node HTTP server accepts the network connection and hands Express the request. Express matches its lightweight handler. It sets the no-store directive and returns the JSON status. The SQL helper is never called. On a brand-new process, the pool may still be undefined at this point. That is deliberate. If installing or restarting the server is the experiment, this checks the HTTP boundary even when the classroom database is down. If viewing a student's row is the acceptance criterion, this test is only the first piece of evidence.

Now trace GET /api/students. The prefix looks like a file name to some beginners. On this server it is a route registered in code, selected using the request method and path. The read function asks MySQL for three explicit fields and an order. MySQL evaluates the statement and returns result data. The driver maps those rows into JavaScript values. Express serializes them and sends a response whose media type identifies JSON. When a later client expects HTML at this URL, changing the CSS cannot help. Give it the HTML route or teach that client to consume the JSON contract.

The HTML report asks for the same ordered rows, then encodes each value separately in a cell. When Neha adds the record named Express rehearsal & proof, the raw HTML contains an entity for the ampersand. The browser interprets that entity as text. The JSON representation contains an ordinary ampersand in the field value. Neither difference means the database contains a different student. Compare meaning at the relevant boundary. Saving a field after converting it to a display format would couple the database to one client and force other clients to undo that decision.

Finally trace POST /api/students. Express finds a different handler at the same path. The practice mode gate runs first. Suppose a teammate opens the same application with its normal managed command. Even a known temporary practice token cannot turn that ordinary process into a writer. The running process must have been started with the explicit lab argument as well. The code then checks the supplied token, parses bounded JSON, validates two fields, issues the prepared insert, and returns the generated ID. An error before the insert leaves the original count. An error after the database changes deserves particular attention before repeating the call.

Imagine a network disconnect between the insert and the client reading its response. The connection can fail even though the database has accepted the write. In this tiny lab, check the expected synthetic marker and record ID before resubmitting. A real registration workflow usually needs a business rule defining a duplicate and server-side prevention appropriate to that rule. A person's name alone is rarely a valid unique registration identifier. A practice request's token determines who may trigger this isolated action, while a production design must separately decide which repeated requests represent the same operation and how to record their result.

ObservationWhat it establishes in this labNext evidence to capture
Health returns 200Node and the health route can answer at the address used.Check readiness and one real page.
Readiness returns 200The query using the expected table and ID column works for this role.Verify the real read query and its expected synthetic rows.
JSON has four records, HTML shows threeThe JSON path already sees the additional row.Compare host, route, response body, timing and any caching front layer for the HTML request.
Local write returns 201 with ID 4The practice route's successful insert returned that ID.Read the ID through the approved list or targeted query and verify that exactly one record matches.
Managed write returns 403The ordinary app rejects the attempted method on this route.Confirm regular reads still work and the stored row count is unchanged.

Count the database work separately from the HTTP traffic

Imagine four readers opening the report while it is busy. Each request runs the same short application route. The process can wait for one database response and handle other incoming work in the meantime. Asynchronous database calls let the application ask for that result, resume other work, and return to the waiting handler once the driver finishes. They do not multiply the number of database sessions the server can support. The pool manages this separate resource. Connection setup has its own costs, including transport, authentication and establishing session settings. Reusing established sessions avoids doing all of that work for every row list.

The source code's connection limit is for one process. Start two separately supervised instances of the app with different private ports and each makes its own pool when it first needs one. Their configured maximum is eight database sessions altogether. Add a third process and the total becomes twelve. In a real deployment, reserve database capacity for its administrators, background jobs, other apps and operational margin. For example, if a learning service is deliberately budgeted twelve sessions across three processes, four per process fits that budget. Giving each process twelve would allow a theoretical total of thirty-six. Track comparable quantities when changing worker count and pool size.

When all four sessions in a process are occupied, the sample permits a bounded number of further requests to wait for a connection. Picture four requests actively using sessions, then eight queued for an opening. If those counts are still present when one more attempt arrives at the pool, the driver rejects it under this configuration. Our app responds with a generic dependency error. Timing can change that outcome. If a connection frees up while the next request is being handled, it may be able to join or proceed. This arithmetic illustrates capacity. It does not promise an exact wait duration or queue occupancy for any specific traffic replay.

Read connectTimeout as a connection setting. The quoted number in the sample is separate from the time a request spends waiting for the pool, the duration of a database statement, and how long a browser or reverse proxy waits for a response. Suppose the app cannot open a connection and the front proxy's own timeout is shorter. The client may see the front proxy's timed-out response before the app can return its database error. If long queries saturate established database sessions, a short connection timeout alone cannot shorten those queries. Diagnose measuring the relevant phase and use the supported settings at the responsible layer.

Normal single-statement calls borrow and return a session through the driver's pool method. A transaction that changes two records together is different. A transaction is scoped to a particular database session. If you call begin through one connection and then submit a separate write through the pool, the pool may lend a second connection. The second write then has different transaction state, so a rollback on the first can leave results from the second. For a future multi-step workflow, hold the checked-out connection through begin, every operation and commit. If a step fails, roll back on that same connection. Release it regardless of success or failure. The current lab avoids that complexity by doing only one insert.

A useful thought experiment is to consider a manually borrowed session that one error path forgets to release. That session cannot be borrowed again while held. One successful request might hide the mistake. Repeating the error can gradually consume the configured limit, leaving ordinary readers stuck waiting even though useful database work is no longer happening. Inspect connection ownership and release behavior before doubling the pool. When verifying a graceful shutdown locally, observe the same teaching server before and after the signal. In the tested serial fixture, five list reads reused one SQL session. After the private HTTP listener stopped, the sample closed that session. Concurrent tests could legitimately use more than one session.

If the report grows from three students to thirty thousand, the cost changes even though there is still only one statement. MySQL returns more rows, the driver retains more data, and JavaScript renders a larger response. Building a very large string is application work done before the browser sees anything. An API built for a busy club should agree how to order and page results. Stable ordering matters because a learner comparing two pages should be able to explain which records belong to each view. Add measurements for rows each request reads and response size before treating a larger pool as a capacity fix.

Diagnose compatibility, supervision and route symptoms

Suppose a package update looks harmless on a laptop but the managed app stops at startup. Start by reading what the intended service actually launches. A logged-in shell may resolve node through a per-user version manager. The service's absolute program path may point elsewhere. The checkout path may also differ from the one you edited. Compare the approved absolute executable, its version, the working directory and permissions of the server identity. Inspect package-lock changes in the release before blindly installing again. For runtime errors about a missing module, distinguish a missing dependency from running an entry file in a different project tree.

Express's current major release is an explicit exercise prerequisite. On Express 5, a handled route returning a rejected promise is sent to error processing. The async functions shown here return promises as part of the handlers. Older tutorials may use wrappers around promise handlers for a different major version. Separate delayed work detached from the handler also needs its own failure handling. Promise-aware routing only handles the promises the framework can observe. Confirm the actual installed major version and consult its documentation before copying error-handling helpers or assuming every asynchronous failure follows the route handler.

If the service manager says the process is active while a direct curl cannot connect, first compare the service's assigned address and port with the request. On a Linux training VM, your assigned ss check and service logs can confirm whether there is actually a listener. The address 127.0.0.1 explicitly selects IPv4 loopback. A program resolving localhost can obtain IPv4, IPv6 or both under its host configuration and resolver policy. This lesson passes an explicit address at both ends so the evidence is comparable. If the app reports that its selected port is in use, identify whether that listener belongs to an old practice copy or another owner's service. Move your own copy to the assigned free lab port. Do not stop another listener to force a quick demonstration.

If a health response succeeds but the API returns 503, use internal evidence in a consistent order. Check that the running service can read its credential and has the correct address and name for the assigned database. Use an allowed targeted read under a matching identity to confirm the expected schema. In the original schema lesson, the app role's access is scoped to its table. An administrator's query working under a more privileged session provides little evidence about that application's permissions. Review logs under the training procedure. Record whether a setting is present and which step fails without pasting the setting value or an entire environment dump.

When both loopback data routes pass and the front website fails, compare the front server's destination address, port and URI after rewriting. A public 404 can come from the front server's selected virtual host or from Express after a request reaches the wrong relative path. The bodies and log registries help separate those possibilities. A public 502 after a local app restart can indicate that the front proxy still points to the previous listening port. Verify the direct request with the exact upstream address taken from the active configuration before pointing the proxy elsewhere. The next lesson constructs this boundary explicitly and checks its selected paths.

Keep a short release record with the previous software revision, command, port, expected schema and a rollback contact when a change affects more than your practice folder. The npm lockfile helps rebuild the package tree. It cannot restore schema compatibility by itself if the database changed. Before reverting app code, check that it still understands the current schema and values. If credential rotation is the change, verify the new application process actually reads the approved credential before retiring the old one under a planned sequence. A healthy front page alone gives no conclusion about either the database or the next deployment restart.

Practice explaining the decisions in an interview

Where does Node.js finish and Express begin?

Node.js runs JavaScript outside the browser and provides access to system functions such as the HTTP listener. Express provides route matching, request and response helpers, and middleware above that runtime. In this lab, a request first reaches the address where the Node process listens. Express then interprets the method and path and invokes a suitable handler. MySQL2 is another separately installed dependency. It is the client that can exchange MySQL protocol messages with the database. Keeping the roles separate helps diagnose whether an error appeared before route matching, in application code, or while using the underlying storage service.

Why can the process be up while the student report fails?

The readiness route checks an actual dependency query. The health route only shows that the process answers a lightweight HTTP request. With the credential file absent, the exact lab still answered its health call but returned 503 for readiness and real data. A serious release check reaches the meaningful student report and verifies its expected markers. If the requirement is to save records, it also verifies the permitted write in an authorized practice environment and checks the saved evidence through a separate read.

What sets the maximum number of sessions the Node processes can open?

The application creates a pool per process. Multiply each configured pool limit by its process count, then account for other database users. Four per process and three processes can reach twelve under full use, even if a serial practice run only shows one. A queue holds callers waiting for an opening and is a different quantity. Capacity decisions should also consider query time and whether each acquired connection is correctly returned.

Why is a prepared statement different from encoding HTML output?

The prepared statement separates SQL structure from data parameters. That is a database interaction concern. The HTML renderer separately encodes characters so browser text can be rendered in the intended context. The same row is routed to a JSON serializer when the client asks for structured data. Rule out mixing the contexts. A value correctly written to the database still needs appropriate representation when it leaves the application.

How would you move the service from one startup method to another?

Record the current owner, release, runtime, credentials and listener. Decide the desired process ownership, prepare and verify the new settings and arrange a controlled handover of the listening address. Avoid executing two app launch commands for the same address at once. Test the health, readiness and real data paths after the handoff, then confirm the intended manager owns restarts. In a real service, also plan traffic changes and rollback according to how its front server reaches the app.

Check your reasoning with short scenarios

  1. A lab process shows health 200 and readiness 503. Which layer should you investigate first?

    Show answer

    Inspect the application's dependency settings and query scope. Health passed on that listener and says nothing about whether the database accepted the application's login or expected table query.

  2. Two Node app processes use the same database and each allows four sessions. What is their combined configured maximum?

    Show answer

    Eight application sessions. An individual limit applies per pool, and each process constructs its own pool as needed. Other database users have their own sessions.

  3. A POST reaches managed mode with the correct lab header. Will it insert?

    Show answer

    The gate returns 403 before parsing the body. Normal startup did not enable local write mode. Verify that the row count stays the same.

  4. Why did the saved fourth ID appear in JSON but the student name's ampersand look different in view source?

    Show answer

    HTML uses a character reference in raw source, which the browser displays as an ampersand. The JSON serializer emits a string value. Compare the interpreted field and record ID.

  5. A local app emits a database error only after long requests fill the pool. Will increasing its connection setup timeout empty the queue?

    Show answer

    That setting concerns opening sessions. Check active statements, held connections, available database capacity and the wait policy to explain the queue before changing settings.

Revision cards

Runtime and framework
Node provides the process and system APIs. Express matches a method and path, then invokes middleware or a handler registered in that process.
Promise-aware middleware
Express 5 can forward rejection from a returned route promise. Work detached from the request still needs an explicit error path.
Named endpoint contract
Record the method, path, media type and fields. The HTML report and JSON list represent the same data for different clients.
Bounded database pool
Connections are reusable and live in one app process. Count separate process limits before scaling up to stay within the database budget.
Meaningful readiness
Pick a small check tied to the dependencies the real operation needs, then independently verify the real request and its expected result.
Clean shutdown
Stop accepting new connections, allow already accepted requests time to finish, close the database pool and enforce a final deadline.

Apply the lesson to a report for equipment practice

Write a one-paragraph release check for an app listing practice equipment. Use made-up examples, such as a demonstration microscope and an empty tool kit. List which fields are public and which identifying fields are excluded. Draw a path from browser to Express to database and back with its two separate connections. Mark the application-level listening port and the SQL service port. As the first check, select a stable private health URL. As a second check, read a narrow query using the assigned database identity. As the final check, require the site's real report and named synthetic evidence.

Then grade the plan against three incidents. First the process is still listening, but its credential file is missing. Second a release restarted the app on a new loopback port while the proxy still uses the old one. Third a learner saved an item but lost the connection before seeing the response. Write the expected observation, the next evidence source and one narrow repair for each. The first should start with direct readiness and identity. The second should compare direct and front-facing results. The third should reconcile the state by a planned registration key or ID before retrying the write.

For an extra sizing problem, your training database administrator budgets eighteen free sessions after accounting for other workloads. The service must leave six of that allocation free for a second exercise. Show two permissible layouts for the equipment service, one with two processes and another with three. Two at six and three at four both fit the remaining twelve. Then describe the independent route timing check you would capture to choose. Counting sessions is an initial resource constraint. Actual query time, row volume and the application's own work determine whether the deployment meets its response target. Record these as different success criteria.

Finish with a short teardown note that another learner could use safely. Include the practice service name, known process ownership, listener address, which data rows or disposable database can be retired, and the expected result after stopping. Record an empty HTTP listener for that process and the cleanup evidence for its pool, while retaining any assigned database that belongs to the next lesson. If you used a revised runtime or lockfile, preserve the intended release record. File cleanup and traffic cleanup are separate operations. If the exercise reused a course-owned schema, follow its retention plan and keep your own synthetic row IDs so the administrator can verify the exact training side effects.

Official references