Chapter 12: Technology Stacks — LAMP, LEMP, MEAN, MERN
12.9 Stack comparison summary
Friends, compare the four stacks below by frontend, runtime and data. Work out the actual listener and permitted source for each connection. Public HTTPS, optional HTTP and the administrative path depend on the deployment.
मित्रांनो, चारही stack मधले frontend, runtime आणि data यांची तुलना करा. प्रत्येक connection साठी नेमका listener आणि परवानगी असलेला source लिहा. Public HTTPS, गरजेचा HTTP आणि admin access हे deployment वर ठरतात.
दोस्तों, चारों stack के frontend, runtime और data की तुलना करो. हर connection का सही listener और अनुमत source लिखो. Public HTTPS, ज़रूरत के अनुसार HTTP और admin access deployment पर तय होते हैं.
| Point | LAMP | LEMP | MEAN | MERN |
|---|---|---|---|---|
| Web entry | Apache | Nginx | Approved frontend, such as Nginx | Approved frontend, such as Nginx |
| Application runtime | PHP through a configured Apache handler | PHP through the configured FastCGI worker pool | Node.js and Express | Node.js and Express |
| Illustrated UI | Server-rendered PHP and HTML | Server-rendered PHP and HTML | Angular browser app in this example | React browser app in this example |
| Database | MySQL or compatible MariaDB | MySQL or compatible MariaDB | MongoDB in the chapter's API | MongoDB in the chapter's API |
| Process supervision | Chosen service manager for Apache and its PHP setup | Chosen service manager for Nginx and PHP-FPM | Chosen manager or platform for Node | Chosen manager or platform for Node |
| Private connection to check | Actual PHP handler and SQL connection | FastCGI socket or endpoint and SQL connection | API listener and database connection | API listener and database connection |
| Network policy | Permit the intended sources for the actual public, administrative and private connections. Choose rules for the deployment rather than by acronym. | |||
Ravindra Bagale's Tip
Ask what you need to build and maintain. Compare the team’s existing skills, application model, data relationships, and the work required to operate and recover the service.
Ravindra Bagale's Tip – मराठी
Stack निवडताना काय बांधायचं आणि नंतर सांभाळायचं आहे ते विचारा. Team चं कौशल्य, app ची रचना, data मधले संबंध आणि service परत चालू करण्याची जबाबदारी यांची तुलना करा.
Ravindra Bagale's Tip – हिंदी
Stack चुनते समय पूछो कि क्या बनाना और संभालना है. Team का कौशल, app की रचना, data के संबंध और service ठीक करने की ज़िम्मेदारी की तुलना करो.
Lab
Run the private comparison below. For the same schedule value, identify the PHP HTML response, the browser shell and the JSON API. Record what each returns when the shared test data is unavailable.
Choose the stack around one workflow you can verify
Mauli Dairy wants riders to look up the next east pickup. The operations team also needs to publish changes, keep the current notice after a server replacement, and recover when the data source is unavailable. One developer suggests LAMP because the company already has a PHP site. Another suggests MERN because the team is trying React. Both proposals can sound right while the business requirement is still unclear. Start with the visitor’s exact journey and who will maintain it after launch.
Here is the common exercise. A rider opens a public route and sees an east pickup time of 16:00. If the schedule data becomes unavailable, the rider should get an understandable result. The page should not quietly display yesterday’s time because an outer layer kept returning 200. Measure that requirement in each design. A technology stack is the combination of tools providing the route, application behavior, and storage. Four memorized names do not tell you which component supplies which part of the rider’s experience.
Draw the production path from left to right. Start with the browser, the exact named HTTPS endpoint, the software responsible for public request routing, the process generating a response, and the place it reads or writes authoritative state. Add the build and supervision responsibility below. We are going to compare those roles using the same small pickup requirement. Holding the requirement constant makes the differences in routing, rendering, state and operations easier to see.
Decide what a useful success looks like before reading the comparison. Pick a known valid input, a deliberate unknown pickup, and an unavailable data path. Write the status, response type and visible outcome you expect. There may be several valid designs. You need a reason for selecting one that is compatible with existing data, people and operating constraints. Keep the other designs available as comparisons, not as reasons to copy several incompatible recipes into the same server.
Read the names as roles in this chapter’s examples
| Example | Request path | Data path |
|---|---|---|
| LAMP | Linux, Apache, and a PHP handler in the chapter's examples. | PHP uses MySQL or a compatible MariaDB deployment. |
| LEMP | Linux, Nginx, and PHP. PHP-FPM often runs the worker pool. | The PHP app can use the same SQL model as in LAMP. |
| MEAN | Angular provides the browser interface. Express runs in Node.js for application requests. | The server app uses MongoDB for the illustrated document data. |
| MERN | React provides the browser interface. Express and Node.js can serve the same API. | The server app uses MongoDB for the illustrated document data. |
Linux is the operating environment in the two PHP examples, and Nginx, pronounced “engine X,” supplies the E in LEMP. PHP-FPM is a way of running PHP through a managed FastCGI worker pool. It is not a different application language. Apache can also use a FastCGI configuration or another supported PHP handler. If a team changes Apache to Nginx while retaining the app and database, the request-routing contract changes around the same application model. Check the actual version and handler involved on the intended host.
MEAN and MERN use the same letters for MongoDB, Express and Node.js. The fourth technology is Angular in MEAN and React in MERN. Angular provides a broad framework for application development with its own ecosystem of routing and tooling. React provides a UI component library with deployment and routing decisions depending on the project and framework. JSX is a common React syntax but is optional. Angular projects commonly use TypeScript, and React projects can also use TypeScript. The language choice alone does not explain how the applications are deployed.
An extra public reverse proxy such as Nginx is a deployment choice for the JavaScript stacks. It can serve a browser build and forward API requests, but you can also use a managed frontend or another appropriate web delivery arrangement. Linux can run these stacks too, although the named acronym focuses on a different list of components. Match the actual deployment roles. A mobile reader cares whether the site returns the current schedule, not which acronym your server diagram happens to use.
Do not infer the hosting model from a familiar frontend term. A single-page application, or SPA, can load an initial browser shell and use client-side routing or fetches to update the view. Angular and React deployments can also use server rendering, static generation or mixed approaches. Likewise, a PHP app can provide JSON for a browser interface. We compare a server-rendered PHP example with a separately delivered browser shell and data API because their evidence boundaries are easy to test. These are choices of architecture rather than universal limits of their tools.
Compare Apache and Nginx around the same PHP application
Suppose the current WordPress-like site already generates the schedule from a PHP template. The visitor asks for a named route. Apache selects a virtual host, uses its configured path rules, and passes the applicable request to the actual PHP handler. The handler reads the requested script and returns the dynamic response. Apache can serve a stylesheet or image directly. The browser receives HTML containing the current schedule when the server-rendered request succeeds.
Now draw LEMP for the same route. Nginx selects the applicable server configuration and location. It can serve files directly and send eligible dynamic requests using FastCGI to a configured PHP-FPM socket or endpoint. PHP-FPM means FastCGI Process Manager. Its workers execute the script. The site configuration needs to map the correct script filename and make the separate process reachable. A matching PHP package in a terminal does not prove the web server points at its active pool.
Apache can apply rewrite rules at a configured vhost or in approved scoped directory overrides. Nginx does not read Apache’s .htaccess file. An Nginx migration can require expressing equivalent path behavior in its configuration. Test the exact old public URLs, redirects, the dynamic schedule and selected static assets. A syntax-validation pass means the candidate parses. It does not prove that requests reach the right PHP script or that other sites on the same server are unaffected.
Keep the database and records fixed while conducting the first comparison. If the former Apache route works and the new Nginx route fails with the same app and database, inspect the first differing step. Which host did the frontend choose? Which document root did it see? Does the selected FastCGI listener exist and can the frontend reach it? What exact path did PHP execute? A static homepage can remain available while Nginx cannot send a dynamic request through its configured socket.
Test the application’s access identity independently. A PHP-FPM pool can run under a different account from the frontend process. Grant the right reads and runtime writes for the actual app rather than making the whole tree writable. The PHP database client must use the intended credentials and reach the expected data source under its controlled policy. Match the stack change with observed evidence in each layer. Moving the frontend does not authorize a public database change or a blanket permission change.
Keep UI delivery and API behavior separate for Angular and React
In our browser-oriented comparison the pickup route has two meaningful stages. The frontend first returns HTML and any JavaScript or CSS it needs. A browser application can then request the schedule from an API. A shell is the starting document and resources the browser loads. The page can still render its general layout when the API cannot obtain data. Design for that state explicitly so the rider knows whether a displayed time is current.
With a small same-origin site the browser and API can share one scheme, host and port. The origin is the combination of those three URL properties. In a simple design the public frontend directs /api/ to the backend and serves the app from the remaining intended routes. The browser can request a relative API path. Keeping them under one origin is a deployment choice that avoids making a cross-origin policy part of this particular path. If services deliberately use different origins, configure their rules and cookie or token behavior for the actual application.
A client-side route may exist in browser application code without having a same-named file on the server. For example, visiting /collection/today from inside the running app can work while directly reloading the URL returns a server 404. A suitable SPA hosting configuration can hand recognized browser navigation paths to the built starting document. Keep API paths and ordinary asset misses distinct so an unknown JSON endpoint or missing script does not become a misleading HTML success response.
Read the actual response type. A valid browser entry route can produce 200 and text/html. A good schedule API route produces 200 with the expected JSON payload and media type. A deliberately unknown API route should return the specified API error, often a JSON 404. If a browser console reports a parse error and the failed API response begins with HTML, check the route and fallback first. The app may be parsing its own shell instead of receiving data at all.
In MEAN and MERN examples the backend can use the same Express route and MongoDB contract. An API contract specifies such things as request path and method, input rules, response fields, statuses and error behavior. Define the contract once for our pickup feature. Compare the Angular and React interfaces using the same API expectations. UI framework choice can affect team skills, routing and build requirements without forcing a database change every time the interface changes.
Plan stable builds and compatibility between a newly deployed API and browsers still using an earlier bundle. A customer may have a previously cached version of the UI. Removing a route or changing a field type can fail even if the newest browser UI works with the newest server. A real release can retain previous assets where required and test one compatible prior client path during the change. Record which artifact and route produced the observed schedule instead of just quoting package names.
Choose a data model from the reads and updates you need
Consider the rider’s lookup and the operations team’s reporting. The rider mostly wants a current time and collection point. The back office wants to see all booked orders, their customers, paid amounts and pickup history. It also needs rules that prevent references to nonexistent customers and procedures for updating several relevant records together. These are different access patterns. Describe them before choosing how to store the data.
In a typical relational design the app can put customers, collection points and bookings in different tables with stable identifiers. A foreign key is a database rule that can require a referenced record to exist, depending on the engine and configured constraints. The team can query related data using joins and can choose transactions for coordinated changes. Think about which values should be unique, which steps require consistency and which queries need useful indexes. A relational database does not make the application automatically correct if the constraints, permissions or transaction boundaries are missing.
A document-oriented design can keep data that is often read together in one document. A pickup schedule might contain the point name, cut-off time, reading instructions and the current notes. If every consumer wants those fields together and they change together, embedding them can fit well. If many unrelated records reference one frequently changing address, a reference or a different document boundary may make updates easier. Design from the observed reads and writes rather than duplicating data by habit.
MongoDB supports collection validation and has transaction features under appropriate configurations. The presence of flexible fields does not mean the schema needs no thought. Decide how old and new document versions coexist, what the application accepts, and how queries are indexed. SQL databases can also store document-like data using their supported types. Pick a representation that meets the required invariants and measured queries. Neither a SQL word nor a NoSQL word alone fixes your schema or recovery plan.
Model a specific change. The dairy changes one point’s name and needs it reflected in future bookings without rewriting past receipts. One design references a collection point for current queries and stores the issued name separately in an immutable receipt record. The business rule determines which parts move together. The same requirement can have plausible solutions in different systems. Ask which operations must be atomic, which data needs a point-in-time record, and how you would verify restoration.
Keep data private through an appropriate connection and identity. The browser sends a permitted request to the application and the server reads only what it needs using a managed credential. A SQL driver or MongoDB driver uses the intended reachable endpoint with approved access and transport verification. The admin’s ability to sign in with a privileged identity does not show that a read-only schedule account works. Test from the real application boundary and observe the expected response.
Treat listeners and firewall rules as an architecture decision
A port is one name for a network connection’s intended destination within a host. A listening process or managed service needs to accept the configured protocol and port at the right address. A Unix socket provides local interprocess communication without a publicly reachable TCP port. MySQL and MongoDB have familiar defaults, and Node examples often pick high private ports. A service can choose other supported values. A textbook port says little about which routes should be reachable from the internet.
Draw the allowed connection from the visitor to the public TLS endpoint. If the deployment redirects or handles an HTTP challenge, decide whether a particular public listener also needs HTTP. If public TLS ends at a load balancer, the app instance may allow only traffic on its target port from the load balancer’s intended security group or source. The database may separately allow the approved application security group. A public site does not imply exposing its database or the Node or FPM backend. These are distinct connection decisions.
Administrative access follows the organization’s design. A restricted SSH listener from an approved source may be appropriate. A correctly configured Systems Manager Session Manager path can manage an eligible instance without opening a public inbound SSH port. Neither selection follows from choosing LEMP or MERN. Record the actual approved management path, roles and network requirements. An inbound rule from all networks for a stock port should never appear simply because it is next to other example ports in a comparison.
A security group describes network access to the resources it is associated with. It cannot make a server listen or cause a URI to match an application route. If a connection fails, compare DNS, the intended destination, the actual process’s bind address, available network paths and permitted sources. On a single host an Nginx-to-FPM socket has file permissions. Between hosts an application-to-database TCP connection has different network controls. Use the mechanism that corresponds to the observed failed connection.
Draw this on paper. A load balancer accepts public HTTPS on its approved listener. Its target service listens on an internally defined app port. That app then connects privately to a managed SQL database. Label the listener types and each approved source. Now replace PHP with an Express app while keeping the same approved public entry. The outer customer URL may stay the same, while the target port, allowed identity, process command or data protocol changes. Verify each actual arrow rather than copying the public rule list across diagnoses.
Work through three defensible choices
Keep a working publishing workflow
The dairy has a well-maintained PHP CMS, an approved SQL backup and a team that publishes in its editor daily. The immediate request is a reliable pickup page and timed publication. Begin by considering the existing PHP application and data. Add the needed route within that architecture if it meets the handling and editing requirements. Compare retaining Apache with moving to Nginx only if there is a specific operating reason. Moving frontends requires translating the actual routes and validating file, PHP and TLS behavior. It does not normally require changing the database engine.
Write acceptance for the existing application. An editor can change a scheduled notice. An ordinary reader receives the correct rendered time from the exact current URL. Previously published posts and media remain usable. If the business expects the site to continue without a front-facing failure during a rollout, the test needs representative traffic and recovery observation beyond a config parse. Consider the team’s incident responsibilities and supported versions before deciding that a new runtime is simpler.
Pick a frontend with an existing compatible API
A second team already operates a supported Express schedule service and wants a richer browsing experience. It has a team comfortable with Angular’s project conventions and shared component practices. MEAN may fit its needs if it already uses an appropriate MongoDB model. Another organisation might already use React, shared UI components and familiar routing and deployment tooling. MERN can fit that team's frontend requirements. The same API can serve both candidate interfaces so the comparison can hold data, URLs and response behaviors stable.
Compare two practical tasks rather than arguing that one framework is always faster. Test navigating to the pickup page through an ordinary link and refreshing the exact direct path. Then withhold or simulate an unavailable lookup and observe how the interface tells the rider. Compare build output, deployment changes, testability and what the operating team needs to diagnose those results. If you intend server rendering, include its runtime and availability responsibilities in the design. Using a frontend framework does not imply that every application is deployed as static files.
Mix components when your requirements differ
The dairy plans to keep its CMS and build a read-only rider app consuming a separate API. That can involve React or Angular in the browser and a PHP API backed by SQL. The product is still a stack, even without one of the four classroom acronyms. Or a Node backend may serve a relational database because order integrity and reporting suit that design. Choose each component by its responsibility, documentation, team capability and operational fit. Avoid migrating durable data solely to match a popular name.
Write two columns for expected benefit and new responsibility. A separate browser and API can make UI releases more independent, but version compatibility, route separation and API observability become explicit tasks. A server-rendered design can return the useful first response directly in one request, while its template and backend may require coordination for changes. A project may also use both patterns for different features. Run representative checks of the actual visitor’s time-to-useful-result, behaviors when data fails, and recovery requirements. Use measured results instead of performance claims implied by tool names.
Run one real frontend against two response patterns
Use a regular Unix-like account with Python 3, Nginx, PHP-FPM and Node.js available. If needed, set NGINX_BIN, PHP_FPM and NODE_BIN to the corresponding executable paths. This exercise was checked with Nginx 1.30.7, PHP-FPM 8.3.6 and Node 24.22.3. Those versions identify the local test only. Choose currently supported packages for an actual deployment. The block needs no cloud access, elevated privileges or package downloads.
Predict three phases. In the first phase, the PHP route renders the real pickup value in an HTML page and the browser-style site returns the shell and API as separate successful responses. An unknown API path returns a JSON 404. In the second phase the script temporarily withholds the shared training data file. The PHP route and JSON API both return controlled 503 responses. The independent browser shell still returns its original HTML. In the final phase the data returns and the tests confirm both dynamic reads work again.
Nginx, FastCGI, PHP-FPM and Node are real in this exercise. The shell is a small static page rather than an Angular or React build, and the API uses Node’s built-in HTTP module instead of Express. The two routes read a deliberately tiny local text file as a substitute for a database. Using one shared input makes it easy to match the returned schedule across both paths and explain which success does not measure the data dependency. The previous chapter examples exercise the actual LEMP and SQL route and Express and MongoDB API.
python3 - <<'PY'
from contextlib import ExitStack
from http.client import HTTPConnection
import json
import os
from pathlib import Path
import shutil
import signal
import socket
import subprocess
from tempfile import TemporaryDirectory
import time
if os.geteuid() == 0:
raise SystemExit("Run this as a regular user.")
nginx = os.environ.get("NGINX_BIN") or shutil.which("nginx")
fpm = os.environ.get("PHP_FPM") or shutil.which("php-fpm")
node = os.environ.get("NODE_BIN") or shutil.which("node")
if not all((nginx, fpm, node)):
raise SystemExit("Make nginx, php-fpm and node available or set their full paths.")
def stop(process):
if process.poll() is None:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=4)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=4)
def start(scope, name, command):
stream = scope.enter_context((lab / (name + ".log")).open("w+"))
process = subprocess.Popen(
command, cwd=lab, stdout=stream, stderr=subprocess.STDOUT,
start_new_session=True,
)
scope.callback(stop, process)
return process, stream
def wait_for_socket(process, stream, endpoint):
until = time.monotonic() + 8
while time.monotonic() < until and process.poll() is None:
if endpoint.is_socket():
return
time.sleep(0.05)
stream.seek(0)
raise RuntimeError(stream.read() or "Worker socket never appeared")
def ask(host, path):
connection = HTTPConnection("127.0.0.1", port, timeout=2)
try:
connection.request("GET", path, headers={"Host": host})
response = connection.getresponse()
media_type = response.getheader("Content-Type", "").split(";", 1)[0]
return response.status, media_type, response.read()
finally:
connection.close()
with ExitStack() as scope:
lab = Path(scope.enter_context(TemporaryDirectory(prefix="stack-compare-", dir="/tmp")))
shell = lab / "browser"
shell.mkdir()
data = lab / "pickup.txt"
data.write_text("EAST-1600\n")
(shell / "index.html").write_text("<!doctype html><h1>Pickup browser shell</h1>")
(lab / "catalog.php").write_text('''<?php
header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-store');
$path = __DIR__ . '/pickup.txt';
if (!is_readable($path)) {
http_response_code(503);
echo '<h1>Schedule unavailable</h1>';
return;
}
$text = trim(file_get_contents($path));
echo '<h1>Pickup schedule</h1><p>' . htmlspecialchars($text, ENT_QUOTES, 'UTF-8') . '</p>';
''')
(lab / "api.cjs").write_text('''const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
http.createServer((req, res) => {
let status = 404;
let body = { error: "unknown API route" };
if (req.method === "GET" && req.url === "/api/pickup") {
try {
body = { pickup: fs.readFileSync(path.join(__dirname, "pickup.txt"), "utf8").trim() };
status = 200;
} catch {
status = 503;
body = { error: "schedule unavailable" };
}
}
res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
res.end(JSON.stringify(body));
}).listen(process.argv[2]);
''')
(lab / "fpm.conf").write_text(f"""
[global]
pid = {lab}/fpm.pid
error_log = {lab}/fpm-errors.log
daemonize = no
[catalog]
listen = {lab}/php.sock
listen.mode = 0600
pm = static
pm.max_children = 1
clear_env = yes
security.limit_extensions = .php
php_admin_flag[display_errors] = off
""")
fpm_process, fpm_log = start(scope, "fpm-boot", [fpm, "-n", "-F", "-y", str(lab / "fpm.conf")])
node_process, node_log = start(scope, "api-boot", [node, str(lab / "api.cjs"), str(lab / "node.sock")])
wait_for_socket(fpm_process, fpm_log, lab / "php.sock")
wait_for_socket(node_process, node_log, lab / "node.sock")
# Pick an unused local port. If another process claims it first, rerun.
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
port = probe.getsockname()[1]
(lab / "nginx.conf").write_text(f"""
worker_processes 1;
pid "{lab}/nginx.pid";
error_log "{lab}/nginx-errors.log";
events {{ worker_connections 32; }}
http {{
access_log "{lab}/nginx-access.log";
types {{ text/html html; }}
default_type text/plain;
client_body_temp_path "{lab}/client";
proxy_temp_path "{lab}/proxy";
fastcgi_temp_path "{lab}/fastcgi";
uwsgi_temp_path "{lab}/uwsgi";
scgi_temp_path "{lab}/scgi";
upstream local_api {{ server unix:{lab}/node.sock; }}
server {{
listen 127.0.0.1:{port} default_server;
server_name _;
return 404;
}}
server {{
listen 127.0.0.1:{port};
server_name php-stack.example.test;
location = /pickup {{
fastcgi_param SCRIPT_FILENAME "{lab}/catalog.php";
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_pass unix:{lab}/php.sock;
}}
location / {{ return 404; }}
}}
server {{
listen 127.0.0.1:{port};
server_name browser-stack.example.test;
root "{shell}";
location ^~ /api/ {{ proxy_pass http://local_api; }}
location = /collection/today {{ try_files /index.html =404; }}
location / {{ return 404; }}
}}
}}
""")
ng_args = [nginx, "-p", str(lab) + "/", "-c", str(lab / "nginx.conf"),
"-e", str(lab / "nginx-bootstrap.log")]
subprocess.run([*ng_args, "-t"], check=True, timeout=8)
front, front_log = start(scope, "nginx-boot", [*ng_args, "-g", "daemon off;"])
until = time.monotonic() + 8
ready = False
while time.monotonic() < until and front.poll() is None:
try:
ready = ask("unknown.example.test", "/")[0] == 404
if ready:
break
except OSError:
pass
time.sleep(0.05)
if not ready:
front_log.seek(0)
raise RuntimeError(front_log.read() or "Private frontend never became ready")
php_site = "php-stack.example.test"
js_site = "browser-stack.example.test"
assert ask(php_site, "/pickup") == (200, "text/html",
b"<h1>Pickup schedule</h1><p>EAST-1600</p>")
page = ask(js_site, "/collection/today")
assert page[:2] == (200, "text/html") and b"Pickup browser shell" in page[2]
api = ask(js_site, "/api/pickup")
assert api[:2] == (200, "application/json") and json.loads(api[2]) == {"pickup": "EAST-1600"}
missing = ask(js_site, "/api/missing")
assert missing[:2] == (404, "application/json")
print("PHP returned note in HTML; browser shell and JSON API were separate.")
hold = data.with_suffix(".held")
data.rename(hold)
assert ask(php_site, "/pickup")[:2] == (503, "text/html")
assert ask(js_site, "/collection/today") == page
assert ask(js_site, "/api/pickup")[:2] == (503, "application/json")
print("Without data: PHP 503; browser shell 200; API 503; unknown API stayed separate.")
assert ask(js_site, "/api/missing") == missing
hold.rename(data)
assert ask(js_site, "/api/pickup") == api
assert ask(php_site, "/pickup")[0] == 200
print("Restored record; both data routes work again.")
assert not lab.exists()
assert all(proc.poll() is not None for proc in (front, fpm_process, node_process))
print("Temporary frontend, workers, sockets and records removed.")
PY
Follow the two named hosts defined by the program. For the PHP host, Nginx’s exact route supplies the script filename on a private FastCGI socket. The PHP worker reads and safely renders the test value into its HTML response. For the browser host, Nginx hands the one recognized browser path to the shell and forwards the API prefix on a different local socket. The Node service handles the actual JSON route and responds to an unknown API path with a JSON 404. The frontend’s unknown-host test rejects an unmatched host, giving you a separate control for route isolation.
Read the test output as evidence about the operational boundaries. During normal operation, print one row for the PHP HTML marker, one for the browser shell, then an API row with the data and content type. When the data file is temporarily unavailable, preserve the shell and data results as independent rows. The shell still loads, so it cannot establish the pickup time is available. The API 503 comes from the Node read, while the PHP page reports unavailability in its own HTML response. One architecture puts the result and its failure in the original page request. The other has a separate response for the same data dependency.
Check the role of the fallback. The fixture serves exactly one recognized browser deep link with the shell. It sends API routes to the API and does not allow an unknown API route to use a browser fallback. If you use a more general fallback in a deployed app, verify the same separation, including missing scripts and style files. A fallback used to support browser navigation is not an instruction to answer every request with success. A valid 404 supports good diagnosis.
After restoring the data file, the assertion repeats the API response and checks that PHP returns a successful page. The context closes all child processes and removes registered temporary paths. If an initial program is missing, provide its correct actual executable path. If Nginx cannot bind its temporary port because another process picked it, rerun to use a new available port. The test never takes ownership of a shared system listener. A failure in the local runtime says to check this isolated environment. It is not a reason to enable a system service or change an existing host configuration.
Two implementation details are intentionally small. Node’s synchronous file read makes the experiment easy to inspect and is unsuitable as a default for long or frequent operations in a real event-loop service. The file is a training substitute for a data store. Async database access, credentials, validation, concurrency and failure handling would need their own design and tests in a real API. Explain that scope before presenting a comparison between production stacks based on the experiment.
Use different evidence for route, runtime and data failures
Write down what the requester actually sees. A named path that reaches a fallback page over HTTPS indicates some frontend responded, but it may be the wrong host or deployment. A dynamic response with a gateway error can mean the frontend selected an upstream it could not use. A working browser shell with a failed API can mean the frontend files are available and the data route stopped elsewhere. A correct API response with a blank screen can direct you to the deployed frontend bundle or application logic. In each case, compare one layer at a time.
Start with the full public name, path and expected status and type. Confirm whether the observed response came from the selected named frontend, route and actual process. Inspect a small response marker to distinguish the target site from a distribution default. If the proxy can reach the app but sends the wrong prefix, the app can correctly return a 404 for the path it saw. If the private worker is unavailable, the route cannot get that far. Match the exact request with relevant scoped logs where available.
A normal test of the PHP app should ask for a dynamic result, not just a static stylesheet. Check whether the chosen web process can reach the local PHP-FPM socket and whether its worker can execute the intended script and access the data. If everything is expected except media, verify its intended URL, permissions and bytes. The existence of a functioning database does not establish that the current public route selects its expected connection or database identity.
For a separately delivered UI, check browser navigation first, then the API request as an independent observation. Record the method, response type and current data fields. If the API works locally but the browser receives HTML, verify the selected frontend location and API route. If the API returns a valid error such as 503 for a temporarily unavailable dependency, the UI should handle the error with a visible message instead of showing an apparently old successful value. Reproduce the real client’s path when possible.
When an application is healthy but records are missing after a release, inventory where the data was supposed to persist. A shell file, a PHP release directory, or Node worker memory is not a backup of the relevant database. Verify credentials, schema, media paths and storage integrity independently. A move to another stack can change data representations and compatibility. Rehearse backed-up restore with a real representative operation, and test whether the earlier and new components can read the latest accepted data across a planned rollback.
Complete the selection record before planning a migration
Choose one deployment for the pickup workflow as an exercise. Write the exact use case, including who updates the records and what the private data depends on. Identify the team that will own the public listener, app runtime and database. In your answer, note any maintained tool you can reuse and any new responsibility the selected stack introduces. Use less familiar parts to expose real support and incident work rather than dismissing them by their language.
Next create a small acceptance matrix. Test direct browser navigation, one known useful result, an unknown route, an unavailable data response, and at least one restart or rollback within a separately approved setting. Include an explicit check for the database connection and expected result using the right identity. If app code and the frontend are separate versioned artifacts, verify that the current browser build and candidate API can operate together. If the app renders server HTML, check its route, expected data and behavior when the downstream dependency is unavailable.
Make the networking decisions visible in the same plan. Write which service needs public reachability, whether plain HTTP is expected as an entry, and which upstream routes are allowed. Add separate administrative access and do not count an app or database port as public merely because it is needed internally. State where the certificate is deployed and whether another connection uses its own transport policy. Draw a rollback boundary around the exact deployment, then list which persistent data and neighboring services should remain available.
Give the plan to a partner and ask them to choose a conflicting scenario. For example, they may switch the requested summary report from simple fields in one note to many relationships and time ranges. Or they may introduce a requirement for UI rendering on the server or support for an earlier browser bundle. Explain which parts of your decision should change and which evidence still applies. A good stack comparison stays useful when the product changes because every recommendation is tied to a requirement and an observable result.
Explain the decision instead of reciting acronyms
How would you compare LAMP and LEMP for an existing PHP application?
I would separate the frontend from the runtime and SQL model. LAMP uses Apache in this comparison, while LEMP uses Nginx. Both can run PHP through suitable handlers, and the existing compatible SQL data can remain. I would compare vhost, rewrites, document root, FastCGI access and verified public routes, then test old URLs, assets and active content.
Must replacing Angular with React also replace the database?
No. In the common MEAN and MERN design the two frontend choices can consume the same Node and Express API with the same MongoDB model. I would preserve the API contract and compare app delivery and client behavior. If the new frontend needs a different capability, discuss that requirement separately from database selection.
Why might a single-page app show its layout while the pickup schedule is missing?
The shell and its assets can be served separately from the API and its storage. Check the actual data request, expected media type and response body. Confirm whether the API path reached the backend and how the UI handles a failure. A normal 200 at the HTML route cannot establish current data.
Which public security group ports change when PHP becomes Express?
The public listener and administrative routes depend on the deployment, not the stack name. If the same public HTTPS path remains, the outer access design might be unchanged. The private listener and app-to-data access may change. Identify the network scope and source of each actual connection.
How do you choose between relational and document storage?
Start with the data relationships, updates, reporting, consistency and failure behavior. A relational design can enforce important cross-record constraints and support relational queries. A document design can group data frequently accessed together and validate its structure. Compare representative reads and writes, recovery and operating ownership before selecting the database.
Predict the result from the actual layers
The static browser shell still returns 200 while the JSON route gives 503. Is the pickup lookup available?
Answer and reasoning
The shell can load independently. The intended schedule operation still fails, as the API observation shows. Verify the data path and the UI’s visible recovery behavior.
An unknown API path returns the app’s HTML shell and status 200. Which rule should you inspect?
Answer and reasoning
Check whether the browser fallback caught an API request. Keep the API route and JSON error handling independent of recognized browser navigation paths.
Does a LEMP deployment require exposing a PHP-FPM port to public browsers?
Answer and reasoning
No. The public frontend talks to the PHP worker through the configured private route, often a Unix socket on the same host. Only allow the network access actually required by the architecture.
The old site has a suitable database and stable reporting. Can a new React interface use the current SQL-backed app?
Answer and reasoning
Yes if the existing app provides an appropriate supported API. The frontend component can change independently. Preserve data and validate the actual request and response contract.
A developer picks MongoDB because it is flexible. Which reliability decision remains?
Answer and reasoning
Design the documents, constraints or validation, access and update rules, indexes and backup and restore. Flexible document structure still needs an explicit data model.
Cards for comparing a new stack
Apache and Nginx
Compare named routing, rewrites, static handling and the actual PHP connection. The same supported PHP and SQL app can run in either architecture.
Angular and React
Choose the interface approach and its delivery model. A shared API can support both frontends without changing the data source.
Shell and data contract
Test the browser document and the data API separately. Confirm status, media type and representative useful content.
Private and public connections
List the real listeners and permitted sources for the chosen architecture. Ports associated with application workers and databases usually need controlled private access.
Fit to the team and workflow
Choose components using real requirements, existing code and data, release compatibility and operating responsibility. Keep evidence for recovering the same customer workflow.
Official references
- Apache virtual hosts
- Apache directory override policy
- Nginx FastCGI routing
- Nginx reverse proxy and passed URIs
- Nginx request locations and file fallback
- PHP-FPM pool configuration
- Angular framework and rendering choices
- React components and optional JSX
- React framework and rendering choices
- Express API routing
- Node event loop and blocking operations
- MySQL foreign keys
- MongoDB data modeling and validation
- AWS VPC security group rules
- AWS Systems Manager Session Manager