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

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

AWS Cloud

12.2 LAMP stack

Friends, LAMP is a longstanding combination for applications such as WordPress. Let’s trace how Apache runs PHP and how PHP reads MySQL or MariaDB data.

One common arrangement keeps all components on a single Linux machine. Apache receives the HTTP request, a PHP module or PHP-FPM executes the script, and the PHP code reads the database through a private Unix socket or TCP connection. The virtual host sets the actual document root.

Full LAMP installation

Choose the package and service instructions for your Linux release and the application’s supported PHP version. The steps below run a private exercise with explicit Apache, PHP-FPM and MySQL executables.

  • Amazon Linux 2023. Use the AL2023 LAMP installation tutorial to identify the matching Apache, PHP and database packages. AL2023 uses DNF and the tutorial uses MariaDB.
  • Ubuntu. Follow the Ubuntu Apache guide and PHP installation guide. Check which installed release, PHP handler and database engine your app needs before enabling services.
  • CentOS Stream. Check supported packages and configuration for the chosen release and repositories. Confirm the actual service units and application permissions on the target image.

Test the stack

Start with a known static page, then test a real application lookup against a known database row. Check the HTTP status and returned values and compare the row with an independent SQL query. Keep worker credentials and private diagnostic logs outside the public document root. The private catalog exercise below covers setup, specific results and cleanup.

Ravindra Bagale's Tip

In an interview, don't just expand the acronym. Draw the request flow: browser → web server → language runtime → database, and mention the ports and process managers. That shows you actually deployed the stack, not just memorised it.

Lab

खाली दिलेल्या खाजगी lab मध्ये static पान आणि PHP catalog वेगवेगळे तपासा. थेट SQL query मधला stock आणि HTTP response मधला stock सारखा आहे का ते पाहा. शेवटी lab मधील तात्पुरत्या सेवा आणि फाइल्स काढा.

A stock count that changes without editing the website

Imagine running a small dairy shop with two products in a catalog. In the morning the counter opens with seven cartons of plain milk. At lunch a delivery brings four more. The shop's page should show eleven once the operator records the delivery. The person placing the order should not need to edit an HTML document, rebuild the site or know any database passwords. The team needs one place to record the stock and a repeatable path that reads it for visitors.

You can begin with two links. The first, /index.html, explains what the catalog does. Those words stay the same through the day, so they can live in a file. The second, /catalog.php?sku=MILK-1, must consult the latest record. For that link, the bytes sent to the browser are generated when someone requests them. The work is different even though the two links use the same host and port. This difference between serving a file and running a program is the useful starting point when somebody says a site is built on the LAMP stack.

The letters usually expand to Linux, Apache, MySQL and PHP in this course. Linux is the operating system that provides processes and filesystem permissions. Apache HTTP Server accepts browser requests and chooses their handler, meaning the part of the server responsible for the response. MySQL stores and queries rows. PHP is the programming language and runtime used here to turn a requested code into a database lookup and then into a response. Some installations use MariaDB for the database. Study your chosen software's support policy, SQL behavior, authentication and backups as its own system. The architecture can look similar while important operational details differ.

The layers describe responsibilities. They can run together on one Linux virtual machine or across multiple services. A lab on a different operating system can exercise the same roles using the actual Apache, PHP and MySQL programs available there. It demonstrates the Apache-to-PHP-to-database links, while package installation, boot management and filesystem labels remain platform-specific. An EC2 instance is a virtual server. Its operating system, application processes, permissions and installed packages remain your team's responsibility in this setup.

PartQuestion for this shopUseful evidence
Linux or other lab operating systemCan the right process open a file or socket, and on what address is the service listening?Actual process user, file and socket permissions, listening port
Apache HTTP ServerDoes the requested URL go to a file or to PHP?Access log, selected virtual host and handler, static control request
PHPWhich SKU was accepted, and what should happen if the row or database is unavailable?Validated input, CSS-independent response body, PHP worker logs
MySQLWhich row is stored, and may this account read it?Independent query for that key and narrowly scoped grants

Follow the distinction between the visitor, the Apache process, the PHP process and the database account. These are different identities. The visitor sends an HTTP request. An operating system user runs the PHP worker and controls which local files and sockets it may open. The worker logs into the database using a database identity. MySQL makes its own permission decision after that connection is established. Giving the Apache process write access to the site files does not grant the PHP application permission to change database rows. Granting SQL permissions does not repair a missing PHP socket.

Start with the earlier stack-roles lesson if the difference between entry point, runtime and persistence is unfamiliar. Use the later LEMP lesson to compare a different HTTP server while retaining the PHP and SQL concepts. Keep the sample shop in mind across these pages so the working parts have names.

Follow the requested product through three connections

