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

AWS Cloud

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

Hello friends! The static site is live; now real applications – login, forms and data. In this chapter we connect a database, an app server and a web server on one EC2 instance. Example: the customer list of a dairy brand like Amul (sample data, for practice) – in PHP, Python and Node. Type every command with me.

In this chapter

  • Dynamic sites and 3 tiers
  • Install MySQL / MariaDB
  • One database user per app
  • PHP with PHP-FPM
  • Flask with Gunicorn
  • Express with pm2
  • Reverse proxy to the app
  • Troubleshooting 502 / 504

Concepts in this chapter

  1. 10.1Why and what
  2. 10.2Installing MySQL / MariaDB
  3. 10.3PHP with MySQL
  4. 10.4Python (Flask) with MySQL
  5. 10.5Node.js (Express) with MySQL
  6. 10.6Reverse proxy to the Python/Node app
  7. 10.7Troubleshooting dynamic sites

Review and practice

  1. ★Common Mistakes I See Students Make
  2. ★Interview Questions
  3. ★Practice Questions and Lab Exercises

Follow a registration into persistent data

Follow a registration into persistent dataSubmitted requestName and workshop choiceApplication decisionValidate and authorizeDatabase transactionStore and commit the resultVerified outcomeRead the saved registration
Read all steps
  1. Submitted request

    The browser sends the operation and its values. A loaded form does not demonstrate that this later submission path works.

  2. Application decision

    The application interprets the request and applies the operation’s rules. Parameter binding, validation and authorization have distinct responsibilities.

  3. Database transaction

    The application sends the values through the database driver and commits the accepted operation. A pending insert is different from a completed registration.

  4. Verified outcome

    Compare the response identifier with a subsequent read. In the local exercise the committed record survives an ordinary process restart; broader recovery needs separate tests.

Turn a timetable into a registration service

The workshop timetable is a useful static document. It tells students where to go and when the session begins. The next request is different: students should reserve a place, see a confirmation and let the coordinator view the accepted registrations. Copying another HTML file cannot by itself provide a shared, persistent registration record. The service needs rules that run when a request arrives and storage that preserves the result.

A dynamic application produces behavior from inputs, application logic and relevant state. The response might be a generated HTML page, a JSON document or another format. It does not have to look visually animated. A plain registration confirmation can be dynamic, while a prepared page with elaborate browser animations can still be delivered as static files. Describe where the behavior is computed rather than judging the appearance.

Our continuous example accepts a fictional student name and a workshop choice, stores an accepted record and returns a confirmation. We will explain how PHP, Python and Node.js can implement that responsibility. The overview's executable exercise uses Python's standard library and a private SQLite file so you can observe a complete request and saved result without provisioning a database server. The later language lessons add their specific MySQL integrations.

SQLite in that exercise is an embedded database, not a simulated MySQL service. Its connection, concurrency and administration differ from MySQL. The shared learning is the request flow, input validation, parameter binding, commit and persistence. We will label the difference explicitly and avoid treating a successful local demonstration as evidence that a public production deployment is ready.

Trace one submission across separate responsibilities

A student first requests the registration form. The browser can receive prepared HTML and CSS from a web server. When the student submits the form, the browser makes another request containing the chosen values. The application must interpret that request, verify the values and decide what operation is allowed. The first page loading successfully does not prove the later submission can reach the database.

The public web endpoint can terminate TLS, select the requested site, serve static files and pass application requests to a configured handler. In an HTTP reverse-proxy arrangement, it makes a separate connection to an HTTP-speaking upstream. The upstream address and port belong to that second connection. The student's public URL does not need to expose the internal application port.

The application runs the workshop rules. It might reject an empty name, check that the workshop exists or prevent duplicate enrollment. It then uses a database driver to request the appropriate database operation. The driver translates the application call into the database protocol or embedded API. The browser should not receive the application's database password or directly run unrestricted database commands.

After a successful database operation is committed, the application constructs the response. It might return a registration identifier and the accepted workshop. The proxy passes the response back to the browser. The useful outcome is the durable accepted registration, not merely a message saying “success.” Verification should compare the response with a subsequent read of the saved record.

