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

Chapter 12: Technology Stacks — LAMP, LEMP, MEAN, MERN

AWS Cloud

12.3 LEMP stack

Friends, LEMP pairs Nginx with PHP-FPM and an SQL database. The PHP app can keep its database logic when the new entry point preserves the runtime and request settings it needs.

The browser connects to Nginx over HTTP or HTTPS. For a PHP route, Nginx sends a FastCGI request to PHP-FPM. PHP can open a separate private connection to MySQL or MariaDB. Local sockets and private TCP listeners are deployment choices.

Full LEMP installation

Start by choosing supported Nginx, PHP-FPM and database packages for your operating-system release and app. Confirm the site configuration loaded by Nginx, which PHP-FPM pool is active, and the exact listen path and permissions that pool provides. The isolated exercise below configures these connections explicitly.

  • Amazon Linux 2023. Use DNF and your selected AL2023 repositories. Check the Nginx includes and the installed FPM pool configuration for that release.
  • Ubuntu. Check the installed PHP release and service unit. The packaged FastCGI include and runtime socket path are installation-specific. Verify what the intended server block actually loads.
  • CentOS Stream. Confirm the supported package streams, service units and applicable file or socket access policy for the selected release.

Test with a small private endpoint that returns a known application result. Use a separate static request to check the host and verify a database-dependent response against a known SQL row.

Ravindra Bagale's Tip

Use a private test with a known application result. Compare the HTTP status and expected fields. Keep PHP version, paths and settings out of public responses.

Lab

खाली दिलेल्या खाजगी lab मध्ये inventory आणि receipts ही दोन test sites तपासा. Catalog route मध्ये चुकीचा FastCGI socket वापरून परिणाम पाहा. मग योग्य socket परत लावून database मधला stock आणि receipts page पुन्हा तपासा.

With LEMP, Nginx maps incoming requests to files and the FastCGI runtime. PHP and the database can retain their roles, while the routes, headers and worker settings still need verification. Next, MEAN and MERN use a different application runtime.

Replace the HTTP entry point and keep the stock contract

The dairy shop has tested its first catalog. The page uses Apache for the browser connection, PHP to validate the product code and MySQL to read the quantity. A second team already operates Nginx for the membership site on the same machine. They want the shopping catalog to use the same kind of HTTP server as their existing service. The shop owner cares about one promise: a known product and its current quantity should still come back from the same address in the same format. To keep that promise, the team needs to know precisely which work moves and which work stays on the existing path.

In LEMP, Linux supports the processes and permissions, Nginx faces the browser, MySQL or MariaDB stores data, and PHP handles dynamic work. The letter E in the common abbreviation comes from the pronunciation of Nginx as “engine x.” A developer who only learns the acronym can't predict what happens after a request arrives. Nginx can send static files itself. For an application written in PHP it can pass the request to a separately configured PHP-FPM worker using FastCGI. It can also handle other applications in entirely different ways. The rules for passing the URL, selecting a file, choosing the worker and handling errors matter more than a new letter in the stack name.

The prior LAMP lesson uses a PHP script that expects a sku parameter. Its test starts with milk stock at seven and curd stock at zero. The script can keep its SQL code if the PHP environment, database and input contract are preserved. Apache and Nginx differ in how those settings reach the script. Packages may use other paths, socket permissions, headers, rewrites and defaults. A PHP application that relies on an Apache-specific .htaccess rule, for instance, needs equivalent behavior deliberately configured in Nginx. Nginx does not read that per-directory Apache configuration file.

Say that the site has two kinds of change to manage. The business change updates a stock record from seven to thirteen. It lives in MySQL and should be reflected in future application reads. The web-server change maps /catalog.php to a new HTTP entry point. The team can test it without changing the quantity or letting the second site's requests reach the wrong catalog. Managing the two separately helps every test say something clear. When adding Nginx causes a malformed request to reach the PHP file as raw text or drops a query value, a stock update is unlikely to repair the HTTP mapping.

The exercise uses two reserved test hostnames on one loopback listener. inventory.test may run exactly one PHP script. receipts.test serves a simple static control response to represent a neighboring website. Neither needs to be added to global DNS or the laptop's hosts file. Curl supplies the local test connection and expected host directly. This arrangement demonstrates why a shared Nginx process can serve an ordinary page for one hostname and report an upstream failure on another. Practice on an isolated listener before attempting the equivalent change for real users.

Read the host, path, endpoint and query as separate choices