Suppose the visitor requests GET /catalog.php?sku=MILK-1 from Apache. The word GET is the HTTP method, conventionally used to retrieve a representation. The first question mark introduces the query string. The path before it selects the catalog script. The query value after it gives PHP a lookup key. A query string is part of the URL. It can appear in browser history and access logs, so the SKU is appropriate there but secrets are not.

  1. The browser speaks HTTP to Apache. Apache has a listening socket, which is the endpoint where a process can receive connections. It accepts this request, selects the server configuration for it and matches the handler for catalog.php. The same listener can respond to the static help page, but that path takes no trip through PHP. A correct Apache access-log entry proves that the request reached this Apache instance, even if a later layer fails.
  2. Apache passes execution to a PHP worker. This lab uses FastCGI, a protocol for passing request data and receiving output from a long-running program. Apache uses its proxy and FastCGI modules. PHP-FPM, the PHP FastCGI Process Manager, owns a pool of worker processes. Apache passes details such as the script path and query string to a worker. The process manager starts and manages the pool. Attaching a FastCGI rule to Apache does not itself launch FPM.
  3. PHP asks MySQL for one row. The PHP code receives MILK-1, verifies it has the agreed shape, and uses PDO, PHP Data Objects, with the PDO MySQL driver. PDO supplies the interface for things such as preparing and executing statements. The driver speaks to the chosen database. This example supplies a Unix socket location, a database name and an account with permission to select from the products table. A Unix socket is a local communication endpoint represented by a filesystem path. It is different from a network port and cannot be reached by sending a packet from another computer.
  4. The response travels back. MySQL returns the matching row to PHP. PHP creates an HTTP result with a status and a JSON body, an agreed structure for representing data. Apache sends the resulting response back to the visitor. Initially the body represents MILK-1 with seven cartons. A later request can show eleven when an authorized operator changes that same row. The static help page keeps its original marker through both requests.

On this particular machine there are three connection boundaries: a local HTTP TCP port, a local FastCGI socket and a different local MySQL socket. TCP is a network transport used here for HTTP even on the same computer. The two Unix socket files belong to different processes and carry different protocols. Pointing Apache's FastCGI rule at the database socket would not connect PHP to MySQL. Similarly, the browser does not send HTTP straight to the database. On an EC2 installation you might instead use a private network database endpoint, often with a TLS requirement. In that case the PHP connection goes over the network while the browser's public entry point can still be Apache.

An older or differently packaged Apache site can execute PHP through an Apache module, often called mod_php. In that layout PHP executes inside an Apache worker, so there is no separate PHP-FPM socket for those requests. You still have an HTTP handler, PHP application code and the database connection. Read the site configuration before trying to debug the process. The presence of a PHP command-line tool proves that the shell can run PHP; it does not identify the web execution method. Apache may serve static files while a separate PHP-FPM process is stopped. In a module setup an FPM service may correctly be absent.

A document root maps URLs to content on disk. In the shop it contains the public index and catalog script. Runtime settings such as the database password are neither visible paths in the site's document root nor text appended to a URL. In the lab the secret is a random temporary value held in the PHP pool's private configuration and passed to the worker's environment. Apache's public directory is its own child of the lab directory. Those boundaries still matter when all processes share one machine.

Model what the app may look up and what the operator may change

The shop uses a short stable stock-keeping unit, or SKU, for each product. The description can be edited when the name on the shelf changes. The SKU remains the reference in orders and links. The database table products holds sku, name and stock. Each row describes one product. A primary key marks the column whose values uniquely identify rows. With the SKU as that key, the data model gives the catalog at most one result for an exact SKU lookup. The example only accepts uppercase letters, digits and a hyphen in the public identifier.

SKUProduct nameOpening quantityCatalog interpretation
MILK-1Plain Milk7Existing product with stock available
CURD-2Set Curd0Existing product, currently out of stock
MILK-9No stored rowNoneUnknown product

The initial result for the first row could be the JSON object {"sku":"MILK-1","name":"Plain Milk","stock":7}. A caller should see a numeric stock value instead of a string or an omitted field. Zero differs from an absent row. The curd response returns a regular success with zero even though there is nothing to sell. An unknown SKU returns 404 with an error body from the catalog logic. An ill-formed SKU returns 400 before PHP goes to the database. These rules describe the API contract, meaning the inputs and responses that other code or people can rely on.

PHP prepares the SQL statement with a placeholder for the input. Preparing defines the structure of a query. Executing it supplies the value for the placeholder. The application chooses the table, columns and comparison. The visitor supplies a value for that one comparison. The application also validates the value separately because even safe parameters can describe unusable inputs. If a later version lets a visitor choose the sort order, the developer must map allowed choices to fixed column names. A bound parameter stands for a value and does not dynamically stand in for a column name or other SQL syntax.

Our public catalog only reads stock, so its SQL account can select from this one table. This is an application of least privilege, the practice of giving an identity only the permissions needed for its task. Loading the seed data and making the stock adjustment use a separate administrative connection on a private lab socket. The exercise keeps a genuine permission boundary while taking a shortcut for local administration. In a real shop give an operator or stock service only the write access it needs, restrict administrative access further, and preserve an audit trail for stock changes. A browser clicking a product link does not receive either SQL credential.