Draw the arrows with their protocols. Browser to public endpoint may be HTTPS. Proxy to a Flask or Express deployment may be HTTP on a local port. Nginx to PHP-FPM uses FastCGI. Application to MySQL uses the database connection. Naming these interfaces prevents a common error: assuming every process that listens on a port understands the same kind of request.

Separate logical tiers from physical machines

The presentation, application and data responsibilities are often described as logical tiers. During learning, a web server, application process and database server can run on one assigned machine. In another design, the database is managed separately and the application runs on several machines. The number of boxes in a logical diagram does not automatically tell you the number of virtual machines.

Putting services on one host makes a small exercise easier to inspect, but it also shares resources and failure boundaries. A full disk or host outage can affect several responsibilities together. Separating components can improve operational choices, but it adds network, identity and maintenance decisions. More machines are not automatically a better learning setup or a complete availability design.

Loopback is useful for a same-host teaching arrangement. A process bound to 127.0.0.1 is reached from that network namespace, not from an arbitrary remote student's laptop. If the proxy and application move into different containers or hosts, loopback no longer identifies the other component. Update the diagram and connection settings to reflect the actual placement rather than copying a local address blindly.

Write one row per process: executable, identity, configuration, listener, working directory, writable data and logs. Then add a row for the database and its persistence location. This inventory explains which component should answer each check. It also makes a later migration easier because you can identify which assumptions depended on sharing one machine.

Recognize the runtime and serving interface in each language

PHP is a language runtime. PHP-FPM manages PHP worker processes and exposes a FastCGI interface. A web server configured for this arrangement sends the appropriate FastCGI parameters, including the intended script mapping. An ordinary HTTP proxy directive aimed at a FastCGI socket does not become correct just because the socket is reachable. The protocol and script path must both match the integration.

Flask is a Python web framework. Its development server is useful while developing locally, but production serving uses a suitable WSGI server or hosting platform. WSGI defines an interface between a Python application and a server. A server such as Gunicorn can run compatible workers and accept requests for the application. The import target, environment and dependencies must refer to the actual application you deployed.

Node.js is a JavaScript runtime, and Express is a web framework running within that runtime. The application can create an HTTP listener. A process manager such as PM2 can supervise that process, collect logs and support lifecycle management. It does not supply the workshop's registration rules or replace Express. Similarly, systemd can supervise a process without becoming the application itself.

The three implementations can share a behavioral contract: the same valid input is accepted, invalid input is rejected, data is stored correctly and responses have the intended meaning. The code and hosting integration differ. Learning one implementation gives you a useful comparison model, but changing language or database is more than renaming a port or replacing a few commands.

ImplementationApplication responsibilityTypical integration to inspect
PHP with PHP-FPMPHP code validates and queries through a driverFastCGI endpoint, pool identity and script mapping
Flask with a WSGI serverPython routes implement the registration behaviorApplication import, worker configuration and HTTP upstream
Express with Node.jsJavaScript routes implement the registration behaviorHTTP listener, dependency versions and process supervision

Model the record before writing the form

Begin with the information that must survive. A workshop has an identifier, title and perhaps a capacity. A registration has its own identifier, a student reference and a workshop reference. The identifiers connect records without relying on repeated display text. Two workshops might have similar titles, so a title alone is a weak way to decide which event a student selected.

A database schema describes the tables, columns, types and constraints. Constraints can enforce rules such as required values, uniqueness and valid relationships. Application validation gives helpful feedback before a database operation, while database constraints protect the stored model when several code paths write to it. Use both according to the actual rule instead of assuming the browser form is the only writer.

Do not put real student details in a disposable teaching exercise. Our lab uses a fictional name and a simple workshop label. The purpose is to observe persistence and query behavior, not to collect personal information. A real registration product needs a clear data purpose, access rules, retention and suitable handling of the actual information it stores.

Plan the lifecycle of the data separately from the application release. Replacing code should not accidentally delete the registration database. On a server-based deployment, identify the database's storage and backup procedure. On an embedded local exercise, identify the exact database file. A program can create a fresh empty file in the wrong working directory and appear to have “lost” records while the original file still exists elsewhere.

Validate input and authorize the operation independently

Validation asks whether a value meets the operation's requirements. A name may need a reasonable length, and a workshop selection must match an allowed workshop. Parse the actual input type and reject unsupported shapes. If the endpoint expects a JSON object, a list or a number is not a valid object just because it is valid JSON. A clear error response helps a learner locate the mismatch.