Work through http://inventory.test:18903/catalog.php?sku=MILK-1 slowly. The client needs an address and port to reach Nginx. The exercise uses a curl option to direct the test-only hostname to the loopback address, while the URL still supplies the HTTP Host value. Nginx uses the listening address and port, then the request's host information to pick a server block. A server block is the group of settings for a website on one or more listeners. The chosen server then compares the normalized URI path with its location rules. A location is a block of settings for matching requests within that server.

The path and query are different pieces of the same request. The location = /catalog.php rule compares the path for an exact match. Both ?sku=MILK-1 and ?sku=CURD-2 use this same location. The value after the question mark won't choose a different location. That value will influence the row only if the FastCGI rule passes it to PHP, and only after PHP validates it. Nearby URLs such as /missing.php have no reason to execute anything. The exercise uses an explicit deny-by-default style for public paths so you can see the allowed set at a glance.

DecisionExample valueEvidence that tests it
Which HTTP server block?Inventory rather than receiptsThe inventory and receipt help pages return different expected markers
Which public path?Exact location for the catalogA real script request reaches FastCGI, while a neighboring PHP path returns Nginx's 404
Which process and script?The inventory FPM Unix socket and the absolute catalog pathThe route produces rendered JSON and the error log identifies socket failures
Which product?CURD-2 from the query stringThe PHP response contains the right SKU and preserves zero stock

The lab's root setting chooses the directory for files in the inventory server. try_files /catalog.php =404 checks a file at the mapped location before contacting FPM. This check stops at the HTTP server if the declared file is missing. It cannot establish that the FPM process exists or can access a file that Nginx can see. Processes may run under different accounts or in separate filesystem environments. A script is usable by FPM only if the path forwarded in the request makes sense and is readable for that PHP worker. That is a second, independently useful check.

The config sends SCRIPT_FILENAME with the exact script file's absolute path. It also sends QUERY_STRING with Nginx's request query value and REQUEST_METHOD with a method such as GET. These are FastCGI parameters, pieces of information Nginx passes to the worker through this protocol. PHP's request handling uses them to identify the source and populate its query input. Omitting the query parameter may allow the correct program to start but cause a missing-key response for every product. Omitting or misconstructing the script filename can prevent that program from being reached at all. These two problems look different in the log and body.

fastcgi_pass chooses where the FastCGI request goes. The value can name a local Unix socket or a TCP FastCGI destination when appropriately configured. The example creates the local socket in a private directory. The PHP process owns the database connection using another local socket. Calling a FastCGI listener with curl as if it were a normal website cannot establish that the protocol between Nginx and FPM works. The meaningful request begins as HTTP to Nginx. FPM's own logs, process state and endpoint permissions are supporting observations.

A modern package may distribute include files that supply common FastCGI parameters. Those are convenient when you verify what they contain and use whichever package-specific layout is actually installed. For a short private example an explicit set for this GET endpoint makes it easier to reason through the important pieces. A real PHP site may need additional parameters and explicit method, body, path and HTTP forwarding behavior. Copying a generic parameter file into the wrong server does not guarantee compatibility with a framework, unrelated site or different root.

Distinguish identical status numbers by who returned them

In the lab, /invented.php and /catalog.php?sku=MILK-9 both return an HTTP 404. One asks for a route outside the permitted set. Nginx rejects it before contacting PHP. The other enters the valid catalog route, executes a prepared query, finds no matching product and then returns the app's own JSON error. A support ticket saying only “I'm getting a 404” leaves out that distinction. Write down the URL, response type, short safe body and originating layer. The body and the upstream detail help you choose a fix.

Imagine a student mistakenly uploads the old catalog script to /catalog-backup.php. The student should not test it by allowing every filename to execute or by making a new public catch-all. The configured allowed route is independent of whether some other file exists on the same disk. Use a challenge request in the private lab to see that a fixture at a different URL is not served. In a maintained site keep backups outside document roots as a separate safeguard. A wrong serving rule can make backup files visible if they fall under a public root.

A 502 comes from a different boundary in this exercise. Nginx is alive and found the catalog location, but the configured FPM destination is unavailable, so the gateway cannot obtain an upstream response. A stopped database creates another case: FPM can execute the script and the script can intentionally return its own 503 after a failed SQL operation. Both errors are useful stress tests. One leads to the PHP-FPM socket and the other to PDO and MySQL. Widening database permissions after a missing FastCGI socket just increases risk without repairing that failure.