PDO asks for an associative array, so sku, name and stock arrive as named fields. The response deliberately casts stock to an integer before encoding JSON, giving clients a reliable number regardless of a driver's scalar conversion. If a site instead shows HTML, it also needs output encoding for data inserted into the page, even though its database statement is prepared. SQL parameters handle the query boundary. Correct response encoding handles how a client interprets data at its own boundary.

The shop cannot tell a visitor a product is absent merely because the SQL connection failed. The catalog uses a temporary unavailability response in that case. The detailed SQL error goes to a private log without including the code's credential. A warning on a public page could confuse the visitor or expose internal hostnames and paths. The separate health cases in this practice let you see the difference instead of mapping all unexpected outcomes to a vague success or failure message.

Run a private Apache, PHP and MySQL catalog

The exercise uses three actual programs and a separate working directory. It is designed for a disposable machine or a local account with an Apache 2.4 executable and its modules, PHP CLI and FPM of a compatible release with PDO MySQL enabled, Oracle MySQL Community Server 8.4 and its client, Bash, curl and Python 3. Run the blocks from one regular-user Bash session. Use executable paths from your own platform if the package names or standard directories differ. The shell code starts no installed system service, uses no sudo and opens no external listener. If you only have MariaDB, read through the behavior and use the matching documented initialization and server options for MariaDB in a separate environment. The Oracle MySQL data-directory startup in these blocks is specific to that implementation.

A hosted lab machine is also fine if you run the curl commands on that machine. Loopback means the program is listening to the same operating system that ran it. If you type its loopback URL into a browser on a different laptop, that browser asks the laptop itself. Use the learning tests locally where you ran the exercises. Reserve TCP port 18902 on that machine. If another process uses it, select a different free high port with LAMP_PORT before starting. Every subsequent block reads the same value. The FPM and MySQL listeners use local sockets inside the temporary folder.

Step 1. Identify the installed tools and create an empty lab workspace

set -eu
if [ "$(id -u)" -eq 0 ]; then
  printf 'Run this as a regular user.\n' >&2
  exit 1
fi
apache_bin=${APACHE_BIN:-$(command -v apache2 || command -v httpd || true)}
php_bin=${PHP_BIN:-$(command -v php || true)}
fpm_bin=${PHP_FPM:-$(command -v php-fpm || true)}
mysqld_bin=${MYSQLD_BIN:-$(command -v mysqld || true)}
mysql_bin=${MYSQL_BIN:-$(command -v mysql || true)}
for bin in "$apache_bin" "$php_bin" "$fpm_bin" "$mysqld_bin" "$mysql_bin"; do
  if [ ! -x "$bin" ]; then
    printf 'Set APACHE_BIN, PHP_BIN, PHP_FPM, MYSQLD_BIN or MYSQL_BIN as needed.\n' >&2
    exit 1
  fi
done
command -v python3 >/dev/null
command -v curl >/dev/null
"$php_bin" -r 'exit(extension_loaded("pdo_mysql") ? 0 : 1);'
"$mysqld_bin" --no-defaults --version
mysql_base=${MYSQL_BASEDIR:-$(python3 - "$mysqld_bin" <<'PY'
import pathlib
import sys
print(pathlib.Path(sys.argv[1]).resolve().parents[1])
PY
)}
lamp_port=${LAMP_PORT:-18902}
umask 077
lamp_lab=$(mktemp -d /tmp/rb-lamp.XXXXXX)
printf 'Private lab: %s\n' "$lamp_lab"
apache_pid=
fpm_pid=
mysql_pid=
stop_child() {
  if [ -n "$1" ]; then
    kill -TERM "$1" 2>/dev/null || true
    wait "$1" 2>/dev/null || true
  fi
}
lamp_cleanup() {
  stop_child "$apache_pid"
  stop_child "$fpm_pid"
  stop_child "$mysql_pid"
  case "$lamp_lab" in
    /tmp/rb-lamp.??????) rm -rf -- "$lamp_lab" ;;
  esac
}
trap lamp_cleanup EXIT
mkdir "$lamp_lab/db" "$lamp_lab/db-tmp" "$lamp_lab/public" "$lamp_lab/run"

Use the full path to the installed executables if your shell can't find them. Some distributions use a versioned FPM command. Setting PHP_FPM to its executable selects that release without changing a system default. The CLI extension check is an early hint. The actual HTTP test later determines whether the FPM worker loaded it as well. An Oracle package in a zip or tar typically stores its binaries in a bin directory immediately under its base. The code derives that base from the resolved server executable. Set MYSQL_BASEDIR explicitly if your vendor installation has a different layout.

The temporary directory and default permissions keep files private to the learning account. All created configuration, payloads, and logs go under it, including the application's document root. At shell exit the cleanup function signals the recorded children, waits for them and then removes the temporary fixture. Keep the printed directory path for diagnosis while the session is open. If you want to practice interactively and collect private logs, run each block from the same shell, then finish with the cleanup step. Never substitute a working data directory for this empty directory.

Step 2. Initialize the isolated database and give the catalog one grant