Authentication establishes the user's identity. Authorization decides whether that identity may perform the operation on the relevant resource. A student can submit a valid name without being allowed to view every registration. An administrator route needs an authorization rule, not only a check that a field is nonempty. A hidden button in the browser is not an access-control boundary.

Browser-side checks improve feedback but cannot be the only validation. A caller can send a request without using your form. The server must apply the required checks again. Likewise, a selected workshop identifier supplied by the browser is a request to be evaluated, not proof that the caller has access to that workshop or that a seat is still available.

For a real browser application, session handling, cross-site request protections and output handling also matter. A cookie-based authenticated action can need CSRF defenses. Text rendered into HTML must be encoded for its context so a stored value does not become unintended markup or script. Parameterized SQL protects query construction; it does not automatically protect HTML rendering or decide who may see a record.

Keep SQL instructions separate from submitted values

A database query has a structure and values. The structure might insert a registration into two named columns. The values are the student's submitted name and chosen workshop. Parameter binding sends those values separately from the query structure through the driver's supported interface. This prevents the values from being treated as new SQL instructions in that operation.

Do not build a SQL statement by joining untrusted text into quoted fragments. A name containing an apostrophe should remain an ordinary value. Trying to manually remove certain characters is neither a good data policy nor a replacement for the driver's binding mechanism. A correctly parameterized query can store a name with punctuation while keeping the statement's structure fixed.

Placeholder syntax depends on the driver. PHP's mysqli prepared statements use question-mark placeholders with binding. MySQL Connector/Python uses its documented parameter conventions, commonly percent-s placeholders passed with a separate sequence. Other Node.js drivers have their own execute or query interfaces. Read the actual library documentation; do not assume a placeholder copied from one API is valid in another.

Parameters usually represent data values, not arbitrary table names or sort keywords. If the application offers a small choice of sort orders, map that choice to a reviewed set of query structures. Do not put a raw user-supplied column expression into SQL and describe it as protected merely because other values use parameters. The boundary between structure and data must remain deliberate.

Make a complete registration the unit of success

Suppose only one workshop seat remains. A registration operation may need to reserve capacity and insert the student's record. If those changes belong together, a transaction can group them so the intended set is committed as one unit. If an error prevents completion, rollback can discard the transaction's uncommitted changes. The database engine and statements must support the intended transactional behavior.

A transaction alone does not automatically prevent every race. Two requests can both read “one seat available” unless the design uses suitable locking, conditional updates, constraints or isolation behavior. A robust capacity rule must be correct under concurrent requests. Explain the exact invariant, such as accepted registrations never exceeding capacity, then choose a database operation that preserves it.

Commit is the point at which the application asks the database to finalize the transaction under its durability behavior. It should not send an unconditional success message before knowing the relevant operation succeeded. If a client times out after the database committed, retrying a create operation can still create a duplicate unless the application has a suitable uniqueness or idempotency design.

Our first lab inserts a simple record and commits it; it does not implement capacity allocation or authentication. An optional second exercise demonstrates rollback by inserting a temporary record and then rolling it back before counting again. This gives you observable evidence for the basic distinction without claiming that the exercise solves a complete concurrent booking system.

Decide what a repeated submission should mean

A student clicks the registration button and sees a loading indicator. The network then disconnects before the response appears. Several outcomes are possible: the server never received the request, the application rejected it, or the database committed the registration and only the response was lost. The student's screen cannot distinguish these cases from the missing response alone. This uncertainty is part of designing a useful registration service.

A second click creates a second request. Our first teaching application accepts repeated valid submissions as separate records because it has no duplicate rule. That behavior is intentional and easy to observe, but a real workshop may require one registration per student and session. Define that rule using a stable identity and workshop identifier. A display name alone is not a reliable identity because different students can share a name.

An idempotency design can let a client identify retries of the same intended operation. The server records the request identifier and the resulting operation so a retry can return the established result instead of performing the creation again. The storage and consistency of that record matter. Merely adding a random header without checking and storing it does not implement the behavior. Likewise, disabling the button in the browser improves the interface but cannot prevent every duplicate request.

