Chapter 12: Technology Stacks — LAMP, LEMP, MEAN, MERN
Hello friends! This chapter connects LAMP, LEMP, MEAN and MERN to the jobs their components perform. We use a fictional college workshop application to trace browser requests, application decisions and stored records. The overview includes an isolated Nginx/Python/SQLite request-flow lab; the individual lessons develop the named stacks.
नमस्कार मित्रांनो! जॉब पोस्टिंग्समध्ये LAMP, MERN हे शब्द नेहमी दिसतात. या चॅप्टरमध्ये आपण चार स्टॅक्स EC2 वर पूर्ण बनवू – LAMP, LEMP, MEAN आणि MERN. उदाहरण: Amul-style dairy (सॅम्पल डेटा, सरावासाठी) साठी एक छोटं नोट्स ॲप. प्रत्येक स्टॅकचा रिक्वेस्ट फ्लो आधी कागदावर काढा, आणि मग कमांड्स माझ्यासोबत टाइप करा.
नमस्ते दोस्तों! जॉब पोस्टिंग्स में LAMP, MERN जैसे शब्द हमेशा दिखते हैं. इस चैप्टर में हम चार स्टैक्स EC2 पर पूरे बनाएँगे – LAMP, LEMP, MEAN और MERN. उदाहरण: Amul-style dairy (सैंपल डेटा, सिर्फ़ अभ्यास के लिए) के लिए एक छोटा नोट्स ऐप. हर स्टैक का रिक्वेस्ट फ़्लो पहले कागज़ पर बनाओ, और फिर कमांड्स मेरे साथ टाइप करो.
In this chapter
- What a stack is
- LAMP and LEMP install
- MEAN and MERN architecture
- MongoDB from the official repo
- Express + MongoDB API
- React and Angular builds
- Serving SPAs with Nginx
- Comparing the four stacks
Concepts in this chapter
- 12.1What is a "stack" and why does it matter?
- 12.2LAMP stack
- 12.3LEMP stack
- 12.4MEAN and MERN architecture
- 12.5Installing MongoDB from the official repository
- 12.6Common backend API for MEAN and MERN (Node + Express + MongoDB)
- 12.7MERN: React frontend served by Nginx
- 12.8MEAN: Angular frontend served by Nginx
- 12.9Stack comparison summary
Review and practice
Trace one registration across the stack
Read all steps
- Browser interface
The browser sends a relative API request to its own origin. The form is an interface; it does not hold the database credentials or decide that a record was saved.
- Web server and proxy
Nginx receives the browser request and forwards the preserved API path to the separate loopback application listener. Static document requests can succeed while this upstream path fails.
- Application and database
The fixture API checks the supplied values and commits the accepted registration using parameter binding. The browser does not connect directly to the database file.
- Response and readback
The browser displays the creation result and reads saved records. Compare the returned identifier and data with an independent database observation before accepting the result.
1. Understand the jobs before learning the abbreviations
A college wants students to browse workshop dates and reserve a place. One student draws the page, another writes the registration rules, and a third plans the stored records. Their work must meet at clearly defined boundaries. The page needs a way to request a registration. The application needs a way to save it. The saved result needs to become a useful confirmation. A technology stack is the collection of software chosen to perform these cooperating jobs.
The word stack can make beginners imagine a physical pile of four servers. That is not its meaning here. Several components can run on one machine, or they can be distributed across different services and machines. The name tells you some technology choices; it does not describe every deployment detail. Knowing that an application uses MERN does not tell you its instance size, backup policy, authentication method or number of database replicas.
Start by describing the workshop application in ordinary words. A student opens a catalog. The browser displays workshops and a registration form. The submitted request reaches code that validates the selection and applies registration rules. Accepted information is stored. The application returns an identifier and the browser displays the result. Each sentence identifies a responsibility that remains important regardless of the programming language.
This chapter connects those responsibilities to LAMP, LEMP, MEAN and MERN. You will compare their components, trace requests and examine a small working system. The overview lab uses Nginx, Python and SQLite as a compact teaching fixture for the shared request path. It deliberately does not claim to install all four named stacks. The individual lessons cover their specific components and deployment details. Keeping the fixture small lets you observe the boundaries before managing several package ecosystems at once.
A useful learning outcome is being able to explain a failure. If the workshop page appears but registration fails, you should be able to identify the later request and its destination. If an API returns a record but the page stays empty, you should examine the interface and browser behavior. These explanations are more valuable than reciting four expansions without knowing which component executed which part of a request.
2. Map the four stacks to their responsibilities
In this course, LAMP means Linux, Apache, MySQL and PHP. Linux provides the operating-system environment. Apache receives and handles web requests according to configuration. PHP executes the application's server-side code through an appropriate serving arrangement. MySQL stores and retrieves relational data. The letters name different kinds of things: an operating system, a web server, a database system and a programming language with its runtime environment.
LEMP keeps Linux, MySQL and PHP while using Nginx as the web server. The letter E comes from the pronunciation of Nginx, commonly spoken as engine-x. In a typical LEMP arrangement, Nginx serves static resources and sends appropriate PHP requests to PHP-FPM using FastCGI. Nginx does not become a PHP interpreter because a requested filename ends with the PHP extension. The configured handler connects the request to the process that can execute the program.
MEAN means MongoDB, Express, Angular and Node.js. MongoDB is the document database. Express is a web framework used to implement routes and middleware in a Node.js application. Angular is a web framework used for the user interface and related application behavior. Node.js is the JavaScript runtime used by the server application and commonly by development tooling. Angular projects commonly use TypeScript, which is processed into JavaScript for browser execution.
MERN replaces Angular with React while keeping MongoDB, Express and Node.js in the named combination. React is a library for building user interfaces with components. A complete React application also needs decisions about routing, data loading, building and deployment; frameworks can supply an integrated approach. React's official guidance discusses framework choices as well as building from scratch. Calling React a library explains its role, but does not imply that a maintained application must assemble every surrounding tool manually.
| Responsibility | LAMP | LEMP | MEAN | MERN |
|---|---|---|---|---|
| Named operating system | Linux | Linux | Not fixed by the acronym | Not fixed by the acronym |
| Named web server | Apache | Nginx | Additional deployment choice | Additional deployment choice |
| Application execution | PHP serving arrangement | PHP, commonly PHP-FPM | Express running in Node.js | Express running in Node.js |
| Named interface technology | Not fixed by the acronym | Not fixed by the acronym | Angular | React |
| Named database | MySQL | MySQL | MongoDB | MongoDB |
The absence of Nginx from MERN's letters does not prohibit a reverse proxy. The absence of a browser library from LAMP's letters does not prohibit an interactive interface. A PHP application can expose a JSON API, and a React interface can call it. A Node application can use a relational database. These combinations may receive different descriptive names, but they still need the same careful boundary design. Acronyms are shorthand, not compatibility laws.
Likewise, the stack does not dictate a unique security or performance outcome. A badly designed query can be slow in either database family. A missing authorization check remains a defect in any language. A well-maintained application depends on appropriate implementation, supported components, measured capacity and operational practices. Compare the choices against the college's actual requirements instead of assigning a universal winner to an abbreviation.
3. Separate browser work, build work and server work
The browser receives resources and constructs the interface. HTML provides document structure, CSS controls presentation, and JavaScript can respond to interactions and update displayed information. These responsibilities can coexist with server-generated HTML. A page does not stop being a server-rendered application merely because a small script updates a counter. Conversely, a static HTML file can contain JavaScript that later performs a dynamic API operation.
In a server-rendered catalog, application code can query workshop records and create HTML before returning the response. In a client-rendered catalog, the browser can load an initial application shell and request workshop data separately. Frameworks also support combinations, including prerendered content and server rendering followed by browser interaction. Avoid treating these techniques as exclusive identities permanently attached to PHP, React or Angular.
A component is a reusable part of an interface, such as a workshop card or registration form. Components help organize presentation and behavior, but they do not automatically provide access to a database. A browser component normally communicates through an application API or another intentionally exposed service interface. Server-side database credentials must not be bundled into browser code. Anything delivered to the browser can be inspected by the person controlling that browser.
A build process transforms development source into deployment output. It may compile TypeScript, bundle modules, process styles and generate asset filenames. This process often runs with Node.js even when the final browser files are served by Nginx. Therefore finding Node in a build pipeline does not prove that every page request runs a Node server. Distinguish tools used to create an artifact from processes required to serve that artifact.
For a purely static browser build, the deployment output can be HTML, CSS, JavaScript and related assets. For a server-rendered framework, the output can include server code that needs its own runtime. Read the selected framework's deployment mode instead of copying an assumed output-directory name from another project. Serving only the static portion of a server-rendered application can leave important routes or data behavior missing.
Development servers optimize the editing experience with features such as automatic refresh and development diagnostics. Production deployment needs an appropriate serving arrangement, supported configuration and controlled exposure. The fact that a development command prints a URL is not evidence that it is the intended production process. Test the built release using the documented deployment mode and the configuration that will actually be used.
Configuration timing matters too. A value substituted into a browser bundle during a build remains in that generated file until the file is rebuilt or otherwise deliberately changed. Editing a server environment variable later may have no effect on already-generated JavaScript. A runtime configuration mechanism can behave differently, but its values remain public if the browser receives them. Record whether each setting is consumed during build, process startup or a request.
4. Treat the API as an agreement between components
An API defines how one part of the application asks another part to do work. For the workshop catalog, a read request can retrieve available workshops. A registration request can submit a name and a workshop identifier. The agreement includes the path, HTTP method, expected fields, validation rules, status and response format. A frontend developer and backend developer need the same agreement even when they use the same programming language.
Consider a registration response containing an identifier, accepted name and workshop. The interface can display the identifier and then request the saved records. This gives two useful observations: the immediate operation response and a later read. A green message produced before checking the response is not reliable confirmation. Likewise, an HTTP success status with the wrong record is not the intended result. Compare the returned meaning with the user's operation.
A JSON API is not automatically a REST API merely because it uses HTTP. REST describes architectural constraints and resource interactions; JSON is one representation format. For a beginner exercise, accurately describe the implemented HTTP API and its methods. You can learn paths, methods, statuses and representations before claiming that every possible design conforms to a broader architectural style.
Validation belongs on the server even when the browser checks the form. Browser checks help users correct mistakes early, but another client can send requests directly. The application must validate required values and apply its authorization and business rules before changing data. A workshop identifier must refer to an allowed workshop, and a seat reservation system would need a concurrency-safe capacity rule. The small fixture below demonstrates basic validation, without claiming to implement real identity or seat allocation.
Error responses form part of the agreement. A rejected input should differ from an unknown API route and from an unavailable upstream service. The frontend should show that an operation was not confirmed instead of assuming success whenever a request was sent. Avoid displaying internal exception details or secrets to users. Keep useful diagnostic evidence in appropriately protected logs and provide a response that the interface can handle predictably.
5. Connect the frontend and API through a deliberate origin
A web origin is determined by the scheme, host and port. Two local development servers on different ports are different origins, even when both run on the same laptop. This matters because browsers apply rules to cross-origin requests and access to responses. A request that works with a command-line client can still encounter browser restrictions. Diagnose the actual browser message and request path instead of assuming that every network client follows identical rules.
A common arrangement gives the browser one public origin. The web server serves frontend resources and forwards requests under an API path to a private application listener. The browser asks its current origin for the API path, and the proxy makes a separate upstream request. From the browser's perspective, the API request remains same-origin. The proxy and application still need the correct mapping, connectivity and authorization behavior.
In the lab, the browser requests a page on port 18892 and sends a relative registration request under the same origin. Nginx forwards that API path to the application on port 18893. The application knows the full API path, so the proxy configuration preserves it. If the configuration instead removes a prefix, the upstream application must expect the resulting path. A small trailing-slash change in a proxy directive can affect this mapping; inspect the documented semantics and test a concrete request.
CORS, or Cross-Origin Resource Sharing, is a browser-controlled mechanism involving server response headers and, for some requests, a preflight exchange. It can permit browser code from an allowed origin to read a cross-origin response. It is not login, authorization or a general network firewall. Some requests can be sent even when browser code cannot read the response. A non-browser client is not prevented from calling an API merely because a CORS header is absent.
Therefore never use CORS as the only protection for a private operation. Authenticate the intended user or client, authorize the requested action and consider protections appropriate to the credential mechanism, including cross-site request forgery where relevant. A same-origin proxy arrangement simplifies browser routing, but does not automatically supply those controls. The local fixture uses fictional data and intentionally has no real account system.
Be careful with local addresses in frontend configuration. In JavaScript running in a student's browser, localhost refers to that student's computer. It does not mean the EC2 instance that served the page. A hard-coded backend localhost URL can work during development and fail for every remote visitor. A suitable relative API path or deliberately configured public API endpoint avoids that mistaken assumption. Server-side code can use a private upstream address because it executes in a different location.
Frontend configuration must be treated as visible when included in downloaded resources. A public API base path can belong there. A database password cannot. Build tools expose environment values according to their own conventions; adding a public-variable prefix does not protect a secret. Review the generated artifact, not only the source configuration, and keep server credentials on the server through an appropriate protected mechanism.
6. Select a data model from the information and operations
The college has workshops and registrations. In a relational model, workshops can occupy one table and registrations another, with identifiers representing relationships. Appropriate constraints can help preserve valid references and values. Queries can combine the related information. Designing these tables requires understanding what makes one record distinct, which relationships exist and which operations must succeed together.
A document model can represent related fields together in a document. A registration document might include a student display name, workshop identifier and status. Some related data can be embedded, while other information can be referenced. Embedding can make a common read convenient, but duplicating information creates update questions. If a workshop title is copied into many documents, decide whether it represents a historical label or must change whenever the catalog title changes.
MongoDB's flexible model does not remove the need for design. Documents can differ in structure by default, but the application still needs predictable values. MongoDB supports schema validation rules, including field types and allowed values. A date stored inconsistently as text, a number and a date value can make queries and updates difficult. Flexibility should reflect an intentional requirement rather than accidental variation between code paths.
Likewise, relational storage does not mean that application change is impossible or that every field must fit a simplistic fixed example forever. Real applications evolve their schemas and queries. Both relational and document systems require attention to indexes, transactions, consistency, concurrency and recovery. Avoid the slogans that SQL is always slow or that NoSQL has no transactions. Evaluate the specific database features and workload.
For a workshop with limited seats, two simultaneous requests create a concurrency problem. Reading the remaining count and then independently inserting a registration can accept too many students if the operations are not coordinated correctly. Choose a suitable transaction or atomic update design and verify its behavior under concurrent requests. Changing the database brand alone does not repair a flawed sequence of operations.
ORM and ODM libraries help application code interact with stored data through models and abstractions. They can reduce repetitive code, but they do not make query cost, authorization or transaction boundaries disappear. Learn the underlying operation well enough to interpret errors and inspect generated requests. An object in process memory is not a durable record until the intended database operation has completed successfully.
Database access also has a network and identity boundary. The browser should not receive the server's database credentials. The application connects through a deliberately configured path using appropriate permissions. A database listener should not be exposed broadly merely to make an initial connection succeed. In a real cloud design, verify routes, security rules, authentication, encryption and the exact operation required by the application.
7. Compare complete operating choices
Suppose the college already has a maintained PHP application and administrators who understand its database and web-server configuration. Moving to a different stack solely because another acronym is fashionable creates migration and maintenance work without an established benefit. On the other hand, a new requirement for a complex interactive interface may justify evaluating a frontend framework. Start with the requirement and existing capabilities, then compare the cost of satisfying it.
Evaluate the team's ability to build, test, update and diagnose the chosen components. A familiar language across browser and server can help some teams, but the execution environments still differ. Browser code cannot use server filesystem access as though it were running in Node.js. Shared syntax does not remove the network boundary, asynchronous behavior or security responsibilities of an API.
Account for the entire lifecycle. Include supported runtime versions, dependency compatibility, package installation, builds, release artifacts, monitoring, backups and recovery. A package requiring a newer runtime can break a build even when the application source has not changed. Preserve a tested dependency resolution and rebuild in a clean environment. Maintenance should deliberately evaluate updates rather than allowing an accidental resolver change to become a production experiment.
On one machine, deployment can be easier to understand, but processes share that machine's capacity and failure boundary. Separating the frontend, application and database can allow different scaling and management choices while adding network dependencies and operational complexity. A logical layer is a responsibility; a deployment tier describes where components run. Three logical responsibilities do not require three EC2 instances for every classroom project.
Write a decision record with alternatives and evidence. For the college, it might compare editorial needs, registration complexity, team skills, data relationships and recovery expectations. Record the chosen approach and the condition that would trigger reevaluation. This produces a useful engineering explanation rather than a ranking based on unsupported claims that one stack is always faster, safer or cheaper.
Plan browser navigation and asset paths
A single-page application can change its visible route using browser-side navigation. Clicking a workshop link after the application has loaded may therefore work without a fresh document request. Refreshing that same nested URL sends a new request to the server. A purely client-routed deployment needs a suitable document fallback for its application routes, while API routes and missing assets still need their own correct responses. Test both navigation and direct refresh.
Do not send the HTML shell for every missing JavaScript file. The browser expects executable JavaScript at an asset URL, and an HTML response can cause a parsing or media-type error. Distinguish a valid client route from a missing build artifact. Inspect the requested URL and response type, especially when the application is deployed beneath a path prefix rather than the origin root.
Versioned asset names and cache rules also belong to the release plan. A new HTML document must reference available assets, while visitors with an older document may still request older asset names. Removing old files immediately can break those visitors. Choose a retention and cache strategy appropriate to the build output and deployment process. A successful home-page request does not test every previously cached combination.
8. Lab: follow a browser registration through a proxy
This exercise builds a small observable request path: browser interface, Nginx, a Python HTTP API and a SQLite file. The particular languages differ from the four named stacks, while the separation of responsibilities is the same idea you are learning. It is a local teaching fixture with fictional names, basic validation and no authentication. Do not expose it to the internet or treat it as a production registration system.
Use a Linux learning machine with Nginx, Python with SQLite support and curl already available. The checked Nginx version is 1.28.0. The exercise starts a separate unprivileged Nginx instance with its own configuration, process identifier, logs and temporary directories. It does not edit the machine's system website configuration or use system-wide service commands. Both listeners bind to loopback. If you use a remote learning machine, run the command-line checks there; browser interaction requires a deliberately configured local forwarding arrangement or a browser on that machine.
First confirm that the two chosen ports are unused. The setup checks ports 18892 and 18893 before creating the exercise directory. If either is occupied, stop and choose different unused ports throughout the exercise. Do not terminate an unrelated process. Use one Bash terminal for the displayed commands so the exercise variables and recorded process identifier remain available.
command -v nginx
python3 - <<'PYPORT'
import socket, sqlite3
for port in (18892, 18893):
with socket.socket() as probe:
probe.bind(('127.0.0.1', port))
print('Both fixture ports are available')
PYPORT
stack_lab=$(mktemp -d /tmp/workshop-stack.XXXXXXXX) || exit 1
mkdir "$stack_lab/public"
printf 'Stack lab directory: %s\n' "$stack_lab"
The public subdirectory will contain only the browser document. The API code and database remain outside it. This is an important boundary: the web server must not offer a database download just because the file belongs to the same project. The fixture's directory layout demonstrates this distinction without relying on a filename that happens to look secret.
Create the API and browser page
The API below accepts only the documented paths. Accepted registrations are inserted with parameter binding and committed before the creation response is sent. The read route retrieves the saved records in identifier order. Unknown API paths return a JSON error. Input rejection happens before insertion. Each successful repeated submission creates another record; this example does not implement duplicate suppression or a capacity reservation policy.
cat > "$stack_lab/api.py" <<'PYAPI'
import json
import os
import sqlite3
from contextlib import closing
from http.server import BaseHTTPRequestHandler, HTTPServer
DB = os.environ['STACK_DATABASE']
WORKSHOPS = {'robotics': 'Robotics', 'solar': 'Solar energy'}
with closing(sqlite3.connect(DB)) as con:
con.execute('CREATE TABLE IF NOT EXISTS registrations (id INTEGER PRIMARY KEY, name TEXT NOT NULL, workshop TEXT NOT NULL)')
con.commit()
class API(BaseHTTPRequestHandler):
def reply(self, status, value):
body = json.dumps(value).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.send_header('Cache-Control', 'no-store')
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == '/api/workshops':
self.reply(200, {'workshops': WORKSHOPS})
elif self.path == '/api/registrations':
with closing(sqlite3.connect(DB)) as con:
rows = con.execute('SELECT id, name, workshop FROM registrations ORDER BY id').fetchall()
self.reply(200, {'registrations': [dict(zip(['id', 'name', 'workshop'], row)) for row in rows]})
else:
self.reply(404, {'error': 'API route not found'})
def do_POST(self):
if self.path != '/api/registrations':
self.reply(404, {'error': 'API route not found'})
return
if self.headers.get('Content-Type', '').split(';')[0].strip() != 'application/json':
self.reply(415, {'error': 'Send JSON'})
return
try:
size = int(self.headers.get('Content-Length', '0'))
if not 0 < size <= 1024:
self.reply(413, {'error': 'Body must contain 1 to 1024 bytes'})
return
value = json.loads(self.rfile.read(size))
except (ValueError, UnicodeDecodeError):
self.reply(400, {'error': 'Invalid JSON'})
return
if not isinstance(value, dict):
self.reply(400, {'error': 'Expected a JSON object'})
return
name, workshop = value.get('name'), value.get('workshop')
if not isinstance(name, str) or not 1 <= len(name.strip()) <= 60 or not isinstance(workshop, str) or workshop not in WORKSHOPS:
self.reply(400, {'error': 'Use a name of 1 to 60 characters and a listed workshop'})
return
with closing(sqlite3.connect(DB)) as con:
row = con.execute('INSERT INTO registrations(name, workshop) VALUES (?, ?)', (name.strip(), workshop))
con.commit()
number = row.lastrowid
self.reply(201, {'id': number, 'name': name.strip(), 'workshop': workshop})
HTTPServer(('127.0.0.1', 18893), API).serve_forever()
PYAPI
Read the code in small sections. The initial database statement creates the fixture table if it is absent. The response helper writes the status, media type, length and JSON body. The read handler distinguishes catalog and registration requests. The write handler checks path, media type, body size, JSON structure and permitted values before executing the insert. Python's built-in HTTP server keeps the example small; it is not the recommended production application server for a public service.
The browser page uses relative API paths. It does not contain the upstream port or a database path. Its submit handler waits for the response, checks the status and only then reports an accepted registration. A later read displays the stored records. The button is disabled during one submission to reduce accidental repeated clicks, but that interface behavior is not a server-side idempotency guarantee.
cat > "$stack_lab/public/index.html" <<'HTMLPAGE'
<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Workshop stack lab</title><style>body{font:18px/1.6 system-ui;max-width:42rem;margin:2rem auto;padding:0 1rem}label,input,select,button{display:block;margin:.5rem 0}input,select,button{font:inherit;max-width:100%}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#f0f4f8;padding:1rem}button{padding:.4rem 1rem}</style>
<h1>Workshop stack lab</h1><p>Use fictional names only. This local exercise has no login or public deployment.</p>
<form id="registration"><label for="student">Fictional student name</label><input id="student" name="student" maxlength="60" required><label for="workshop">Workshop</label><select id="workshop"><option value="robotics">Robotics</option><option value="solar">Solar energy</option></select><button type="submit">Register demo student</button></form>
<p id="result" role="status">No submission yet.</p><h2>Saved registrations</h2><button id="refresh" type="button">Read saved registrations</button><pre id="saved">Press the read button.</pre>
<script>
const result = document.querySelector('#result');
const saved = document.querySelector('#saved');
async function loadSaved() {
try {
const response = await fetch('/api/registrations');
const body = await response.json();
if (!response.ok) throw new Error(body.error || 'Request failed');
saved.textContent = JSON.stringify(body, null, 2);
} catch (error) { saved.textContent = 'Could not read records: ' + error.message; }
}
document.querySelector('#refresh').addEventListener('click', loadSaved);
document.querySelector('#registration').addEventListener('submit', async (event) => {
event.preventDefault();
const button = event.currentTarget.querySelector('button');
button.disabled = true;
result.textContent = 'Submitting...';
try {
const response = await fetch('/api/registrations', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({name:document.querySelector('#student').value, workshop:document.querySelector('#workshop').value})});
const body = await response.json();
if (!response.ok) throw new Error('HTTP ' + response.status + ': ' + (body.error || 'Request failed'));
result.textContent = 'HTTP ' + response.status + ': saved registration ' + body.id + ' for ' + body.name;
await loadSaved();
} catch (error) { result.textContent = 'Registration not confirmed: ' + error.message; }
finally { button.disabled = false; }
});
</script></html>
HTMLPAGE
All displayed names are assigned as text rather than inserted as executable markup. This matters because a student's input is data, even if it contains characters that resemble HTML. The form's required and length checks improve the editing experience. They do not replace the API checks, which also apply to requests sent without the form. Use invented names only and keep the page restricted to the local exercise.
Configure the separate Nginx instance
The configuration gives API requests a distinct location and forwards them to port 18893 without replacing their path. Other requests are mapped to public files and return not found when no matching file exists. There is no blanket single-page-app fallback here. The fixture has one ordinary HTML page; sending that page for an unknown API route would hide a routing error behind an apparently successful HTML response.
cat > "$stack_lab/nginx.conf" <<EOF
pid $stack_lab/nginx.pid;
error_log $stack_lab/error.log notice;
worker_processes 1;
events { worker_connections 64; }
http {
types { text/html html; }
default_type application/octet-stream;
access_log $stack_lab/access.log;
client_body_temp_path $stack_lab/client_temp;
proxy_temp_path $stack_lab/proxy_temp;
fastcgi_temp_path $stack_lab/fastcgi_temp;
uwsgi_temp_path $stack_lab/uwsgi_temp;
scgi_temp_path $stack_lab/scgi_temp;
server {
listen 127.0.0.1:18892;
server_name localhost;
root $stack_lab/public;
index index.html;
location /api/ {
proxy_pass http://127.0.0.1:18893;
proxy_connect_timeout 2s;
proxy_read_timeout 3s;
}
location / { try_files \$uri \$uri/ =404; }
}
}
EOF
The operating system sees separate processes even though the browser sees one origin. Nginx receives the browser connection on port 18892 and creates an upstream connection when the API location is selected. The application receives the forwarded path and performs its database operation. Its response then travels back through Nginx. The access and API logs let you correlate those parts of one operation.
Start the fixture and compare the responses
Start the API in the background and record its process identifier, then test and start the private Nginx configuration. If either component reports an error, inspect its own log and stop before continuing. The application may need a brief moment to bind its listener. An initial upstream failure immediately after startup should be investigated against the API log and retried after startup is confirmed; it should not be hidden by opening public network access.
STACK_DATABASE="$stack_lab/data.sqlite3" python3 "$stack_lab/api.py" > "$stack_lab/api.log" 2>&1 &
stack_api_pid=$!
nginx -e "$stack_lab/error.log" -p "$stack_lab/" -c "$stack_lab/nginx.conf" -t
nginx -e "$stack_lab/error.log" -p "$stack_lab/" -c "$stack_lab/nginx.conf"
Run the read and submission requests below. Expect the document to return success, the first registration read to contain an empty list, the valid submission to return created, and the next read to contain the returned registration identifier and values. The invalid workshop request should be rejected. The unknown API route should return a JSON not-found response, while the attempted database-file URL should not expose the private file.
curl -i http://127.0.0.1:18892/
curl -i http://127.0.0.1:18892/api/registrations
curl -i -H 'Content-Type: application/json' --data '{"name":"Asha Demo","workshop":"robotics"}' http://127.0.0.1:18892/api/registrations
curl -i http://127.0.0.1:18892/api/registrations
curl -i -H 'Content-Type: application/json' --data '{"name":"Test Demo","workshop":"unknown"}' http://127.0.0.1:18892/api/registrations
curl -i http://127.0.0.1:18892/api/missing
curl -i http://127.0.0.1:18892/data.sqlite3
If you run the valid submission more than once, the identifiers and record count increase. Compare the actual inserted identifier instead of assuming it always remains one. The API's validation protects the listed fields, but the exercise makes no claim about real users, authorization, duplicate registrations, seat limits or malicious public traffic. Those are separate application requirements that need their own implementation and tests.
Now open the loopback page in a browser on the learning machine and submit a different fictional name. The confirmation should show a created status and identifier, followed by the updated record list. Read the list again and compare it with the command-line result. Both clients should observe the same saved information because they call the same application and database path. A browser screenshot is helpful evidence only when it agrees with the response and saved result.
Observe a partial failure and clean up
Stop only the API process created by this exercise using its recorded identifier. Repeat the page request and an API read. The static document should remain available, while Nginx cannot connect to its upstream and returns a bad-gateway response. This demonstrates that a loaded interface does not establish backend health. The web-server error log should identify an upstream connection problem for the API request.
kill "$stack_api_pid"
wait "$stack_api_pid" 2>/dev/null || true
curl -i http://127.0.0.1:18892/
curl -i http://127.0.0.1:18892/api/registrations
The browser form may still be visible during this failure because Nginx can serve the HTML. Submitting it should show that registration was not confirmed. A failed response does not establish whether every conceivable operation in a real distributed system was rolled back; this controlled case stops the upstream before the request. In a real timeout or connection-loss incident, use an appropriate operation identifier and reconciliation procedure before retrying blindly.
Finally, stop the exercise's Nginx instance using its own prefix and configuration. Wait for the process-identifier file to disappear before considering shutdown complete. Review the unique directory printed at setup and save any observations you need. Remove only that exercise directory when finished. No system web-server service needs to be restarted, and no existing website needs to be edited.
nginx -e "$stack_lab/error.log" -p "$stack_lab/" -c "$stack_lab/nginx.conf" -s quit
9. Tasks that connect the architecture to evidence
- Draw two versions of the same application. Use a PHP-and-MySQL approach for one drawing and an Express-and-MongoDB approach for the other. Mark where the catalog HTML is generated, where validation executes and where records are stored. Completion means you can trace one registration in both drawings without treating the browser as a database client or mistaking a programming language for a separate machine.
- Inspect the fixture's boundary. List which files are inside the public directory and which are outside it. Explain the response to the attempted database-file URL. Then identify the configured upstream port and the exact path it receives. Completion means your explanation accounts for both a normal API response and the JSON error for an unknown API route.
- Compare three observations. Record the browser confirmation, command-line read and independent database row for one synthetic registration. Include the returned identifier in all three where applicable. Explain what each observation establishes and what remains untested, including authentication and concurrent seat allocation. Completion means your report distinguishes a visible message from a persisted operation.
- Review a faulty deployment plan. A teammate proposes placing a database password in frontend build configuration, running the development server publicly and using CORS as the only access control. Rewrite the plan by assigning each concern to an appropriate component. Completion means you explain where the secret belongs, which production serving arrangement is required and which application authorization checks are still needed.
- Choose a stack for a defined requirement. Compare two realistic choices for a workshop catalog with a small editorial team and a custom registration rule. Include team skills, existing software, data modeling, update responsibility and recovery. State what evidence would change your decision. Completion means another student can understand the tradeoff without accepting unsupported claims about one universally best stack.
10. Interview questions and model answers
Does MERN require four servers?
No. Its letters identify technologies, not a machine count. Several components can run on one machine, or deployment can distribute them. Explain the logical responsibilities first, then describe capacity, isolation and availability requirements that influence placement. Four names alone cannot justify four instances.
Can a React frontend use a PHP API or a relational database?
It can call a suitably designed PHP HTTP API. That server application can use a relational database. React describes interface construction and does not require MongoDB. Keep database credentials and privileged data access on the server. A named stack is a common combination rather than a rule preventing other compatible combinations.
What is the difference between Node.js and Express?
Node.js is the runtime that executes server-side JavaScript and provides runtime APIs. Express is a framework used within a Node.js application for routes, middleware and related web behavior. Installing Node does not automatically create the project's routes. Installing Express does not replace the runtime required to execute it.
The page loads but an API call returns 502. Which component would you examine?
Identify the component that produced the response, then inspect its upstream connection and the intended application's listener and logs. In this fixture, Nginx remains able to serve HTML after the API is stopped, but reports an upstream connection failure for the API path. Do not infer that the database caused the failure before establishing whether the application was reached.
Is MongoDB flexible schema the same as having no schema?
No. The application still expects meaningful fields and types, and MongoDB can enforce validation rules. Flexible document structure allows intentional variation, while data modeling determines embedding, references and query patterns. Without deliberate design, inconsistent fields can make reads and updates unreliable.
Why can frontend configuration changes require another build?
A build tool may replace configuration references with literal values in generated browser files. Changing a server environment variable afterward does not rewrite those files. Determine when the setting is consumed and deploy the corresponding updated artifact. Any value included in a public browser bundle remains visible regardless of its original environment-variable name.
Does same-origin API routing eliminate the need for security checks?
No. It changes how the browser reaches the API and can simplify cross-origin behavior. The application still needs authentication, authorization, validation and protections appropriate to its credential and request design. The proxy arrangement cannot decide whether a particular student is allowed to change another student's registration.
11. Quiz: explain the boundary behind each answer
Quiz 1: Nginx serves a JavaScript bundle produced with Node. Must Node run for every static-file request?
No. Build-time tooling and request-time serving are different roles. A static build can be served by Nginx without a Node process for those files. A server-rendered framework can require a Node runtime, so inspect the actual deployment mode before deciding.
Quiz 2: A browser API URL contains localhost. Whose machine does it identify?
It identifies the machine running that browser, not automatically the EC2 server that delivered the page. A remote visitor would therefore target their own machine. Use the intended public endpoint or relative same-origin path for browser requests.
Quiz 3: Can a PHP application return JSON instead of a complete HTML page?
Yes. The language does not force one response representation or interaction pattern. PHP can implement an HTTP API, and browser code can use its response. Design the request and response contract explicitly.
Quiz 4: An unknown API path receives the application's HTML shell with status 200. Is that a useful API success?
No. The response does not match the API contract. A broad frontend fallback may have intercepted the request. Keep API routing distinct and verify both status and media type so a missing route is not disguised as a successful page response.
Quiz 5: A direct command-line client calls an API without an allowed browser origin. Does missing CORS permission necessarily block it?
No. CORS is enforced by browsers for cross-origin behavior, not as universal API authorization. The server must apply its own identity and permission checks to protected operations regardless of the client's ability to send an origin header.
12. Revision cards
Stack
A set of cooperating technologies. Its acronym is a shorthand for choices, not a complete architecture or machine count.
Runtime
The environment that executes application code. Distinguish it from a framework and from the browser's execution environment.
Build artifact
The reviewed output selected for deployment. Know whether it contains static files, server code or both.
API contract
The methods, paths, fields and responses on which clients and servers agree. Errors belong to the contract too.
Origin
The scheme, host and port that define a browser origin. Separate internal processes can still serve one public origin through a proxy.
Data model
The chosen organization and relationships of stored information. Both tables and documents need intentional rules and query planning.
Primary sources
- React components and interface behavior
- React framework and build choices
- Angular framework overview
- Angular deployment modes and configuration
- Node.js runtime introduction
- Express application and routes
- MongoDB data modeling
- MongoDB schema validation
- MySQL InnoDB transactions and locking
- Nginx proxy path mapping
- Nginx file selection
- PHP FastCGI processing
- Browser CORS behavior
- Browser Fetch API and response handling
- Vite public environment values and build-time replacement
- Python HTTP teaching server and limitations
- SQLite connections, parameters and transactions
Stacks in the real world
A stack is a set of cooperating technologies. LAMP names Linux, Apache, MySQL and PHP; LEMP replaces Apache with Nginx. MEAN and MERN name MongoDB, Express, Angular or React, and Node.js. These components have different responsibilities. The expanded lesson explains their boundaries, deployment choices and tradeoffs.
Other combinations include Spring Boot with React and PostgreSQL, ASP.NET Core with Angular and SQL Server, Django or Rails with PostgreSQL, and Go with a selected data store. Deployment placement and request handling depend on the application. Plan an appropriate public entry point and restrict backend and database access deliberately; a technology name does not enforce that design.
After this part you will be able to
- Explain LAMP, LEMP, MEAN and MERN with a diagram.
- Install MongoDB from the official repository.
- Build and serve React and Angular apps with nginx.
- Choose a stack based on the team and the data.
Everyday analogy: different cuisines, same kitchen rules. Whatever you cook, the gas, the fridge and the cleaning rules stay the same.
Key terms
- Stack: A set of technologies used together.
- SPA: A single-page application updates views through browser-side behavior. React and Angular also support other rendering and deployment approaches.
- REST API: An interface designed around REST architectural constraints. HTTP and JSON alone do not establish that a design is RESTful.
- try_files: An Nginx directive that checks file candidates and can select a configured fallback; API and asset paths need deliberate handling.
- bindIp: The MongoDB setting for which addresses it listens on.
- ODM / ORM: Libraries that map objects to documents or tables, such as Mongoose, Hibernate, EF Core and Django ORM.
Mini case study
Suppose we are a junior cloud engineer at a Bengaluru e-commerce startup (sample data). The team runs a PHP admin, a Node.js storefront API and a Python report job on two EC2 instances. Using this chapter, you write a one-page runbook: which service listens where, how to test and reload each one, which logs to read, and which ports are public (only 80 and 443, plus 22 from the office IP). New team members can then fix most problems on their own.
Practice Tasks
Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.
About this scenarioKolhapuri Chappal Co is a footwear business in Kolhapur. Sachin Mane looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.
0 / 12
Easy Install a package on Ubuntu
Ubuntu uses apt. Package names differ: on Ubuntu Apache is apache2.
Install the apache2 package on Ubuntu without being asked to confirm.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Install a package on Amazon Linux
dnf is the package manager on Amazon Linux 2023. -y answers yes for you.
Install the httpd package on Amazon Linux 2023 without being asked to confirm.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Restart a service after a change
For this browser exercise, practice the restart command. In a real application, determine how the particular setting is applied and verify the resulting behavior.
Restart the nginx service.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Check if a service is running
When a site is down, first check whether the web server process is running.
Show the status of the httpd service.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Log in to MariaDB
The mysql client lets you run SQL on the database server.
Open the MariaDB client as user root and ask for the password.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Biggest orders first
Querying the database is daily work after you set up RDS.
Show order id and amount, biggest amount first.
Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).
- Find the table the task is about (see the table list above the box).
- Write the SQL statement step by step: what, from where, which rows.
- End the statement with ;
- Click Check answer. Your query runs on a practice copy of the table.
Easy Filter customers by city
Querying the database is daily work after you set up RDS.
List the names of customers in Pune.
Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).
- Find the table the task is about (see the table list above the box).
- Write the SQL statement step by step: what, from where, which rows.
- End the statement with ;
- Click Check answer. Your query runs on a practice copy of the table.
Medium Start a service now and at boot
enable makes it start after reboot; --now also starts it right away.
Enable the nginx service and start it immediately, in one command.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Medium Remove small orders
Querying the database is daily work after you set up RDS.
Delete orders with amount below 200.
Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).
- Find the table the task is about (see the table list above the box).
- Write the SQL statement step by step: what, from where, which rows.
- End the statement with ;
- Click Check answer. Your query runs on a practice copy of the table.
Medium Orders with customer names
Querying the database is daily work after you set up RDS.
Show each customer name with each order amount.
Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).
- Find the table the task is about (see the table list above the box).
- Write the SQL statement step by step: what, from where, which rows.
- End the statement with ;
- Click Check answer. Your query runs on a practice copy of the table.
Hard Sales per customer
Querying the database is daily work after you set up RDS.
Show customer_id and total amount per customer, only where total is above 1000.
Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).
- Find the table the task is about (see the table list above the box).
- Write the SQL statement step by step: what, from where, which rows.
- End the statement with ;
- Click Check answer. Your query runs on a practice copy of the table.
Hard Customers with no orders
Querying the database is daily work after you set up RDS.
List names of customers who have never ordered.
Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).
- Find the table the task is about (see the table list above the box).
- Write the SQL statement step by step: what, from where, which rows.
- End the statement with ;
- Click Check answer. Your query runs on a practice copy of the table.