When reading diagnostic logs, record what the logger knows. An upstream 404 can mean PHP answered with 404. A gateway's failed connection attempt can also appear under upstream status or address fields generated by Nginx. A value in that field does not establish that PHP itself sent it. Pair the record with the connection error or the expected PHP response body. For this lab the Nginx error log gives an explicit failed socket path for the broken configuration, making it easier to identify the line responsible and compare the observed failure to your prediction.

Lab: keep a neighboring site healthy while changing FastCGI

Prepare a private copy of the dairy catalog by performing Steps 1 through 3 of the LAMP lab from one ordinary-user Bash session. Stop after starting PHP-FPM in Step 3. Do not start Apache for this exercise. Those three steps provide a fresh MySQL data directory, the two seed rows, the known PHP file and the private FPM worker. If an earlier run finished or changed stock, create a fresh fixture. The new lab uses the variables and cleanup function created by the preparation. This shared beginning lets you test the same actual application and same input data at two different HTTP entry points.

You also need an installed Nginx executable and a free local high port. Use NGINX_BIN for its full path when it is outside the shell's executable search path. Use LEMP_PORT to select a free high port before running the first block if 18903 is already in use. You will not need an Internet-facing DNS name, EC2 firewall changes, or access to the installed Nginx configuration. Run all blocks in the same session that created the temporary database. This is a learner-only setup, with the test HTTP listener inaccessible from other machines.

Step 1. Map the inventory site and the receipts control site

nginx_bin=${NGINX_BIN:-$(command -v nginx || true)}
test -x "$nginx_bin"
test -f "$lamp_lab/public/catalog.php"
test -S "$lamp_lab/fpm.sock"
sql -e 'SELECT sku, stock FROM dairy_catalog.products ORDER BY sku;'
lemp_port=${LEMP_PORT:-18903}
nginx_pid=
lemp_cleanup() {
  stop_child "$nginx_pid"
  lamp_cleanup
}
trap lemp_cleanup EXIT
mkdir -p "$lamp_lab/logs" "$lamp_lab/ng-logs" "$lamp_lab/ng-temp" "$lamp_lab/receipts"
printf 'receipts-control-v1\n' > "$lamp_lab/receipts/index.html"
write_nginx() {
  local worker_socket=$1 version=$2 config_path=$3
  cat > "$config_path" <<NGINX
worker_processes 1;
pid "$lamp_lab/run/nginx.pid";
error_log "$lamp_lab/ng-logs/error.log" notice;
events { worker_connections 64; }
http {
    types { text/html html; }
    default_type text/plain;
    client_body_temp_path "$lamp_lab/ng-temp/body";
    proxy_temp_path "$lamp_lab/ng-temp/proxy";
    fastcgi_temp_path "$lamp_lab/ng-temp/fcgi";
    uwsgi_temp_path "$lamp_lab/ng-temp/uwsgi";
    scgi_temp_path "$lamp_lab/ng-temp/scgi";
    log_format catalog 'site=\$server_name method=\$request_method uri=\$uri code=\$status fcgi=\$upstream_status';
    access_log "$lamp_lab/ng-logs/access.log" catalog;
    server {
        listen 127.0.0.1:$lemp_port default_server;
        server_name _;
        return 404;
    }
    server {
        listen 127.0.0.1:$lemp_port;
        server_name inventory.test;
        root "$lamp_lab/public";
        location = /index.html { try_files \$uri =404; }
        location = /route-version { return 200 "$version\\n"; }
        location = /catalog.php {
            try_files /catalog.php =404;
            fastcgi_param SCRIPT_FILENAME "$lamp_lab/public/catalog.php";
            fastcgi_param QUERY_STRING \$query_string;
            fastcgi_param REQUEST_METHOD \$request_method;
            fastcgi_pass unix:$worker_socket;
        }
        location / { return 404; }
    }
    server {
        listen 127.0.0.1:$lemp_port;
        server_name receipts.test;
        root "$lamp_lab/receipts";
        location = /index.html { try_files \$uri =404; }
        location / { return 404; }
    }
}
NGINX
}
write_nginx "$lamp_lab/fpm.sock" route-good "$lamp_lab/nginx.conf"
cp "$lamp_lab/nginx.conf" "$lamp_lab/nginx.known-good"
ngx() {
  "$nginx_bin" -p "$lamp_lab/" -c "$lamp_lab/nginx.conf" "$@"
}
ngx -t
"$nginx_bin" -p "$lamp_lab/" -c "$lamp_lab/nginx.conf" -g 'daemon off;' &
nginx_pid=$!
for attempt in $(seq 1 40); do
  if [ -s "$lamp_lab/run/nginx.pid" ]; then break; fi
  if ! kill -0 "$nginx_pid" 2>/dev/null; then break; fi
  sleep 0.25