A database uniqueness constraint can enforce an agreed enrollment rule, while the application translates a conflict into a clear response. The exact design depends on whether a student may enroll more than once, cancel and reenroll, or attend repeated sessions. Write those cases before choosing a constraint. Otherwise, a seemingly helpful restriction can reject a legitimate student action.

For your lab record, submit the same fictional request twice only in the disposable local application and predict the result. You should get two identifiers because each accepted request performs a new insert. Then write a paper design for returning the earlier result on an intentional retry. State where the operation identifier would be stored and how simultaneous requests would avoid creating duplicate records. This exercise connects HTTP behavior to the database rule without pretending the small demo already implements it.

Plan identities, connections and process lifetime

A MySQL application should use an account with the operations and objects it needs. Restricting an account to one database is a useful scope decision, but granting every privilege on that database may still exceed a read-only report's needs. Schema migration permissions can belong to a separate deployment identity. Verify both the allowed operations and the intended connection source.

Keep credentials out of public files and source repositories. Environment variables are a delivery mechanism, not a guarantee that secrets cannot be exposed through logs, process inspection or debugging tools. Use the deployment's supported protected configuration or secret-delivery mechanism, limit access and avoid printing full connection strings in a student's troubleshooting transcript.

Application workers and database connections interact. If several processes each create their own connection pool, the total potential connections can be larger than one pool's configured size. Increase workers only with a reason and measurements. More concurrency can increase memory use or overload a constrained database rather than making every request faster.

In Node.js, long blocking work on the event loop can delay other requests handled by that process. In a synchronous Python worker, a slow request can occupy that worker. PHP-FPM has its own pool limits. The language label alone does not determine capacity. Measure the actual path, request duration, errors and resource use before choosing worker counts or timeouts.

A supervisor should start the intended command with the intended identity, working directory and environment. It can restart a failed process, but repeated restarts are evidence to investigate. Verify readiness separately from process existence. A process may be running while it cannot authenticate to the database or load a required table. Graceful shutdown also needs to stop accepting new work and handle current work appropriately.

Configure the proxy around the application's actual contract

A reverse proxy needs the upstream protocol, destination and route mapping. If the application expects /register but the proxy removes or duplicates a prefix, the upstream can return a missing-route response even though the connection works. Inspect the path received by the application. A correct port is necessary for that connection, but it does not establish that the intended route was forwarded.

The public request and upstream request can have different connection addresses. The application may see the proxy's address as its direct peer. Forwarded headers can carry information about the original request, but the application must trust only the configured proxy arrangement. A client can supply a header with the same name. Flask's proxy middleware and Express's trust-proxy settings need the actual deployment topology, not an unconditional “trust everything” setting.

Request-size limits and timeouts can exist at several components. If the proxy rejects a large upload before forwarding it, changing a database timeout will not solve the problem. If the application waits on a slow query, increasing every timeout can merely make users wait longer. Record where the request stopped and which component produced the error before changing the limit.

Keep the application listener private to its intended callers. In a same-host design this may be loopback or a Unix socket. In a multi-host design it may be a private network endpoint with the relevant rules and identity controls. A browser should use the intended public endpoint. Do not publish an internal development port simply to avoid understanding the proxy configuration.

Lab: submit, store and read one registration

Use Python 3 with its sqlite3 module and curl on a learning computer. The lab binds only to loopback on port 18890 and creates its own temporary directory. It uses fictional records. There is no login, public hostname, reverse proxy or MySQL service in this first exercise. The small built-in HTTP server is a teaching tool; it is not the production server recommended for a Flask deployment.

Create the application file below. The database path is derived from that file's directory, so starting the program from another working directory does not silently choose another database. At startup, the program creates its teaching table if needed. The connection is closed after use, and successful inserts are committed before the response is sent.

app_lab=$(mktemp -d /tmp/workshop-register.XXXXXX)
cat > "$app_lab/app.py" <<'PY'
from contextlib import closing
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
import json
import sqlite3