"$mysqld_bin" --no-defaults --initialize-insecure \
  --basedir="$mysql_base" --datadir="$lamp_lab/db" \
  --log-error="$lamp_lab/mysql-init.log"
sql() {
  "$mysql_bin" --no-defaults --protocol=SOCKET \
    --socket="$lamp_lab/mysql.sock" --user=root --batch --skip-column-names "$@"
}
start_mysql() {
  "$mysqld_bin" --no-defaults --basedir="$mysql_base" --datadir="$lamp_lab/db" \
    --tmpdir="$lamp_lab/db-tmp" --skip-networking --mysqlx=OFF \
    --socket="$lamp_lab/mysql.sock" --pid-file="$lamp_lab/run/mysql.pid" \
    --log-error="$lamp_lab/mysql.log" &
  mysql_pid=$!
  for attempt in $(seq 1 40); do
    if sql -e 'SELECT 1' >/dev/null 2>&1; then return 0; fi
    if ! kill -0 "$mysql_pid" 2>/dev/null; then break; fi
    sleep 0.25
  done
  printf 'MySQL did not become ready. Read %s/mysql.log.\n' "$lamp_lab" >&2
  return 1
}
start_mysql
db_pass=$("$php_bin" -r 'echo bin2hex(random_bytes(16));')
sql <<SQL
CREATE DATABASE dairy_catalog CHARACTER SET utf8mb4;
CREATE TABLE dairy_catalog.products (
  sku VARCHAR(16) PRIMARY KEY,
  name VARCHAR(80) NOT NULL,
  stock INT UNSIGNED NOT NULL
);
INSERT INTO dairy_catalog.products VALUES
  ('MILK-1', 'Plain Milk', 7), ('CURD-2', 'Set Curd', 0);
CREATE USER 'catalog_reader'@'localhost' IDENTIFIED BY '$db_pass';
GRANT SELECT ON dairy_catalog.products TO 'catalog_reader'@'localhost';
SQL
sql -e 'SELECT sku, name, stock FROM dairy_catalog.products ORDER BY sku;'
sql -e "SHOW GRANTS FOR 'catalog_reader'@'localhost';"

Initialization writes MySQL's own internal files to the empty data directory. The special local bootstrap account has no password in this disposable fixture so the first administrative connection is straightforward. It remains confined to an account-private directory and a socket-only server, with MySQL X Protocol disabled as well. This is a deliberate test choice. A real server needs authenticated administrative access and its own secure setup procedure. These calls start an independent instance with option files disabled. They have no reason to stop, configure or reset the system's regular MySQL service.

The start function checks a real database query. A newly created socket by itself would tell you a listener path exists. A successful SELECT 1 proves that the supplied client, socket and administrator agree enough to execute SQL. A launch message printed before this result could arrive while initialization is still underway. If startup returns an error, capture the private error log before replacing components. For example, a path that resolves under an incompatible installation can fail before the network issue you were trying to test even exists.

Expect two rows in ascending SKU order, with CURD-2 and zero first, then MILK-1 and seven. The grant display normally includes a general USAGE line plus the specific table SELECT permission. USAGE is not permission to query everything. The specific grant is the useful part to read. This output is from an independent administrative client. You will compare it with the HTTP behavior later. The temporary credential is generated by PHP and never passed to a shell command's public argument list. Avoid shell tracing when running the setup because it can repeat expanded values in terminal logs.

Step 3. Add the public files and configure the private PHP worker

cat > "$lamp_lab/public/index.html" <<'HTML'
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Private dairy catalog</title>
<h1>Dairy catalog</h1>
<p>catalog-help-v1</p>
<p><a href="catalog.php?sku=MILK-1">Read current milk stock</a></p>
</html>
HTML
cat > "$lamp_lab/public/catalog.php" <<'PHP'
<?php
declare(strict_types=1);

function send_json(int $status, array $body): void {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    echo json_encode($body, JSON_THROW_ON_ERROR), "\n";
}

$sku = $_GET['sku'] ?? '';
if (!is_string($sku) || !preg_match('/\A[A-Z0-9-]{1,16}\z/', $sku)) {
    send_json(400, ['error' => 'invalid sku']);
    return;
}

try {
    $db = new PDO(
        'mysql:unix_socket=' . getenv('CATALOG_DB_SOCKET')
          . ';dbname=dairy_catalog;charset=utf8mb4',
        'catalog_reader',
        getenv('CATALOG_DB_PASSWORD'),
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
         PDO::ATTR_EMULATE_PREPARES => false]
    );
    $query = $db->prepare('SELECT sku, name, stock FROM products WHERE sku = ?');
    $query->execute([$sku]);
    $row = $query->fetch(PDO::FETCH_ASSOC);
    if ($row === false) {
        send_json(404, ['error' => 'unknown sku']);
        return;
    }
    $row['stock'] = (int) $row['stock'];
    send_json(200, $row);
} catch (PDOException $error) {
    error_log('catalog database operation failed; SQLSTATE=' . $error->getCode());
    send_json(503, ['error' => 'catalog temporarily unavailable']);
}
PHP
"$php_bin" -l "$lamp_lab/public/catalog.php"
cat > "$lamp_lab/fpm.conf" <<FPM
[global]
pid = $lamp_lab/run/fpm.pid
error_log = $lamp_lab/fpm.log
daemonize = no