done
kill -0 "$nginx_pid"
test "$(tr -d '[:space:]' < "$lamp_lab/run/nginx.pid")" = "$nginx_pid"

The configuration writer only sets the FPM destination and a small route marker using controlled arguments. If making your own test, use safe plain values for those arguments. The chosen variables in this file serve different uses. The shell expands the lab directory and port while it writes the config. The backslash before the dollar sign keeps values such as $uri unexpanded by the shell. Nginx will provide those values for each incoming request. Reading the final file under the lab directory can show the difference. The absolute PHP filename is the path the worker receives, not part of what the browser requests.

The port and hostname may be reused in several blocks. The default server is selected by default_server on the listening socket. Its ordinary server name is not a wildcard that magically catches other hosts. Nginx first selects by address and port and normally uses the host name to select another matching server. The default replies 404 if the client asked for an unexpected host. The receipts site has no FastCGI route or access to the inventory document root through these location rules. It acts as a control with separate content while both sites use one Nginx process.

ngx -t points the test at the actual candidate using the same prefix and file as the new process. Testing syntax can catch a malformed parameter name or file opening issue, but a valid address can still point to a nonexistent endpoint. The process identity guard checks that the private instance actually started. If the private log reports a bind failure, select a different port and rebuild this local fixture. A response from the already established process on an occupied port is not an acceptable substitute.

Step 2. Prove host mapping, query delivery and SQL agreement

request() {
  local host=$1 path=$2
  curl --noproxy '*' --silent --show-error --max-time 4 \
    --resolve "$host:$lemp_port:127.0.0.1" \
    -o "$lamp_lab/lemp-response" -w '%{http_code}' \
    "http://$host:$lemp_port$path"
}
expect() {
  local host=$1 path=$2 expected=$3 actual
  actual=$(request "$host" "$path")
  printf '%s %s %s\n' "$actual" "$host" "$path"
  test "$actual" = "$expected"
}
expect_stock() {
  python3 - "$lamp_lab/lemp-response" "$1" "$2" "$3" <<'PY'
import json
import sys
from pathlib import Path

record = json.loads(Path(sys.argv[1]).read_text())
wanted = {"sku": sys.argv[2], "name": sys.argv[3], "stock": int(sys.argv[4])}
assert record == wanted and type(record["stock"]) is int, (record, wanted)
print(record)
PY
}
expect inventory.test /index.html 200
grep -Fq 'catalog-help-v1' "$lamp_lab/lemp-response"
expect receipts.test /index.html 200
grep -Fxq 'receipts-control-v1' "$lamp_lab/lemp-response"
expect unassigned.test /index.html 404
expect inventory.test '/catalog.php?sku=MILK-1' 200
expect_stock MILK-1 'Plain Milk' 7
expect inventory.test '/catalog.php?sku=CURD-2' 200
expect_stock CURD-2 'Set Curd' 0
expect inventory.test '/catalog.php?sku=MILK-9' 404
grep -Fq 'unknown sku' "$lamp_lab/lemp-response"
expect inventory.test /invented.php 404
if grep -Fq 'unknown sku' "$lamp_lab/lemp-response"; then exit 1; fi
expect receipts.test '/catalog.php?sku=MILK-1' 404
expect inventory.test '/catalog.php?sku=plain_milk' 400
grep -Fq 'invalid sku' "$lamp_lab/lemp-response"
mv "$lamp_lab/public/catalog.php" "$lamp_lab/held-catalog.php"
expect inventory.test '/catalog.php?sku=MILK-1' 404
if grep -Fq 'unknown sku' "$lamp_lab/lemp-response"; then exit 1; fi
mv "$lamp_lab/held-catalog.php" "$lamp_lab/public/catalog.php"
sql -e "UPDATE dairy_catalog.products SET stock = 13 WHERE sku = 'MILK-1';"
test "$(sql -e "SELECT stock FROM dairy_catalog.products WHERE sku = 'MILK-1';")" = 13
expect inventory.test '/catalog.php?sku=MILK-1' 200
expect_stock MILK-1 'Plain Milk' 13

The host resolution override tells curl where to connect without a DNS or system file change. Curl still sends each URL's host information. --noproxy '*' keeps the lab request local even if the shell otherwise uses a proxy. Confirm the two static markers first. That tests server selection with the same address and port. The unassigned name checks the fallback, and a catalog URL on the receipts host must stay rejected. These observations protect the unaffected site before you attempt a fault.