DB = Path(__file__).resolve().parent / "registrations.sqlite3"
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 Handler(BaseHTTPRequestHandler):
    def reply(self, status, value):
        body = json.dumps(value).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/health":
            return self.reply(200, {"process": "responding"})
        if self.path != "/registrations":
            return self.reply(404, {"error": "route not found"})
        try:
            with closing(sqlite3.connect(DB)) as con:
                rows = con.execute(
                    "SELECT id, name, workshop FROM registrations ORDER BY id"
                ).fetchall()
        except sqlite3.Error:
            return self.reply(500, {"error": "database operation failed"})
        return self.reply(200, {"registrations": [
            {"id": row[0], "name": row[1], "workshop": row[2]}
            for row in rows
        ]})

    def do_POST(self):
        if self.path != "/registrations":
            return self.reply(404, {"error": "route not found"})
        if self.headers.get("Content-Type", "").split(";")[0] != "application/json":
            return self.reply(415, {"error": "use application/json"})
        try:
            length = int(self.headers.get("Content-Length", "0"))
        except ValueError:
            return self.reply(400, {"error": "invalid length"})
        if length < 1 or length > 1024:
            return self.reply(413, {"error": "body must be 1 to 1024 bytes"})
        try:
            data = json.loads(self.rfile.read(length))
        except (ValueError, UnicodeError):
            return self.reply(400, {"error": "invalid JSON"})
        if not isinstance(data, dict) or set(data) != {"name", "workshop"}:
            return self.reply(400, {"error": "provide name and workshop"})
        name, workshop = data["name"], data["workshop"]
        if not isinstance(name, str) or not 1 <= len(name.strip()) <= 60:
            return self.reply(400, {"error": "name must be 1 to 60 characters"})
        if workshop not in ("robotics", "solar"):
            return self.reply(400, {"error": "unknown workshop"})
        try:
            with closing(sqlite3.connect(DB)) as con:
                cursor = con.execute(
                    "INSERT INTO registrations (name, workshop) VALUES (?, ?)",
                    (name.strip(), workshop),
                )
                con.commit()
                registration_id = cursor.lastrowid
        except sqlite3.Error:
            return self.reply(500, {"error": "database operation failed"})
        return self.reply(201, {"id": registration_id, "accepted": True})

HTTPServer(("127.0.0.1", 18890), Handler).serve_forever()
PY
printf 'Registration lab directory: %s\n' "$app_lab"

Read the three routes before starting the program. The health route answers without reading the database, so it proves only that the process can handle that route. The registrations GET route reads rows. The registrations POST route validates and inserts a row. These distinct checks will let you explain a partially working service.

Start the program in the same terminal. It runs in the foreground so you can stop only this exercise with Ctrl+C. If the port is already in use, choose another unused high port consistently in the code and requests. Do not terminate an unrelated process to make the exercise fit its printed port.

python3 "$app_lab/app.py"

In a second terminal, read health and the current registrations. A newly created practice database should contain an empty registration list. The health response says the process is responding; it does not claim every dependency or business operation is ready. Keep that narrow meaning when designing real monitoring endpoints.

curl --noproxy '*' --max-time 5 -i http://127.0.0.1:18890/health
curl --noproxy '*' --max-time 5 -i http://127.0.0.1:18890/registrations

Submit one fictional registration as JSON, then read the list again. The request declares its content type so the handler knows which representation it accepts. The response should be 201 with a new identifier and an accepted value. The later GET should contain the same student's name and workshop. This second observation is the evidence that the stored result matches the success response.

curl --noproxy '*' --max-time 5 -i -H 'Content-Type: application/json' --data '{"name":"Asha Demo","workshop":"robotics"}' http://127.0.0.1:18890/registrations
curl --noproxy '*' --max-time 5 -i http://127.0.0.1:18890/registrations

Try two invalid inputs and a missing route. An empty name and an unknown workshop should each receive 400. The missing route should receive 404. After these rejected requests, the accepted list should still contain only the earlier valid registration. A rejected request is a correct result when it violates the operation's stated contract.

curl --noproxy '*' --max-time 5 -i -H 'Content-Type: application/json' --data '{"name":"","workshop":"robotics"}' http://127.0.0.1:18890/registrations
curl --noproxy '*' --max-time 5 -i -H 'Content-Type: application/json' --data '{"name":"Ravi Demo","workshop":"unknown"}' http://127.0.0.1:18890/registrations
curl --noproxy '*' --max-time 5 -i http://127.0.0.1:18890/missing
curl --noproxy '*' --max-time 5 -i http://127.0.0.1:18890/registrations