[catalog]
listen = $lamp_lab/fpm.sock
listen.mode = 0600
pm = static
pm.max_children = 1
clear_env = yes
env[CATALOG_DB_SOCKET] = $lamp_lab/mysql.sock
env[CATALOG_DB_PASSWORD] = $db_pass
security.limit_extensions = .php
php_admin_flag[display_errors] = off
php_admin_flag[log_errors] = on
php_admin_value[error_log] = $lamp_lab/catalog-php.log
FPM
unset db_pass
"$fpm_bin" -t -y "$lamp_lab/fpm.conf"
"$fpm_bin" -F -y "$lamp_lab/fpm.conf" &
fpm_pid=$!
for attempt in $(seq 1 40); do
  if [ -S "$lamp_lab/fpm.sock" ]; then break; fi
  if ! kill -0 "$fpm_pid" 2>/dev/null; then break; fi
  sleep 0.25
done
test -S "$lamp_lab/fpm.sock"

The public HTML is a static control. The PHP file is a dynamic endpoint and a small application with its own answers. The quoted here-documents tell the shell to write the source literally, so the shell does not expand PHP variables such as $sku. FPM's unquoted block is different. That block needs the shell to write the real local socket path and generated secret to its private configuration. The guard can reject a PHP array in the query string as well as an unacceptable SKU string. That protects the program's assumption that the lookup uses one short text value.

One worker is enough to study a single request. A real server pool's worker count, runtime memory, queueing and timeouts should be chosen using an actual workload. The PHP socket is accessible to the current user only in this lab, and Apache is launched as that same user. A deployed installation often uses separate operating system users with carefully planned socket access. Changing the socket to be world-writable is unnecessary for this exercise.

Expect a syntax success from PHP and a successful FPM configuration test. With the documented single -t option, FPM checks configuration. Avoid asking it to dump the complete live pool settings, since those settings include a temporary credential. Every local worker will receive the variables explicitly listed in the config. Clearing inherited environment variables helps demonstrate that the password is supplied deliberately to the process intended to use it. The effect of package default ini paths still varies, so an end-to-end check is required.

Prove the path with requests, one update, and a dependency failure

Step 4. Give Apache exactly one PHP handler

module_dir=${APACHE_MODULE_DIR:-}
if [ -z "$module_dir" ]; then
  for candidate in /usr/lib/apache2/modules /usr/lib64/httpd/modules /usr/lib/httpd/modules /usr/libexec/apache2; do
    if [ -r "$candidate/mod_proxy_fcgi.so" ]; then
      module_dir=$candidate
      break
    fi
  done
fi
compiled=$("$apache_bin" -l)
load_module() {
  local name=$1
  if ! printf '%s\n' "$compiled" | grep -Eq "(^|[[:space:]])mod_${name}\.c$"; then
    test -r "$module_dir/mod_$name.so" || return 1
    printf 'LoadModule %s_module "%s/mod_%s.so"\n' "$name" "$module_dir" "$name"
  fi
}
{
  printf 'ServerRoot "%s"\n' "$lamp_lab"
  if ! printf '%s\n' "$compiled" | grep -Eq '(^|[[:space:]])(event|worker|prefork|mpm_event|mpm_worker|mpm_prefork)\.c$'; then
    load_module mpm_event
  fi
  for name in unixd authz_core dir log_config proxy proxy_fcgi; do
    load_module "$name"
  done
  cat <<APACHE
ServerName localhost
Listen 127.0.0.1:$lamp_port
User "#$(id -u)"
Group "#$(id -g)"
PidFile "$lamp_lab/run/apache.pid"
DefaultRuntimeDir "$lamp_lab/run"
ErrorLog "$lamp_lab/apache-error.log"
LogFormat "%m %U %>s" catalog
CustomLog "$lamp_lab/apache-access.log" catalog
ProxyRequests Off
DocumentRoot "$lamp_lab/public"
<Directory />
    AllowOverride None
    Require all denied
</Directory>
<Directory "$lamp_lab/public">
    Options -Indexes
    AllowOverride None
    Require all granted
    DirectoryIndex index.html
    <Files "index.html">
        ForceType text/html
    </Files>
    <Files "catalog.php">
        SetHandler "proxy:unix:$lamp_lab/fpm.sock|fcgi://localhost/"
    </Files>
</Directory>
APACHE
} > "$lamp_lab/httpd.conf"
"$apache_bin" -t -f "$lamp_lab/httpd.conf"
"$apache_bin" -f "$lamp_lab/httpd.conf" -DFOREGROUND &
apache_pid=$!
for attempt in $(seq 1 40); do
  if [ -s "$lamp_lab/run/apache.pid" ]; then break; fi
  if ! kill -0 "$apache_pid" 2>/dev/null; then break; fi
  sleep 0.25