The unknown product request returns a JSON response carrying the PHP program's own phrase. The invented script and temporarily moved catalog should return the HTTP server's 404 instead. The invented path tests the location boundary. Moving the expected script from the public folder tests the file guard within the catalog location. This move happens in a private fixture, so it cannot disrupt a real request. When the file goes back the next test restores the dynamic contract. Use the independent SQL write and read to prove that the product's thirteen cartons came from this data store, rather than from a string printed in a website template.

Activate a wrong socket, prove its impact, and roll back

Step 3. Show why a successful syntax check cannot prove a working app

await_version() {
  local wanted=$1 status attempt
  for attempt in $(seq 1 40); do
    status=$(request inventory.test /route-version)
    if [ "$status" = 200 ] && grep -Fxq "$wanted" "$lamp_lab/lemp-response"; then
      return 0
    fi
    sleep 0.25
  done
  printf 'Nginx did not switch to %s. Read the private error log.\n' "$wanted" >&2
  return 1
}
await_version route-good
test ! -e "$lamp_lab/absent-fpm.sock"
write_nginx "$lamp_lab/absent-fpm.sock" route-broken "$lamp_lab/nginx.conf"
ngx -t
ngx -s reload
await_version route-broken
expect inventory.test '/catalog.php?sku=MILK-1' 502
grep -Fq 'absent-fpm.sock' "$lamp_lab/ng-logs/error.log"
expect inventory.test /index.html 200
grep -Fq 'catalog-help-v1' "$lamp_lab/lemp-response"
expect receipts.test /index.html 200
grep -Fxq 'receipts-control-v1' "$lamp_lab/lemp-response"
test "$(sql -e "SELECT stock FROM dairy_catalog.products WHERE sku = 'MILK-1';")" = 13

The second config names a perfectly valid-looking socket path with no PHP listener. A successful syntax check is expected. The next command asks only the private Nginx process to reload. The master process receives that request, tries to apply the configuration and starts new workers if it can. Existing accepted work may still be finishing under old workers. The loop checks a marker from normal HTTP traffic before expecting the changed behavior. This is stronger than sleeping for a fixed time after a signal and hoping the new configuration will be running by then.

With the new config active, the same public catalog route returns 502. The error log naming absent-fpm.sock tells you what Nginx failed to reach, while a direct SQL check still reads thirteen. The inventory static file succeeds because it does not use the FastCGI handler. The receipts file succeeds from its own server block on the same Nginx listener. Those tests narrow the failed change to the catalog connection and measure the intended impact. They also rule out the tempting conclusion that losing one application means the entire HTTP server is down.

In the private folder the wrong endpoint has no listener by design. In a real deployment there can be a live process but the path still disagrees. Compare the worker's configured listen value, whether the socket exists, and permissions for the exact Nginx worker identity. A permission denied message calls for different investigation than a filename that doesn't exist. A worker in a container might see a different filesystem even when both configurations spell the same path. Start with those observations before changing access policy.

Step 4. Restore the known-good route and retest application behavior

cp "$lamp_lab/nginx.known-good" "$lamp_lab/nginx.conf"
ngx -t
ngx -s reload
await_version route-good
expect inventory.test '/catalog.php?sku=MILK-1' 200
expect_stock MILK-1 'Plain Milk' 13
expect receipts.test /index.html 200
grep -Fxq 'receipts-control-v1' "$lamp_lab/lemp-response"
printf 'Observed route and upstream status samples:\n'
grep -F 'uri=/catalog.php' "$lamp_lab/ng-logs/access.log" | tail -n 8

The known-good copy belongs only to this exercise and was written before the invalid destination was proposed. Restore that file rather than typing an endpoint from memory. After confirming the original marker has been activated, check the response data and untouched neighbor again. An HTTP 200 on the static page alone would have passed even with the broken socket. Verify milk stock still equals the independently observed thirteen. Rollback changes the HTTP wiring and leaves the database change in place. In a real system there can be multiple candidate changes, so record which file and release you restore and what behavior each verification should confirm.

The log samples show path and response status without logging the query string. Find a catalog 404 produced by the app, a catalog 404 when the script was moved, and the gateway failure. A blank or dash upstream value shows that Nginx didn't record an upstream status for that request. The app's 404 has its own upstream response. Nginx can record a gateway error as upstream status when an attempt fails, so compare the private error log as well. This approach is more rigorous than treating every number branded 404 as a missing file or assuming every 502 error must come from an application program.

Step 5. Separate an incomplete request from a failed gateway