Now stop the foreground application with Ctrl+C in its original terminal and start the same file again. Read the list from the second terminal. The valid record should remain because it was committed to the database file. The application process stopped, but the file did not disappear. If you create a new practice directory instead, you have created a different database and should expect a different list.

Do not describe this as a complete durability or recovery test. It demonstrates persistence across an ordinary process restart. It does not simulate a disk failure, corrupted storage, a machine outage or restoration from a backup. Each of those requires its own procedure and evidence. The distinction helps you avoid overclaiming from a successful small experiment.

Lab: observe an uncommitted change disappear

Stop the foreground application before this follow-up and remain in the original terminal where app_lab still identifies the practice directory. The script opens the existing database, counts registrations, inserts a temporary fictional row and counts within that connection. It then rolls back and counts again. No public service or other database is involved.

APP_LAB="$app_lab" python3 - <<'PY'
from contextlib import closing
from pathlib import Path
import os
import sqlite3

db = Path(os.environ["APP_LAB"]) / "registrations.sqlite3"
assert db.is_file(), "Use the existing practice database."
with closing(sqlite3.connect(db)) as con:
    before = con.execute("SELECT COUNT(*) FROM registrations").fetchone()[0]
    con.execute(
        "INSERT INTO registrations (name, workshop) VALUES (?, ?)",
        ("Rollback Demo", "solar"),
    )
    during = con.execute("SELECT COUNT(*) FROM registrations").fetchone()[0]
    con.rollback()
    after = con.execute("SELECT COUNT(*) FROM registrations").fetchone()[0]
    print({"before": before, "during": during, "after": after})
    assert during == before + 1 and after == before
PY

With one previously accepted record, the expected counts are one, two and one. The connection saw its own uncommitted insert, but rollback removed that pending change. The earlier committed record remained. This is a concrete way to distinguish an operation attempted inside a transaction from a completed registration that the service has accepted.

Read the SQL parameter tuple in both inserts. The temporary name is passed separately from the statement, just as the HTTP handler passes the student's value. The concept transfers to the appropriate MySQL driver, but the exact placeholder conventions and transaction settings must follow that driver. Do not copy the SQLite connection code into a MySQL lesson and claim it connects to a server.

When finished, inspect the known practice directory. It contains the application and its teaching database. Retain them if you want to revisit the result, or remove those verified exercise files after the process is stopped. A real cleanup procedure must distinguish disposable sample data from records that users expect the service to retain.

Turn the experiment into a deployment plan

The local application intentionally leaves out several production responsibilities. It has no user authentication or per-user authorization, no CSRF-protected browser session, no public TLS endpoint and no capacity-control transaction. Its simple server handles a teaching workload. Those limitations do not make the experiment useless; they define which concept it demonstrates and what a real product must add.

For the PHP, Flask and Express lessons, preserve the behavioral contract while replacing the relevant serving and database integration. Use the intended database account, supported driver and deployment configuration. Record application dependencies and versions so another environment can reproduce the installation. A project directory containing source files is not necessarily the complete deployment artifact.

Review database migrations before applying a new application release. A schema change can affect the previous version's ability to run, so code rollback and database rollback are separate questions. Adding a compatible column is different from deleting a column that the older application still needs. Keep an appropriate backup and demonstrate restoration to a separate target for the changes that require it.

Define readiness and useful monitoring. A static home page, a process health response and a sample database read each exercise different dependencies. Choose checks that support the service's actual promise without causing unintended writes. For a controlled acceptance test, a synthetic registration can be useful if its creation and cleanup are explicitly part of the test design.

Before publishing, verify the external route and the internal path independently. Confirm the intended certificate, hostname, response behavior and application data result. Review logs for the named test and make sure they do not expose passwords or unnecessary submitted data. The deployment record should state what was tested, what changed and how the prior working behavior can be restored.

Read errors as evidence from a particular component

A 400 response can mean the application rejected a malformed or unacceptable request. In our lab, an empty name is deliberately rejected with 400. A 404 means the responding component did not provide the requested resource under its handling. The proxy might return it before contacting the app, or the app might return it for an unknown route. Identify the producer before editing configuration.