done
kill -0 "$apache_pid"
test "$(tr -d '[:space:]' < "$lamp_lab/run/apache.pid")" = "$apache_pid"
lamp_url="http://127.0.0.1:$lamp_port"

This configuration allows the HTTP worker to serve one directory. It enables a FastCGI handler only for the exact filename used by the exercise. The Unix socket before the vertical bar is the actual destination for the FastCGI connection. The hostname that follows the bar in this handler notation is part of Apache's FastCGI target representation. It does not create a second listener on an ordinary public HTTP port. ProxyRequests Off keeps forward proxying off and does not prevent the configured PHP handler from forwarding to the private application socket. A forward proxy would accept client requests to fetch other destinations, which this catalog doesn't need.

The module checks account for some builds compiling a component into the server. File paths for separately loadable modules vary by system. Check the private configuration with Apache's syntax check, then check that the foreground process writes its own PID. A PID is the number the operating system assigns to a running process. The block compares it with the number recorded when starting the background process. That helps a learner avoid taking a response from an existing process on the same port as proof that the newly configured Apache started.

Step 5. Check data behavior against the SQL client

http_check() {
  local path=$1 expected=$2 actual
  actual=$(curl --noproxy '*' --silent --show-error --max-time 4 \
    -o "$lamp_lab/response" -w '%{http_code}' "$lamp_url$path")
  printf '%s %s\n' "$actual" "$path"
  test "$actual" = "$expected"
}
check_stock() {
  python3 - "$lamp_lab/response" "$1" "$2" "$3" <<'PY'
import json
import sys
from pathlib import Path

body = json.loads(Path(sys.argv[1]).read_text())
expected = dict(sku=sys.argv[2], name=sys.argv[3], stock=int(sys.argv[4]))
assert body == expected and type(body["stock"]) is int, (body, expected)
print(body)
PY
}
http_check /index.html 200
grep -Fq 'catalog-help-v1' "$lamp_lab/response"
http_check '/catalog.php?sku=MILK-1' 200
check_stock MILK-1 'Plain Milk' 7
http_check '/catalog.php?sku=CURD-2' 200
check_stock CURD-2 'Set Curd' 0
http_check '/catalog.php?sku=MILK-9' 404
grep -Fq 'unknown sku' "$lamp_lab/response"
http_check '/catalog.php?sku=plain_milk' 400
grep -Fq 'invalid sku' "$lamp_lab/response"
sql -e "UPDATE dairy_catalog.products SET stock = 11 WHERE sku = 'MILK-1';"
sql_stock=$(sql -e "SELECT stock FROM dairy_catalog.products WHERE sku = 'MILK-1';")
test "$sql_stock" = 11
http_check '/catalog.php?sku=MILK-1' 200
check_stock MILK-1 'Plain Milk' 11
http_check /index.html 200
grep -Fq 'catalog-help-v1' "$lamp_lab/response"

Write down your predicted status and quantity for each request before running it. The helper saves the body separately from the HTTP status. The data checker parses the JSON and compares all three values and the stock type. Looking for a string anywhere in the response would give a misleading pass if the value occurred in a diagnostic message. The error checks use a known unique phrase after requiring the matching HTTP status. Keeping the static response as a control makes the comparison particularly clear when diagnosing the next step.

The SQL update uses the primary key to change one row. The next direct query confirms what the database stored. The application makes a fresh lookup and sends eleven even though you have not edited either public source file. Its response also tells caches not to store the dynamic body through Cache-Control: no-store. The exercise validates that live reading behavior in this specific path. A real site may intentionally use caching with defined freshness behavior. Then it needs a separate procedure for invalidation or for how long an old count is acceptable.

Step 6. Reproduce one safe fault and restore the same private database

stop_child "$mysql_pid"
mysql_pid=
http_check /index.html 200
grep -Fq 'catalog-help-v1' "$lamp_lab/response"
http_check '/catalog.php?sku=MILK-1' 503
grep -Fq 'catalog temporarily unavailable' "$lamp_lab/response"
grep -Fq 'catalog database operation failed' "$lamp_lab/catalog-php.log"
http_check '/catalog.php?sku=plain_milk' 400
start_mysql
http_check '/catalog.php?sku=MILK-1' 200
check_stock MILK-1 'Plain Milk' 11
printf 'Observed Apache requests:\n'
tail -n 5 "$lamp_lab/apache-access.log"

This stops the process started in the private workspace and keeps its data files. Apache is still listening. The static file response stays healthy. PHP still gets requests and can reject malformed input, but the database-dependent lookup cannot run. The request that looked up milk should return a temporary unavailability response after PHP logs the failed operation. Restarting the same instance reuses the existing data directory. It does not rerun the data seed. A restored answer of eleven is evidence that the earlier change stayed in the database beyond the life of the old database process.

Do not generalize the exact status code to every site. The application explicitly supplies 503 for a PDO error during this lesson. Apache may also produce an error if its own upstream PHP connection fails. A static response paired with an unavailable catalog narrows the issue to the dynamic path. Looking at the response body, Apache's logs and the PHP log differentiates which boundary produced the status. An account failure and a stopped database can both appear as temporary unavailability to the visitor. The private operator should confirm the actual cause before changing permissions or restarting services.