Now that both routes work, test a subtler configuration error. Keep the working socket and script but remove the parameter passing the query to the PHP worker. The caller still sends ?sku=MILK-1. Predict whether the response should resemble the wrong-socket 502 or the application’s earlier input error. The distinction matters because the web server could successfully connect to a useful worker even while sending it incomplete data. An independent SQL read remains a control in this case too.

python3 - "$lamp_lab/nginx.known-good" "$lamp_lab/nginx.conf" <<'PY'
from pathlib import Path
import sys

source = Path(sys.argv[1]).read_text()
query = "            fastcgi_param QUERY_STRING $query_string;\n"
marker = 'return 200 "route-good'
assert source.count(query) == 1 and source.count(marker) == 1
Path(sys.argv[2]).write_text(source.replace(query, "").replace(marker, 'return 200 "route-no-query'))
PY
ngx -t
ngx -s reload
await_version route-no-query
expect inventory.test '/catalog.php?sku=MILK-1' 400
grep -Fq 'invalid sku' "$lamp_lab/lemp-response"
test "$(sql -e "SELECT stock FROM dairy_catalog.products WHERE sku = 'MILK-1';")" = 13
expect receipts.test /index.html 200
grep -Fxq 'receipts-control-v1' "$lamp_lab/lemp-response"
cp "$lamp_lab/nginx.known-good" "$lamp_lab/nginx.conf"
ngx -t
ngx -s reload
await_version route-good
expect inventory.test '/catalog.php?sku=MILK-1' 200
expect_stock MILK-1 'Plain Milk' 13
expect inventory.test '/catalog.php?sku=CURD-2' 200
expect_stock CURD-2 'Set Curd' 0

The small script copies the known-good text to a candidate and verifies that exactly one query parameter line goes away. It checks a reload marker before sending the original request. Its new result is 400 with the catalog's input error, which tells you PHP ran and found no usable key. If you thought that 400 could only come from the customer's browser misbehaving, the experiment shows an important counterexample. The browser's visible URL was unchanged. A service boundary failed to forward part of it. An Nginx operator can now distinguish three different states using the same milk URL: a broken FastCGI address gives 502, a reachable PHP worker that receives no query gives 400, and a complete route gives 200 with the stored stock.

After restoring, use both valid SKUs to prove more than one business example. A badly configured route could supply MILK-1 as a fixed default and pass one product case. The curd request would then fail its semantic comparison even if the status still looked healthy. Candidate acceptance should test the range of meaningful values. This is also useful when deciding which information belongs in the HTTP forwarding configuration and which behavior belongs in application code. The worker should see the intended request, validate it itself, and send a response the caller can interpret.

Step 6. Clean up the isolated fixture

lemp_cleanup
trap - EXIT
test ! -e "$lamp_lab"
printf 'Private LEMP fixture removed.\n'

The new trap wraps the previous fixture cleanup. First it stops the recorded Nginx process. Then it lets the original cleanup stop PHP-FPM and MySQL and remove the files under their private directory. The final check covers both test sites, the log files and database data. No machine-wide service unit, firewall or DNS setting was changed. If you launch your own cloud instance to run the lesson, remove the instance or other cloud resources you specifically created after you have captured the exercise results you need.

Plan an actual transition without composing unrelated changes

Suppose this service already has a real domain with traffic and the team wants to migrate from Apache to Nginx. Start by collecting a few known requests that represent real behavior: a static resource, a valid product request, a missing product, a non-catalog URL, and whichever form or API methods the real site accepts. For each case record the input URL and method, expected status, relevant response headers and an expected body property. If requests are signed or rely on cookies, record which feature matters without saving actual customer credentials. Match a fixed release, fixture or read-only query so a natural stock change doesn't appear to be a regression.

List what Apache currently does for the site before configuring its substitute. A long-running virtual host may apply redirects, compression or special caching. It may protect a staff section with an authentication rule. A framework may rely on routing any requested path through an index script. Files under an authentication-protected directory, for example, must remain protected after the change. Copying the public files and checking the homepage will not exercise those conditions. Translate the intended HTTP behavior using Nginx mechanisms, including exact intentional routes and permissions, and verify specific examples rather than assuming Apache directives rename cleanly.

Many real applications want URLs like /products/MILK-1 rather than a visible PHP filename. Such an application might use one front controller, meaning one script receives many application route paths and chooses a handler internally. This lesson deliberately uses a simpler explicit script URL. For a front controller, first identify what path the framework expects under FastCGI. Check that the routing fallback does not serve arbitrary PHP source or turn missing assets into mysterious successful application responses. Verify canonical redirects preserve query values where intended and check that public error behavior remains intelligible. Test a negative path outside the approved set along with the happy path.