A 500 indicates an unexpected server-side failure for the request. It does not name the root cause. A database permission error, missing table or application exception can be involved. Inspect the relevant protected logs and a narrow reproduction. Showing a full stack trace or credentials to the visitor is not necessary to explain that the operation failed.

A 502 from a gateway indicates that it did not obtain an acceptable upstream response. Check the configured protocol and destination, whether the upstream is listening and the associated error message. Sending HTTP to PHP-FPM or pointing at a stopped application are different failures that can appear at this boundary. A running proxy process cannot establish that its upstream is healthy.

A 504 indicates that the gateway's upstream interaction exceeded the relevant timeout. The underlying cause may involve application work, a database wait, network behavior or an overloaded dependency. Measure the request path before increasing a limit. A longer timeout might be appropriate for an intended long operation, but it does not repair a deadlock or an unavailable dependency by itself.

Use one diagnostic table with timestamp, request path, responding component, status and supporting log observation. Change one justified cause, then repeat the affected checks. If the registration is accepted, read its stored result. If the fix changes proxy behavior, also verify a static asset and an unrelated route. That completes the explanation from symptom to corrected user outcome.

Tasks to complete after the walkthrough

  1. Draw the registration flow. Label each connection with its protocol and each component with its responsibility. Include the commit before the accepted response and explain which check verifies the saved record.
  2. Write an input contract. List the required JSON fields, allowed workshop values, name-length rule and response statuses. Add an invalid object shape to your test list and explain the expected rejection before running it.
  3. Compare restart with recovery. Record the identifier before and after restarting the same application file. Then explain why this does not prove that a backup can restore records after storage loss.
  4. Read the rollback counts. Predict the before, during and after values for two already committed registrations. Explain which row disappears and why the earlier records remain.
  5. Translate one integration. Choose PHP-FPM, Flask with WSGI or Express. Write the correct interface between web server and application, then identify the database driver's parameter mechanism. Keep the behavior consistent while naming the different tools accurately.
  6. Diagnose partial health. Suppose the health endpoint returns 200 while the registrations endpoint returns 500. Explain which dependency the health route did not exercise and which narrow evidence you would collect next.

Interview questions with explained answers

How is dynamic hosting different from uploading static files?

A dynamic service runs application logic for relevant requests and may read or change stored state. Deployment therefore includes the runtime, dependencies, configuration, serving interface and data lifecycle. A static asset can still be part of that application. I would verify a complete useful operation, such as a committed registration and subsequent read, instead of treating a loaded HTML page as proof that the backend works.

Does a three-tier design require three EC2 instances?

No. The tiers describe responsibilities that can share a machine in a teaching setup or be separated in another architecture. Placement changes failure boundaries, connection paths and operational choices. I would draw the actual deployment and identify each process and listener. Moving components to different hosts requires revisiting loopback assumptions, routing, credentials and access rules.

Why must a proxy distinguish PHP-FPM from an HTTP application?

PHP-FPM exposes FastCGI, while a typical Flask WSGI server or Express listener can expose HTTP. The web server must use a compatible protocol and correct mapping. A reachable socket alone does not establish compatibility. I would verify the endpoint type and script or route mapping before interpreting a gateway error as a generic network failure.

Do prepared statements replace validation and authorization?

No. Parameter binding separates query structure from values in the database operation. Validation checks whether the values satisfy the application contract. Authorization decides whether the caller may perform that operation. Output encoding protects the response's presentation context. A sound implementation applies the relevant mechanisms together because they answer different questions.

What does a successful commit tell the application?

It indicates that the database accepted the transaction's completion under its configured behavior. The application should align its success response with the required committed outcome. It still needs a plan for uncertain client retries, duplicates and recovery. A timed-out client might not know whether the server committed, so a retry design must consider more than the original response status.

Can adding more application workers solve a slow database?

Not necessarily. Additional workers can increase concurrent database work and connection demand. If the database is already constrained, the change can worsen waiting. I would measure request duration, query behavior, connection counts and errors, then choose a correction supported by that evidence. Worker limits and database pool limits must be considered across all processes.

Quiz: check the complete operation

1. The form page loads, but submissions fail. Has the database path been proven healthy?

Answer and explanation