Step 7. Close the private listeners and remove the fixture

lamp_cleanup
trap - EXIT
test ! -e "$lamp_lab"
printf 'Isolated LAMP fixture removed.\n'

Cleanup stops Apache first, then PHP-FPM, then the isolated database. It removes the temporary data directory only after attempting to shut down those three recorded children. The final existence check covers the configuration and logs, including the generated database credential and seed rows. It does not remove installed software and will not touch your system's service setup. On an EC2 lab you provisioned yourself, stop or remove separately created cloud resources through your normal lab cleanup if you no longer need them.

Use two checks to narrow the next problem

Imagine the next morning a learner sees a blank product page and remembers installing PHP the day before. Before changing packages, record the exact URL, time, status and body. A particular host may have multiple websites and private services. Verify that the request went to the expected host and path, over the intended protocol, without falling back to a different site. Then try /index.html and a known valid catalog item. The outcomes form two independent observations of the same Apache listener. The difference between them helps you choose the next piece of evidence.

What you sawNext focused checkWhat that check would mean
Both URLs fail before an HTTP responseLook for the intended listener and the correct local address and portIf nothing is listening where the client connects, inspecting the SQL grant first won't establish an HTTP connection
Apache sends the wrong help pageCompare the selected virtual host and public rootA successful HTTP exchange can still reach the wrong site's files
The static page succeeds, the request for PHP fails in ApacheLook for the FastCGI path permission or connection error in Apache's own logA missing, wrongly owned or unreachable FPM socket can stop the request before PHP interprets a SKU
The catalog gives its own unavailable messageRead the private PHP and SQL logs, then verify the exact configured database targetSome PHP code ran. Investigate driver, socket, authentication, grant and schema using evidence from that failed step
The catalog is successful but returns the wrong numberRead the same key and database independently once, checking host and database nameThe response may have read a different row, reached the wrong database or been cached against expectations
Compare a response with independent process or data evidence before claiming a root cause.

For example, if the direct query still says eleven while the page says seven, verify that the PHP worker connects to the same database instance and to the same named table. On a more complex shop network, an old worker could retain a stale configuration that points to the previous environment. A worker pool can be running normally against a different database that has the same schema. Permissions and connectivity tests can both pass. One distinguishing fixture row, such as a stock count only this lab instance contains, helps prove which data path actually responded. If the server is behind a cache, compare the freshness policy and production behavior using a read-only check before clearing everything.

A separate failure occurs when the SQL login works while the intended SELECT fails. A successful login checks credentials and the connection path. It does not prove permission to access one table or that the table has all expected columns. Compare the account's grants and the deployed schema with the query. With a prepared query, the first error may come from preparing it, executing it, or establishing the connection. Put enough information in an internal log to tell these apart when developing a real service. The public handler's generic error protects those details from the client.

For the exercise, the Apache access log shows the HTTP method, path and final status. It deliberately records the path without query strings. The PHP log records a database operation failure and its code. The MySQL server log reports database lifecycle events. Match evidence by request time while using a private fixture for this small lab. A deployed system should use a safe request ID to join relevant events across layers. Logs can be rotated, filtered or retained for different periods. A missing line is a clue. Prove the correct process was writing to the log before concluding a request never happened.

A PHP source download or visible PHP text is a distinct and serious configuration problem. A web server receiving the request but serving the script as a file has not correctly selected a PHP execution handler. Withhold access to affected PHP files, check the active host and handler rule, and verify through an HTTP request with a known rendered marker before publishing the site. Keep secrets outside the document root and handle any facts about previously exposed credentials using your incident process. Reinstalling SQL cannot repair what Apache does with a file.

Move from a private exercise to a Linux deployment plan

The exercise intentionally sidesteps package and service managers. On Amazon Linux 2023 the command that obtains operating system packages is dnf. AWS's Apache/PHP/MariaDB tutorial names the packages for its release rather than promising that every image has the same PHP stream or database builds. A stream is a maintained package version family. On Ubuntu use its apt repositories and packages for the chosen release. Ubuntu documentation describes PHP running under Apache as a module as well as PHP-FPM for FastCGI. Select one execution model for the application and verify the installed package's expected configuration. Copying a command from another distribution may install its counterpart, a different version, or nothing.

Make a short inventory before choosing commands. Identify the image release and CPU architecture. Confirm the application's supported PHP versions and extensions. Record the intended database engine, version, storage location, backup responsibility and recovery objective. Identify the actual names of the installed services and which need to run. A running service is in use now. An enabled unit is configured to start through the relevant boot or dependency relationships. If you use systemctl on a Linux image with systemd, use it to check both facts where applicable and read the relevant service journal on failure. The regular-user process labels in the lesson do not apply automatically to system package units.