Map all work crossing the executable boundary. Write down the selected PHP-FPM service or pool, worker identity, socket or network endpoint, absolute script location and required extensions. A pool groups PHP worker processes under its own settings. Two deployed sites can use different pools when privileges or application settings differ. A configuration may legitimately point them at different socket paths. Compare against the actual listen value instead of a guessed versioned path. Review the target environment separately from the old one. Different configuration files, system packages and optional security policy can lead to different behavior even with the same PHP source.

When the two HTTP servers run on the same instance, plan listener ownership. Apache and Nginx cannot ordinarily claim the same address and port as independent servers. A candidate on a private high port gives you a place to test planned headers, roots and handler rules. The intended loopback URL, explicit host name and site marker are tools to confirm the current target. Treat a production port or existing reverse proxy switch as a separate controlled release. Decide what resource is the entry point and how to revert that resource before switching traffic. Keep hosted test ports private and check who can reach the candidate.

For a delivery with a real TLS certificate, verify the public hostname, the certificate name and the endpoint that terminates TLS, meaning the component that accepts the encrypted client connection. A correct test with HTTP and a custom hostname on a private port does not verify that a real client recognizes your TLS certificate. Separately test the intended production scheme and redirects at a controlled stage. If an upstream component terminates TLS or performs authentication, record which forwarded information the app trusts. Produce a separate check for any important external boundary rather than assuming the test socket presented the same conditions.

Choose a small cutover or staging window with an observable dispatch path and an available rollback. One possible safe rehearsal routes an internal tester to Nginx while public traffic remains on the current service. The tester captures the expected host and path behaviors, confirms the neighboring site and compares the dynamic response with an independent SQL read. The database, credentials and stock schema can stay unchanged for this rehearsal. Updating them in the same release would add uncontrolled variables. If a new schema or engine is genuinely needed, plan that change and its own reversal separately, including how reads and writes behave across both versions.

Suppose staging receives valid JSON for milk and curd but receipts begins returning the inventory help marker. Stop forwarding traffic to the candidate while diagnosing. The catalog data passed, but a neighboring site boundary failed. Look at the responding Nginx server block, the listener defaults and the actual request Host. A change to the PHP worker would not fix wrong host selection for a static page. The rollback checks should restore the expected response for each planned host, including redirects or restrictions the catalog may have inherited from the original environment.

Once a change is active, compare observation windows. Record the before and after status mix, latency and FPM log errors around the cutover. Measure completed actions that matter to users, such as successful stock lookups, in addition to the server's process status. Static requests dominate many site logs, and a healthy static average can disguise problems concentrated at the PHP location. Rehearsed database read checks offer direct evidence but should be limited to a known workload. Take care when measuring private details. Keep logs to the useful path and timing fields and avoid logging secret query values.

Diagnose on the permission boundary or the content boundary

A small difference in evidence changes what you investigate. Suppose /index.html succeeds on both test hosts, and an inventory request records site=inventory.test uri=/catalog.php code=502 fcgi=502. The entry point and host survived. If the error log says the Unix socket path does not exist, note the exact configured path and look for the FPM master's listen setting. Package names might include whichever PHP major and minor version is actually installed. Recreating a symbolic link to a guessed socket without checking the underlying process can conceal an older pool or send requests to the wrong application. Correct the intended system endpoint, then prove the script and returned values again.

A Unix socket has permissions, and a process often also needs permission to traverse the containing directory. If the socket exists but Nginx receives a permission error, determine which user is running the worker. The configured administrative user in an SSH shell is not necessarily the one Nginx uses for connections. FPM pool settings such as listen.owner, listen.group and listen.mode can matter for regular host-level deployment. Mandatory access controls such as SELinux or AppArmor may apply depending on the operating system and service packaging. Check the actual denial evidence and narrow permissions for the intended consumer. The same-account fixture demonstrates the route without claiming to test every platform's mandatory policy.

Now suppose both static pages are fine and /catalog.php?sku=MILK-1 returns the application's invalid sku message. The presence of the application message proves that a worker executed at least part of the PHP script. It also points away from the SQL login because that guard returns before opening the database. Compare the shape received by PHP with the actual URL and inspect the configured FastCGI query parameter. An accidentally replaced QUERY_STRING can make all products look malformed. Repair that input boundary and test with at least two distinct item values to catch a copy-pasted fixed key.