No. The form may be a static resource. Exercise the submission route and the relevant database operation, then inspect the stored result for an accepted request.

2. The local health route returns 200. Does it prove the registration table can be read?

Answer and explanation

No. That route deliberately returns without querying the database. The registrations GET route is the separate read check in this exercise.

3. A student types an apostrophe in a valid name. Should the application build SQL by manually removing the punctuation?

Answer and explanation

No. Apply the legitimate name policy and bind the value through the database driver's parameter mechanism. Data punctuation should not become part of the SQL instruction structure.

4. The rollback exercise starts with three committed rows. What counts should it print?

Answer and explanation

Three before the insert, four inside the transaction and three after rollback. The pending row disappears while the earlier committed rows remain.

5. An operator starts Express under PM2. Which part implements the registration route?

Answer and explanation

The application's JavaScript running with Node.js and Express implements the route. PM2 manages the process lifecycle; it does not invent the application's business logic.

Revision cards

Follow the saved result

A success message is useful only when it matches the required operation. Verify the committed record with a subsequent read.

Name the protocol

HTTP, FastCGI and the database interface have different expectations. A listening port does not tell you that the message format is correct.

Separate the controls

Validation, authentication, authorization, parameter binding and output encoding solve different problems. None replaces all the others.

Preserve data across releases

Application code, configuration and persistent records have different lifecycles. Know the database location and the tested recovery procedure.

Measure concurrency

Count workers and connections across all processes. More parallel work can increase pressure on a constrained dependency.

Identify the error producer

Record the component that returned the status and inspect its relevant evidence. A gateway error does not uniquely identify a database or network cause.

Official sources

What "dynamic" means, with real examples

A static response delivers prepared content, which can still include browser-side behavior. A dynamic application runs logic for relevant requests, such as a fictional workshop registration or result lookup. To build it, three tiers work together. The web server (nginx or Apache) receives the request. The application (PHP, Python, Node.js, or in other teams Java, .NET or Go) runs the logic. The database (MySQL or MariaDB here, and PostgreSQL or MongoDB elsewhere) stores the data.

In this chapter you build the same small customer-list app three times, in PHP, Flask and Express, on one EC2 instance. The responsibilities are comparable, but the integration differs: PHP-FPM uses FastCGI, while typical Flask and Express deployments expose HTTP upstreams. The same-host examples keep internal listeners private. Other frameworks require their own runtime, configuration and operational review.

3 tiersBrowsernginx :443App on127.0.0.1MySQL127.0.0.1:3306
This diagram illustrates a same-host design with Nginx as the public endpoint. The application interface and database access rules must match the chosen deployment.

After this part you will be able to

  1. Install MySQL or MariaDB and create one user per app.
  2. Run a PHP, a Flask and an Express app behind nginx.
  3. Keep the app and database ports private.
  4. Investigate gateway errors using the upstream protocol, destination and logs.

Practice examples: A fictional order history, registration service or result portal can demonstrate generated responses and stored state. This teaching diagram does not describe a named company’s actual architecture. Everyday: a tea stall makes tea fresh for each order (dynamic), while the menu board stays the same (static).

Beginner questions I get in class

Q. Why three languages in one chapter?
To show that the pattern (web server → app → database) does not depend on the language.

Q. Can I use PostgreSQL instead of MySQL?
Yes, with a reviewed database migration and application integration. Drivers, SQL behavior, types, authentication, privileges, transactions and operational procedures can differ; changing a port is not enough.

Key terms

  • Three tiers: Web, app and data.
  • WSGI / ASGI: Python app interfaces used by Gunicorn and Uvicorn.
  • PM2: Node.js process manager.
  • systemd unit: A service definition with restart and boot rules.
  • Least-privilege DB user: An account granted only the required operations on the required objects, with the intended connection scope.
  • 504: A gateway did not receive the needed upstream response within its timeout. Investigate the application, dependencies and connection evidence.

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 connections are permitted by the approved design, including the chosen administrative access path. 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 scenario

Nashik Vineyards is a wine and farming business in Nashik. Meera Joshi 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Restart a service after a change

This Nginx exercise applies startup configuration through the intended service action. Other application and server settings can have different reload or request-time behavior.

Restart the nginx service.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. 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).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. 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).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. 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).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. 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).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.