In a first deployment to a disposable EC2 instance, prepare the site in a fresh virtual host with a known document root. Validate private application credentials and permissions before making the public URL available. Test from the instance first, then from the intended user network. Add the desired DNS name and configure TLS before handling real login or order traffic. TLS is the protocol that encrypts the client connection and allows a client to verify the server's identity when configured with the correct certificate and trust settings. A DNS record points a name at a service destination. It does not give Apache permission to serve a folder or make PHP available.

A security group is AWS's network access policy for supported resources and interfaces. Your final design might allow HTTPS to the HTTP entry point from visitor networks. The FPM interface usually stays private to the host. A SQL listener on another AWS service should accept traffic only from authorized application sources, such as the security group attached to the app instances where the configuration supports that. The database should not need inbound traffic from every browser. A connected socket still requires a database login and correct SQL grants. Encrypted network traffic also needs correct trust configuration, especially when crossing the app and database boundary.

If the shop moves data to Amazon RDS for MySQL, record the service endpoint, the configured port and the required connection encryption. The database endpoint is the network name used by the client to connect. A socket filename on the old app machine cannot represent that remote database. Change the PDO connection settings with the approved credential mechanism, test an independent SQL connection from the application environment, then validate the documented HTTP data contract. Confirm the database's collation, meaning its text matching and sorting rules, if SKU letter case affects behavior. Clients should keep getting the same intended JSON field types, success with zero stock and a controlled error for an unavailable store.

Plan rollback in advance. A new PHP file can be reverted, and a known-good Apache host setting can be restored, but changing database tables and data can be harder to undo. Record tested backup and restore steps consistent with how the database is hosted. If you change code and table schema together, consider whether the old code can safely read the newer schema during rollback. A private startup success or a saved SQL dump cannot demonstrate recovery by itself. Restore to an isolated location, verify important records with a direct query, and verify the same application reads the restored data before relying on it for a real incident.

Explain the decisions and test your diagnosis

Interview questions

Which part of LAMP generates a current stock result?

Apache takes the request and hands the catalog path to its configured PHP handler. PHP validates the key and uses PDO MySQL to select the record. MySQL owns the stored quantity and returns the requested row. PHP encodes the record and chooses the status. The final answer involves several roles. In the lab the same Apache provides a file on another path without asking PHP or MySQL to participate.

What does a healthy Apache home page prove?

It proves that the caller reached enough of the HTTP server to receive that page. It says little about whether the same host can execute a PHP script, connect to the particular SQL database and select a row with the intended application account. First check the two paths separately, then use a private log and a direct read of known data if the catalog differs from your prediction.

When are there two local sockets behind Apache, and when might there be none?

The exercise puts FPM and MySQL in separate processes and accesses each through a local socket file. An Apache setup using a PHP module can run PHP in its own worker without that FastCGI socket. A workload with a separate database later connects to the database over a network interface rather than a socket file on the Apache machine. Trace the actual deployment instead of assuming one socket per letter.

Why would an existing product and a missing database have different statuses?

An existing row with zero stock is still a successful lookup. A missing database means the application can't determine whether the row exists, so calling the product unknown would give the caller incorrect information. The exercise distinguishes invalid request, missing row and unavailable dependency, giving the consumer a chance to correct a typo or try again when the store is ready.

Quick quiz

What result should the app return for CURD-2: 200 with 0, 404, or 503?

200 with 0. The initial seed contains that item. Zero is the stored quantity. The application sends a missing product status only for a valid lookup that produced no row, and an unavailable status if the dependency failed.

After the lab's MySQL child is stopped, which check still proves PHP is processing input?

Ask for the deliberately invalid SKU and check for 400 with the expected error body. The PHP validation returns that response before the code opens the database. The static page still proves Apache can serve its file but does not exercise PHP at all.

Which statement should the catalog reader account be able to run, SELECT or UPDATE?

SELECT from the catalog products table. Its public task is presenting a product record. The inventory update in the exercise runs separately through the private SQL administrator, leaving the application's credential without write permission.

Practice to complete before closing the terminal

  1. In the private fixture, set the milk quantity to a different number such as thirteen using the administrative connection. Prove the direct SQL read and HTTP body agree, then confirm the curd stays at zero. This second key gives you a control for the intended update's scope.
  2. Compare the catalog response for a malformed key with a valid unknown key such as CURD-9. Record the status, error message and whether the request needed a database connection. Explain how you can verify the claim by comparing the malformed response with the database unavailable.
  3. Describe the first check you would do if the same URL returned a PHP file as text. Name the Apache configuration and HTTP evidence needed to show that the production fix repaired script execution. Explain which secrets should be stored outside the publicly mapped files regardless of that fix.

Two control URLs

Static proves the HTTP entry point and file mapping. Dynamic checks the worker, application logic and its data store.

Two local socket paths

Apache's FastCGI endpoint reaches PHP-FPM. PHP's database socket reaches MySQL. Each process expects a different protocol.

Check the real stored row

Compare the exact key in the public response with an authorized independent SQL read. Preserve numeric zero as a genuine result.

Separate permissions

Filesystem rules allow the worker to open a socket. Database credentials and grants determine which rows it can query or change.

Official references