For a third symptom, assume the dynamic result is valid but always contains seven after the same authorized SQL client says thirteen. Check that the PHP process actually reaches that SQL instance. A second schema or a connection from another pool can point to a different store. Compare the active site and pool, the private settings without printing secrets, and a known row tied to the test environment. Caching at an upstream HTTP layer or in the application can also affect freshness. The lab's dynamic data has an explicit no-store policy. A deployment with caching should spell out when an old result is acceptable and prove its actual behavior after an update.

An explicit allowed script still requires careful file placement. Keep source backups, credentials, environment files and logs outside the public tree. Avoid letting browser-writeable uploads land in a script-executable location. A separate static directory or service can make that boundary easier to reason about. Nginx identifies a file using its rules while the operating system enforces private visibility and ownership. PHP, the database and other program components each enforce their own boundaries. A passing case at one boundary does not remove the need for checks at the rest.

During a real incident, preserve the observations that distinguish a suspected app defect from a failed transport. State which hostname and path returned the error, which layer supplied its body and whether the independent SQL check passed. Record a time or request ID and the exact active configuration marker when available. When you restore a service, check the real public behavior and the important unaffected case. Restoring only a green process indicator creates very little evidence about what the next customer will receive.

Practise explaining the route as well as fixing it

Interview answers

Can Nginx serve a PHP file without PHP-FPM?

Nginx needs a configured way to hand dynamic PHP execution to a worker or another backend that can run the code. Here the FastCGI socket reaches PHP-FPM. A static file does not require FPM and is served as ordinary content. Without appropriate routing, simply placing a PHP file among static files may leave it unserved or expose source in an incorrect configuration. Test a known rendered output through the intended entry point.

How do two websites share a route name on a single Nginx listener?

Server selection is based on address and port and then the host, with an explicit default receiving unmatched requests. Location selection happens in the chosen server. inventory.test permits /catalog.php, while receipts.test returns 404 for the same path. Pass the hostname with the request and verify both sites before claiming that a shared port is configured correctly.

Why can a successful configuration test be followed by a 502?

The syntax test can accept a well-formed Unix socket path without connecting to its application. Once activated, the location attempts a real connection for requests. The lab's failed candidate names an absent path, so the runtime request gets Nginx's gateway error. Pair a syntax test with a real response and check the private log for the target name.

What changes in an Apache-to-Nginx migration if PHP and MySQL stay?

The externally visible contract may remain the same, but the work that translates incoming requests to files and FastCGI changes. Reproduce the script selection, query forwarding, redirects, auth and relevant errors. Confirm which FPM pool and database the candidate uses. Check static and dynamic content from the intended virtual host before and after cutover.

Predict each result before opening the answer

The inventory app returns “unknown sku” for MILK-9. Which boundary most likely produced the 404?

The running PHP application. The exact path matched the catalog location, the query shape was valid, and the application supplied that body when its SQL lookup found no row. Compare the body and upstream status with Nginx's earlier rejection of /invented.php.

After changing only FastCGI's destination, should receipts still serve its control file?

Yes. The receipts location is in another server block with a separate root and no FastCGI requirement. Testing it protects a neighboring service even though the two names share a listener. The expected marker is stronger evidence than a bare 200.

After rollback restores the good socket, should milk stock be seven or thirteen?

Thirteen. The HTTP route rollback does not undo the earlier SQL update. The independent SQL read verifies that quantity. Compare the typed JSON output to it once the original configuration marker returns.

Apply the method to another request

  1. Predict the Nginx status, presence of an upstream response and expected output for the inventory static URL, the unknown product and the wrong-socket request. After the lab compare all three with the log and write a one-sentence explanation of each boundary.
  2. Describe a release check for a real application that depends on a protected staff path. Include a successful authorized interaction and the expected result for an ordinary visitor. Keep the test separate from the stock write so you know which behavior changed if something fails.
  3. During a fresh run, add another safe fixture SKU using the independent SQL admin session. Give it a distinct description and a small known quantity. Show that the exact same Nginx route returns the new body based on the query value. Then try an unassigned hostname with the same URL and confirm it cannot reach that app.

Host before application

Confirm the listener and virtual host before debugging a PHP path. A neighboring host is a useful independent control.

Path and query are separate

Location selection maps the path. FastCGI forwards the query string for the PHP code to validate and use.

Check two kinds of 404

Compare HTTP body and upstream evidence to tell a rejected route from an application that found no data.

Reload and verify

Activate a known candidate, confirm the HTTP marker, then test data and the unaffected site before declaring recovery.

Official references