Chapter 10: Dynamic Website Hosting (PHP, Python, Node.js with MySQL)
10.2 Installing MySQL / MariaDB
Think of the database like the college office register where every student's record is kept — the web app only asks the office for data; it does not keep the register itself. It's the same at Mauli Dairy – the orders register stays with the database, and the app only asks for it.
डेटाबेसला कॉलेज ऑफिसच्या रजिस्टरसारखं समजा जिथे प्रत्येक स्टुडंटचा रेकॉर्ड ठेवलेला असतो – वेब ॲप फक्त ऑफिसकडे डेटा मागतो; रजिस्टर स्वतः ठेवत नाही. Mauli Dairy मध्ये पण असंच – ऑर्डर्सचं रजिस्टर डेटाबेसकडे, ॲप फक्त विचारतो.
डेटाबेस को कॉलेज ऑफ़िस के रजिस्टर की तरह समझो जहाँ हर स्टूडेंट का रिकॉर्ड रखा होता है – वेब ऐप सिर्फ़ ऑफ़िस से डेटा माँगता है; रजिस्टर ख़ुद नहीं रखता. Mauli Dairy में भी ऐसा ही – ऑर्डर्स का रजिस्टर डेटाबेस के पास, ऐप सिर्फ़ पूछता है.
The app sends SQL to the selected database server through a TCP connection or a Unix socket. The classic TCP protocol often uses port 3306. A local socket uses its configured file path.
MariaDB is derived from MySQL. The sample SQL works on supported versions of both engines. Verify connector, authentication and version-specific feature compatibility for your chosen server.
| OS | Package to inspect | Service to verify | Administrator session |
|---|---|---|---|
| Amazon Linux 2023 | Versioned MariaDB server package selected in DNF. | mariadb | Use the assigned local administrator and package's approved client. |
| Ubuntu Server | mysql-server or mariadb-server. | mysql or mariadb | Default Ubuntu MySQL commonly uses socket authentication. Check the actual installation. |
| CentOS Stream 9 | mariadb-server or the approved available MySQL package. | mariadb or mysqld | Use the selected engine's documented and assigned method. |
Amazon Linux 2023
# Select one approved versioned server package after reviewing the list.
sudo dnf search mariadb
Ubuntu
# Check the package on the assigned Ubuntu guest.
apt-cache policy mysql-server
CentOS Stream 9
# Check the approved MariaDB package on the assigned CentOS Stream guest.
sudo dnf info mariadb-server
Securing the installation
# Discover the security utility for the installed engine.
command -v mariadb-secure-installation
command -v mysql_secure_installation
Read each prompt for your installed engine and the assigned fresh guest. Preserve the approved administrator access and review anonymous users, inappropriate remote admins and unneeded sample objects before changing them. Do not copy fixed password-policy or authentication choices onto a shared installation.
Ubuntu MySQL root login
The default Ubuntu MySQL package commonly authenticates local root through its socket. Keep the administrator separate and verify the actual package and assigned access before changing authentication. Give the app only its own runtime account.
Create the application database and user
Come on, prepare the new appdb.students table on your assigned practice database. The expanded setup below creates the seed rows and a narrow app account with a unique credential.
चला, सरावाच्या database वर नवीन appdb.students table तयार करूया. खाली दिलेल्या setup मध्ये sample rows आणि वेगळ्या credential चा मर्यादित app account तयार होतो.
चलो, अभ्यास के database पर नया appdb.students table बनाओ। नीचे वाले setup में sample rows और अपनी अलग credential वाला सीमित app account बनता है।
-- Run in the approved app session after the expanded setup below.
SELECT CURRENT_USER(), DATABASE();
SELECT id, name, city FROM appdb.students ORDER BY id;
Useful SQL/admin commands:
SELECT CURRENT_USER(), DATABASE();
SHOW GRANTS;
# Check which backup tool your engine supplies before making a scoped restore plan.
command -v mysqldump
command -v mariadb-dump
Keep the database private
For a same-guest app, use the approved loopback listener or Unix socket and keep the database private. For a separate managed or EC2 database, verify the private connection, intended client security scope and server authentication and TLS requirements.
Ravindra Bagale's Tip
Keep the database administrator separate from the application. The sample runtime only needs SELECT and INSERT on its student table. Narrow permissions reduce what that account can change.
Ravindra Bagale's Tip – मराठी
Database administrator आणि application वेगळे ठेवा. या sample app ला students table वर फक्त SELECT आणि INSERT लागतात. मर्यादित permissions मुळे त्या account चे काम मर्यादित राहते.
Ravindra Bagale's Tip – हिंदी
Database administrator और application अलग रखो। इस sample app को students table पर केवल SELECT और INSERT चाहिए। सीमित permissions उस account का काम सीमित रखती हैं।
Lab
Chala, khalcha assigned database lab kara. App account chya exact TCP kiwa socket path ne connect kara. Matched account ani teen sample rows tapaasa. Scratch lab madhe SELECT, INSERT ani rollback vegle nondva.
Database ready? Verify the app account, its approved local or private transport, and the sample rows. Now connect the PHP example using the same intended settings.
Database तयार झाला का? App account, मंजूर local किंवा private connection आणि sample rows तपासा. आता याच settings वापरून PHP जोडा.
Database तैयार है? App account, मंजूर local या private connection और sample rows जाँचो। अब उन्हीं settings से PHP जोड़ो।
Prepare a database that an application can use without administering it
The training application needs to list students and add a synthetic record with a name and city. The application should have permission to read and insert those rows. It should not be able to change the table layout or manage other databases. This distinction is the reason to create a database and an application account separately from installing the database server. The administrator prepares the environment. A running web application performs a smaller set of named operations.
This lesson separates several milestones. The distribution can install a MySQL or MariaDB package. The service can start its own data directory and listen through an appropriate local interface. An administrator can prepare the schema and grant a narrow runtime role. Finally, the application's actual connection can execute a query with its own credentials. Verifying each milestone in order makes it easier to tell whether a later problem belongs to installation, transport, authentication, privileges or schema.
Use a dedicated assigned guest for managed service changes. Keep the service and user identity appropriate to the selected engine. An alternate exercise starts an already available MySQL executable with a new private data directory and local socket. It makes no package or systemd changes. Both routes use synthetic training rows. Neither needs real student information, contact information or a publicly accessible database.
Choose one engine and check what the assigned guest supplies
MySQL and MariaDB share substantial history and both can provide the SQL used in these lessons. They are maintained as separate database products. The same simple table and queries can work on both without implying that all features, authentication plugins, migration steps or clients are interchangeable. For the assigned engine, check the precise version and the supported application connector. Record whether the release uses MySQL or MariaDB rather than assuming the name of its command-line client tells you which server answered.
On a dedicated guest, read the operating system release and check whether a database is already installed or listening. Use the distribution's repository query rather than guessing a release-specific package name. Package installation is a controlled change, so read the transaction before approving it. Avoid installing both engines into the same ordinary guest layout. Their package files, data directories or default sockets can overlap. A different exercise needs intentionally independent service directories or containers to run multiple servers without interference.
cat /etc/os-release
id
command -v mysql
command -v mariadb
sudo ss -ltnp 'sport = :3306'
systemctl is-active mysql
systemctl is-active mariadb
systemctl is-active mysqld
Run the relevant inspections individually. A missing binary or service can be expected before installation. The socket check is about TCP port 3306, which is commonly used for classic SQL connections. A database can still serve authorized local clients through a Unix socket without listening on TCP. Also check what service already owns the data directory if it appears populated. Never initialize a package against an existing database directory merely because a learner expects a fresh installation.
| Guest | Repository check | Usual service to verify |
|---|---|---|
| Amazon Linux 2023 | Use DNF to inspect available versioned MariaDB server packages. AWS's LAMP guide shows mariadb105-server as an example. | mariadb for the expected distribution package. |
| Ubuntu Server | Use APT to inspect mysql-server or mariadb-server; choose the assignment's engine. | mysql or mariadb, according to the package. |
| CentOS Stream 9 | Inspect mariadb-server or the approved MySQL package or stream in the guest's repositories. | Commonly mariadb or mysqld, respectively. |
These are distribution conventions and examples. You may have a customized image, a vendor-provided repository or a release with different available package versions. Compare the actual source and maintenance policy of the chosen package. Do not add arbitrary repositories to make an old command work. Ask the environment owner which engine and version the training application expects. This also matters to clients that support different authentication plugins or default connection encryption.
Install and start the assigned daemon, then verify the connection
On the approved fresh machine, choose the installation for this exercise. For Ubuntu MySQL the documented package is mysql-server. On a CentOS Stream classroom image with MariaDB available, inspect mariadb-server first. On Amazon Linux 2023 the name of a supported MariaDB package can include the engine version. Review your repository's package selection and do not assume the older example is the newest supported route. The course keeps a version-neutral table and uses your approved installed engine for the shared application schema.
# On Ubuntu, for the approved MySQL package:
apt-cache policy mysql-server
sudo apt update
sudo apt install mysql-server
# On CentOS Stream 9, when using its approved MariaDB package:
sudo dnf info mariadb-server
sudo dnf install mariadb-server
# On Amazon Linux 2023, inspect available versioned MariaDB packages:
sudo dnf search mariadb
AL_PACKAGE='REPLACE_WITH_APPROVED_VERSIONED_SERVER_PACKAGE'
sudo dnf info "$AL_PACKAGE"
sudo dnf install "$AL_PACKAGE"
Run the one recipe for the assigned guest. A package can use its own setup scripts to create initial structures or start the unit. Inspect its actual service and start only if the assigned database is inactive. An active unit describes current state and an enabled unit usually describes how it participates in boot. Decide separately whether the database should start automatically. Use the systemd journal and the engine's configured error log when startup fails. A bind conflict, missing data volume or a package initialization error has a different remedy.
# Example for one approved MariaDB service:
systemctl cat mariadb
systemctl is-active mariadb
systemctl is-enabled mariadb
# Start only if the dedicated practice service is currently inactive:
sudo systemctl start mariadb
sudo journalctl -u mariadb --no-pager -n 18
Once the package's approved local administrator access works, query the actual server version and selected session. For standard Ubuntu MySQL, an administrator commonly enters local MySQL using the socket-authenticated root account with sudo mysql -u root. A MariaDB install may provide its own socket-authentication arrangement, often reached through sudo mariadb with the approved account. Modified installations can use other methods. Confirm the lab owner's procedure and verify the destination and session before running administrative SQL. Do not change authentication merely to match another distribution's screenshot.
SELECT VERSION() AS server_version, CURRENT_USER() AS matched_account;
SHOW VARIABLES LIKE 'socket';
SHOW VARIABLES LIKE 'port';
SHOW VARIABLES LIKE 'bind_address';
The first line reports what server executed the query and which account was used for permission checks. The other lines report its configured socket and TCP connection parameters. A variable in the database and the actual listener together give stronger evidence than either alone. On an installation that also has a different network protocol listener, inventory it separately. The beginner application examples use the ordinary SQL connection and do not require adding a public inbound database rule.
Choose the application transport, account and privilege independently
A Unix socket is a local filesystem-addressed connection endpoint. A TCP connection instead uses an address and port. In common Unix MySQL clients, localhost can select a socket by default while an explicit 127.0.0.1 and --protocol=TCP select IPv4 TCP. Connector defaults can differ, so read the actual driver configuration. A socket connection has no TCP port in its destination. A successful administrator session through the local socket is not evidence that the app will be allowed to log in over TCP.
MySQL and MariaDB use account names that can include a user and host portion. The server considers the client connection when choosing which account definition matches. Definitions with the same username and different hosts can carry different authentication and grants. View CURRENT_USER() after connecting through the app's real path. The function identifies the matched server account, while USER() can include what the client supplied. Check the matched role and its grants rather than assuming every name spelled appuser has identical permissions.
For this single-guest application family, the public application and database worker can talk over an approved IPv4 loopback connection. Keep the database listening on that local address if TCP is required, or use the approved Unix socket for a socket-only deployment. In an authorized split deployment use the correct private endpoint, network path, authenticated account and TLS trust for that design. If an AWS security group is involved, constrain the database path to the intended app clients according to the approved architecture. Keep the admin interface and application privileges distinct.
Authentication establishes which account may connect. Authorization determines which operations it can perform. In the shared sample, the web code reads and inserts synthetic students. Give its runtime only SELECT and INSERT on the relevant table. Creating users, changing schema, dumping the whole instance, deleting a database or changing permissions are administration or migration work. A runtime account with less access reduces the scope of unintended operations. It does not solve every mistake or guarantee that a compromised component can affect no other system.
Match the runtime connector to the server's authentication policy
An app can have the correct address and still fail login if its client library cannot negotiate the configured authentication method. MySQL 8.4, for example, disables the older native-password plugin by default. MariaDB has its own supported account plugins and package behaviour. Check the installed connector's supported server versions and plugins before provisioning the runtime account. A current engine and properly supported driver are preferable to changing server-wide authentication to fit a historical snippet. In this chapter the application examples should use separate runtime credentials, regardless of which administrative mechanism is configured.
Make a small direct test before integrating code. Use the same connection parameters the app is meant to use and check its matched account and target schema. A command-line tool can still use a different client library or protocol default, so follow that with an application-level test. If the CLI works and the code fails, compare connector version, selected authentication or encryption settings, and how the running service receives its connection parameters. Do not log the whole connection object or display the secret in an error page to learn which settings were applied.
Record the negotiated plan in terms another operator can verify. The database identity is the approved server and schema, the runtime identity is the user and host account recognized by that server, and the transport is the authorized TCP address or Unix socket. A configuration typo can send the correct user to the wrong instance. A port change can break a connector without altering any stored role. By recording each input independently, you can test a later infrastructure or credential change without granting the app more authority than the exercise needs.
Review the package's initial administrator policy
Initial database settings depend on the chosen package and engine. MySQL and MariaDB provide security utilities whose prompts can differ. The official MariaDB utility is commonly mariadb-secure-installation; mysql_secure_installation is also used in supported setups or as a compatibility name. Review the installed utility and the guest's current state rather than following a sequence of yes and no answers from a different release. Existing socket-authenticated admin accounts can be intentional. Their local OS identity enforcement is a different mechanism from the password that the application will use.
On a newly assigned dedicated host, identify any test database, anonymous accounts or unneeded remote administrative accounts under the owner-approved policy. Confirm the authorized administrator access to keep before altering settings. Never run an initialization or account-removal recipe on a shared installation merely to make a lab match. A prompt can modify a real account or remove an existing data object. Report any difference from the intended fresh state first, then select the least disruptive correction. Password validation policy should follow the host's requirements and the engine's current supported mechanism.
For a network connection also consider encryption and identity verification where the design requires it. Same-host Unix sockets have local access controls, and separately hosted services need their own approved private transport and trusted identity configuration. Verify required settings from the client and server documentation. An administrative ability to connect is necessary for setup, but it is not the application path. Plan how to prove both independently and how to handle credentials without embedding them in sample code or command history.
Create the schema and grant only the operations the sample needs
Use the assigned fresh database service and its authorized admin login. The shared application examples use appdb.students with id, name and city. Confirm that the name appdb and the exact app account are new or explicitly assigned to this exercise. If the names already exist, stop and inspect them. These examples deliberately use new-object creation without IF NOT EXISTS so a collision is visible. Do not reuse a pre-existing database as a private scratch area. When retrying after a partial setup, inspect which objects were already created rather than rerunning the whole seed.
CREATE DATABASE appdb CHARACTER SET utf8mb4;
CREATE TABLE appdb.students (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
city VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB;
INSERT INTO appdb.students (name, city)
VALUES ('Practice Student A', 'Pune'),
('Practice Student B', 'Nagpur'),
('Practice Student C', 'Nashik');
The database name groups related tables. The table defines columns and constraints. The generated primary key distinguishes rows independently of names or cities, which need not be unique. VARCHAR supplies a declared text capacity and utf8mb4 supports Unicode data. The selected transactional engine is InnoDB in the compatible server versions used for the lesson. Application validation is also needed because not all values that can be stored are acceptable for the form. Use realistic but synthetic rows and keep the initial expected count visible.
The following statement is a template. Replace the password placeholder with a strong unique practice secret before executing it through the approved admin workflow. On a current MySQL that supports generating random account passwords, you can use its documented tool and store the generated value appropriately. Use the supported method for the chosen engine. Do not paste a real password into shell command arguments or commit it to a source file. MySQL client histories, administrator logs and secret handling vary, so follow the authorized workflow and the product's advice for credential creation.
CREATE USER 'appuser'@'127.0.0.1'
IDENTIFIED BY 'REPLACE_WITH_UNIQUE_PRACTICE_SECRET';
GRANT SELECT, INSERT ON appdb.students TO 'appuser'@'127.0.0.1';
SHOW GRANTS FOR 'appuser'@'127.0.0.1';
This account is intended for the later lessons' local TCP path. If your approved application uses a Unix socket instead, prepare and verify the account needed for that host match, typically 'appuser'@'localhost'. Create only the account needed for your actual transport. When testing the later language examples, choose the same approved connection that was granted access. Inspect the account selected by the server because resolution and product behaviour can differ. Normal account creation and grant statements update access through their supported interfaces; the exercise need not edit system grant tables directly or run a blanket privilege reload.
Separate one-time schema work from every application startup
A managed service can restart after a deployment, operating-system reboot or a failure. If its code attempts to create users and seed the database every time, starting it can unexpectedly change persistent data. It may also tempt the operator to grant the runtime schema or account permissions. Create the table and initial rows through an approved bootstrap or migration. In the normal request path connect through the small application grant and do only the intended read or insert. This keeps a restart from rewriting the practice registrations.
Suppose the installer ran the table statements and then failed while creating the user. The new schema and sample data may already exist. Many schema definition operations have implicit commit behaviour, so a failing statement does not guarantee the preceding work was undone. Inspect the objects and rows actually present. Continue the missing authorized part once you know the state, and keep the identity and grant checks in the report. Do not put IF NOT EXISTS around everything merely to suppress evidence that names refer to an earlier exercise.
Track the configuration shared by the next lessons. The app should know the intended database and table, which account to connect as and which operations it can perform. If you choose a unique custom database name to avoid a collision, update the app setting consistently instead of editing a separate hardcoded instance in each language sample. Retain the initial markers and object definitions for your personal test. A new test row can be created under the agreed transaction or cleanup plan to avoid polluting the next student's starting state.
Lab one. Confirm the application's session and its narrow privileges
Use your assigned guest, a locally installed client for that engine, the fresh approved schema and the app account with only the documented grants. In the one-host TCP version explicitly choose the loopback transport and the approved port. Do not run the following command from another host and expect its loopback to reach this database. The -p flag without a pasted value asks the client to prompt. Set the actual chosen credentials in the later runtime using its authorized secret configuration.
mysql --protocol=TCP --host=127.0.0.1 --port=3306 \
--user=appuser -p --database=appdb \
--execute="SELECT CURRENT_USER() AS matched_account; SELECT id, name, city FROM students ORDER BY id;"
Use mariadb as the binary where the package provides it as the supported client. The first query reveals the matched account. The next query should show exactly the three synthetic starter rows on the fresh database. If it returns the wrong count, verify the database name and seed state rather than reapplying inserts blindly. Repeating a seed can add duplicate logical rows even when the database generates distinct IDs. Use the same server and account as the application's configuration when drawing a conclusion.
With the same approved app session, begin a transaction and insert one synthetic temporary record. Verify it within the session. Then roll back and check that it is absent. The example verifies permitted insert and read behavior without keeping an extra record. InnoDB supports transactions, and a rolled-back insert does not establish that a generated sequence will reuse that ID. The important evidence is which row is visible and which state remains after the rollback. If you need a negative grant check on a managed service, inspect the application's grants or use the entirely isolated fixture.
START TRANSACTION;
INSERT INTO students (name, city) VALUES ('Temporary Lab Row', 'Pune');
SELECT name, city FROM students WHERE name = 'Temporary Lab Row';
ROLLBACK;
SELECT COUNT(*) AS remaining FROM students WHERE name = 'Temporary Lab Row';
Expect one matching row before rollback and zero after it when the sandbox did not already contain that marker. If the first SQL query cannot connect, check the intended listener and chosen socket or TCP mode. If it connects and denies the query, inspect the matched account and exact grant. If it does not find the table, compare the selected schema and whether the setup completed. These outcomes belong to different milestones. Keep the three seed rows and app account if the next runtime exercises continue with this exact practice database. Remove the temporary connection or standalone exercise artifacts when their scope is complete.
Lab two. Verify a SQL server and grant boundary in a private scratch instance
This optional exercise uses a compatible local MySQL server and matching client, plus Python 3. It intentionally targets MySQL, whose data directory initialization flags differ from MariaDB's. Choose an approved installed executable and client through DBLAB_SERVER and DBLAB_CLIENT if they are outside your path. Set DBLAB_BASE only if your build requires its installation directory. Do not use sudo. The script initializes a new directory under a private temporary parent and disables classic TCP networking. On MySQL 8 or later it also disables X Plugin for this fixture. It makes no service-manager changes.
python3 - <<'PY'
from pathlib import Path
from tempfile import TemporaryDirectory
import os
import re
import secrets
import shutil
import subprocess
import time
server = os.environ.get("DBLAB_SERVER") or shutil.which("mysqld")
client = os.environ.get("DBLAB_CLIENT") or shutil.which("mysql")
if not server or not client or os.getuid() == 0:
raise SystemExit("Use approved MySQL executables as a regular user.")
version = subprocess.run([server, "--no-defaults", "--version"], check=True,
capture_output=True, text=True).stdout
match = re.search(r"\bVer\s+(\d+)\.(\d+)\.", version)
if "mariadb" in version.lower() or not match or tuple(map(int, match.groups())) < (5, 7):
raise SystemExit("This scratch initializer expects MySQL 5.7+ or 8.x.")
with TemporaryDirectory(prefix="sqllab-", dir="/tmp") as area:
p = Path(area).resolve()
data = p / "data"
data.mkdir()
socket_path = p / "db.sock"
environment = dict(os.environ)
environment.pop("MYSQL_PWD", None)
environment["MYSQL_TEST_LOGIN_FILE"] = str(p / "empty-login-file")
base = os.environ.get("DBLAB_BASE")
common = [server, "--no-defaults", f"--datadir={data}", f"--tmpdir={p}"]
if base:
common.append(f"--basedir={base}")
subprocess.run([*common, "--initialize-insecure",
f"--log-error={p / 'initialize.log'}"], check=True,
env=environment, timeout=45)
args = [*common, "--skip-networking", "--skip-log-bin",
f"--socket={socket_path}", f"--pid-file={p / 'server.pid'}",
f"--log-error={p / 'server.log'}"]
if int(match[1]) >= 8:
args.append("--mysqlx=OFF")
root = [client, "--no-defaults", "--protocol=SOCKET", f"--socket={socket_path}",
"--user=root", "--skip-password", "--batch", "--skip-column-names"]
process = subprocess.Popen(args, env=environment)
try:
for _ in range(100):
if process.poll() is not None:
raise RuntimeError("Scratch database exited during startup.")
if socket_path.exists():
ready = subprocess.run(root, input="SELECT 1;\n", text=True,
capture_output=True, env=environment, timeout=3)
if ready.returncode == 0:
break
time.sleep(0.05)
else:
raise RuntimeError("Scratch database was not ready in time.")
def run(command, sql, check=True):
output = subprocess.run(command, input=sql, text=True, capture_output=True,
env=environment, timeout=5)
if check and output.returncode:
raise RuntimeError("A scratch SQL command failed.")
return output
assert run(root, "SELECT @@skip_networking;").stdout.strip() == "1"
password = secrets.token_hex(24) + "!aA1"
run(root, f"""
CREATE DATABASE appdb CHARACTER SET utf8mb4;
CREATE TABLE appdb.students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
city VARCHAR(50) NOT NULL
) ENGINE=InnoDB;
INSERT INTO appdb.students (name, city) VALUES
('Practice Student A', 'Pune'), ('Practice Student B', 'Nagpur'),
('Practice Student C', 'Nashik');
CREATE USER 'appuser'@'localhost' IDENTIFIED BY '{password}';
GRANT SELECT, INSERT ON appdb.students TO 'appuser'@'localhost';
""")
options = p / "practice-client.cnf"
options.write_text(f"[client]\nuser=appuser\npassword={password}\n")
options.chmod(0o600)
app = [client, f"--defaults-file={options}", "--protocol=SOCKET",
f"--socket={socket_path}", "--database=appdb",
"--batch", "--skip-column-names"]
assert run(app, "SELECT CURRENT_USER();").stdout.strip() == "appuser@localhost"
assert run(app, "SELECT COUNT(*) FROM students;").stdout.strip() == "3"
result = run(app, """
START TRANSACTION;
INSERT INTO students (name, city) VALUES ('Temporary Lab Row', 'Pune');
SELECT COUNT(*) FROM students;
ROLLBACK;
SELECT COUNT(*) FROM students;
""").stdout.split()
assert result == ["4", "3"], result
denied = run(app, "DELETE FROM students WHERE id = 0;", check=False)
assert denied.returncode and "ERROR 1142" in denied.stderr, denied.stderr
assert run(app, "SELECT COUNT(*) FROM students;").stdout.strip() == "3"
print("private socket ready; matched appuser@localhost")
print("SELECT and INSERT allowed; rows 3 → 4 in transaction → 3 after rollback")
print("DELETE denied by the narrow grant")
finally:
process.terminate()
try:
process.wait(timeout=12)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
PY
The exercise uses an initially passwordless scratch admin account reachable only through the local socket under a private directory. Do not use that initialization mode to launch an exposed service. All server paths and client options are explicitly scoped, and the separately generated app password is used from a restricted temporary file. No password is printed. Because this lab chooses its private socket rather than TCP, the app account is the socket host form. The managed exercise uses its own verified account and transport. The SQL grant boundary, transaction and read evidence are comparable between the two setups.
Expect three initial rows, a temporary fourth inside the app transaction and three again after rollback. The denied no-match DELETE demonstrates the server checks the operation's privilege even when that predicate would affect no rows. No student data is altered permanently by it. If you cannot bootstrap a particular binary, examine its supported initialization and runtime prerequisites. Do not point it at a real data directory. The script stops only its own child and removes all its scratch files, including its generated credential.
Identify the first database milestone that failed
| What the client reports | First evidence to compare | Question the check answers |
|---|---|---|
| Cannot open the expected local socket. | Unit journal, actual socket location and permissions, client protocol. | Did the client reach the intended database process? |
| TCP connection refused at loopback. | Listening addresses, configured port and whether TCP is enabled. | Are the application and server using the same interface? |
| Access denied during login. | Supplied identity, server's account matching and supported authentication plugin. | Which account is eligible for this connection? |
| Connected but one statement is denied. | Matched account, selected database, grants and the attempted operation. | Does the runtime role allow that action on this object? |
| Expected table or columns are missing. | Current schema, migration state and actual SQL query. | Was the application pointed at the intended stored structure? |
| Query returns unexpected values. | Query filters, seed state, transaction timing and database selected by the runtime. | Did the app read the correct records and interpret them appropriately? |
A novice sometimes reacts to a connection error by granting more SQL permissions. A server cannot evaluate the app account's table privileges until the connection and authentication make progress. Start with an explicit protocol and trusted endpoint. Conversely, creating a broader inbound network rule does not allow a SQL statement denied to a connected account. Read the client's real error alongside the server's active state. Use a single targeted query and the expected app identity to locate the first failing milestone.
Consider a common case: sudo mysql opens a session, but PHP using TCP receives an access-denied error. The first client might use OS socket authentication as root. The second asks for password authentication of the intended runtime account over a different transport. Check the chosen host, protocol, matched account, connector support and configuration. Never hand the app the admin account simply because that session worked. A narrow role requires its own positive and permitted negative tests.
Another case occurs when a TCP client connects to an entirely different server. It reports a valid version that you recognize and can execute a trivial query, but it reads another training schema. Record the actual selected hostname or socket and the server version and use SELECT DATABASE() in the intended session. Clarify whether the prepared fixture or managed service is expected. A correct login in one of them does not establish the state of the other. Separate record identifiers can catch this subtle error.
Choose which clients can reach each database interface
An application can need access to its local database without any Internet-facing database path. A loopback TCP binding accepts connections only from the same network environment. A Unix socket exposes a filesystem path whose permissions and process environment determine local access. A separate database with a private address or managed endpoint requires a route, approved security rules and the intended authentication method. In all cases check the specific transport and avoid treating a default port as a security boundary.
On the managed guest, compare the database's configured socket and bind settings with the operating system's actual listeners. A package might accept both a normal SQL port and a separate interface used by another protocol or management feature. Know which one the application needs. Common MySQL deployments can expose X Protocol separately, and the usual classic port may be changed by administrators. In the scratch fixture X Plugin is disabled explicitly for supported MySQL versions. Do not infer that classic port restrictions account for every plugin or socket a managed system can open.
For a managed endpoint in another private network, identify the route and the narrowly approved source identity. A security group can control traffic from another resource group when the architecture supports that reference. The database must still authorize the corresponding network client role, and where required the driver needs trusted TLS verification. Read the actual connection details and current service documentation. A developer who connects locally over an SSH session does not automatically recreate the same route taken by the application process.
Explain what the private SQL fixture proved
The scratch program uses a real MySQL daemon; its SQL results come from that engine. It can show a successful socket connection, an actual matching host account and a grant refusal. It does not run the systemd unit or inspect the hosted guest's packages. The managed path in this lesson asks for a separate transport check because later runtime examples normally connect through local TCP. If the private fixture passes and the managed client cannot connect, use the comparison to investigate the socket or port without concluding that the app user should be granted more rights.
The local program uses temporary client options and a random password because it needs to start and check the application session without an interactive prompt. This is useful inside a private directory created for the test and removed afterward. A persistent app needs the approved configuration and secret handling for its service account. During debugging keep credentials out of copied terminal output. The relevant observed result is the matched account and the row or statement outcome, not the password that made the login possible.
For a reproducible report, include the tested MySQL version and whether the program used a special installation base. Some builds use their own locations for message or plugin files. Review the actual compatibility rather than mixing a client for one engine with unknown server defaults from another. The numeric privilege error assertion in this exercise verifies the specific SQL command was denied independently of what language the error message uses.
Check that a manually working session matches the application's view
When an application is started by systemd, its working directory, user and configured variables can differ from your terminal. A developer may run a client using defaults that point to the intended socket and successfully query a table. The running app may instead open TCP, use another database or fail to receive its credentials. Write down the inputs to the service without exposing secrets. A targeted startup diagnostic can confirm the configured host, port and schema when those values are appropriate to log, and a successful query can establish which account and row were actually used.
Use SELECT DATABASE() to tell which default schema was selected in the session. Selecting the right default is important when the code uses a table name without a schema prefix. The explicit admin statement SELECT id FROM appdb.students can succeed even when that default is absent. Test the exact query shape the app uses, with the same account and target. If a migration changes a column, compare the real table definition and version expected by the running code. A process can be active and still lack the structure it needs for a particular route.
Keep the runtime environment and storage lifecycle visible during cleanup. Stopping Apache or Node leaves the data service and its stored rows in place. Restoring an application code release cannot restore a database that was modified separately. A short handoff should name the app release and its schema version or supported fields, the active database, the connection boundaries and the expected starting count. These observations make it possible to recreate the test while protecting the data the next lesson will use.
Separate schema bootstrap, data backup and restoring an exercise
Startup produces engine structures. A schema bootstrap adds training tables and test rows. A logical dump is another artifact, usually written as commands or data that can recreate selected definitions and records. Treat those actions separately. If you rerun a seed after a partial failure, it can create extra test rows. If you restore a dump into an existing database without inspecting its statements, it can replace or duplicate data. Prepare a fresh named target for restore practice and verify the intended source and destination separately.
The database documented here will be used by the PHP, Flask and Node chapters. Keep its tables and role if you need them there. When testing backup, use an authorized account and the engine's matching dump utility, not the web runtime account. Depending on flags and objects a dump may need privileges beyond the runtime's SELECT and INSERT, and a restore generally needs schema and write permissions. Check the required scope and use a separate, private output path. A dump can contain data that should never be published through the website.
A useful classroom restore test is to make a separately named disposable schema, restore into it using the approved administrator or restore role, and compare the count, columns and known marker queries. Read the dump's scope first, including whether it declares or selects the original schema. A tool invoked with a “databases” mode can embed a CREATE DATABASE or USE statement that does not belong in a different live target. Successful command exit is only a start. Query the expected restored schema and verify the app's original training data is unchanged.
Test restore requirements before a real data change. An instance backup may preserve storage state under its method, while a scoped logical backup gives a way to review and restore a specific dataset. Use the owner-approved backup and retention policy rather than assuming one method solves every recovery goal. On completion remove only the synthetic restore schema, files and app credentials assigned to the exercise when no later lab needs them. Let a shared managed service and its remaining client access continue. The standalone scratch fixture automatically stops and removes itself.
Write a database handoff without publishing credentials
Record the server type and version, the app's approved transport and database, the identity it is expected to match and a description of where its secret is supplied. Store the secret only through its authorized mechanism. Include a smoke query with a known synthetic marker and the expected grant check. If the connection is private, say which host or socket must be used. That lets the next PHP, Flask or Express exercise distinguish a missing credential from a schema precondition and reuse the exact database intended for the course.
Interview questions with explained answers
Why install only one database engine on the training guest?
The deployment needs one compatible server and connector. The ordinary packages can overlap in files, sockets or data paths. Compare engine versions in separate approved environments if both are needed, and keep their connection settings and persistence independent.
What is the difference between localhost and 127.0.0.1 for a MySQL client?
On common Unix command-line clients, localhost can select a Unix socket by default. The loopback IPv4 address can select TCP. Explicit transport settings and the matching server account make the result reproducible.
Why not use the database administrator from the app?
The app needs only specific operations on its runtime tables. A dedicated role can read and insert the intended rows without controlling schema or other databases. It also lets administrators maintain distinct credentials and verify the actual granted scope.
How do you prove a seed is correct while avoiding duplicate rows?
Verify the actual database and known markers from the app account. Query the existing schema and count before retrying a partial bootstrap. Do not recreate or reseed existing data blindly.
What does a TCP connection failure tell you about table grants?
Very little. The client may not have reached the process or authentication. Inspect the endpoint and listener before changing database privileges, then test the exact statement after connecting as the intended account.
Check your understanding
The app needs to list students and save a new one. Which permissions suffice for this exercise?
Show answer
Grant only SELECT and INSERT on the students table to the intended runtime account. Keep schema and account changes in an approved separate role.
Does a working
sudo mysqlprove the application's TCP password works?Show answer
No. The admin might use local socket identity and has different grants. Test the app's exact transport, credentials and role.
What does the scratch lab expect after inserting in a transaction, then rolling back?
Show answer
The app reads four rows inside that uncommitted transaction and the original three afterwards. The rollback removes the test row.
Which result confirms a narrow role in addition to a successful query?
Show answer
Inspect the effective grants. In a dedicated scratch instance the forbidden DELETE is denied while the authorized SELECT and INSERT continue to work.
Why would a table missing error persist after opening a firewall rule?
Show answer
The client already made it far enough to send the SQL statement. Check the selected schema and bootstrap or migration state.
Independent practice tasks
Record the candidate package, active unit and actual database version of an assigned guest. Compare what each one can prove.
Run the private scratch fixture if the matching MySQL executables are available. Explain the choice to disable TCP and the difference between admin and app transport and privileges.
Write a scoped recovery and cleanup note for one version of the exercise. Include the database and account that belong to it and the queries that establish their intended state.
Revision cards
- Database daemon
- A managed process that uses its own data directory and exposes designated SQL connections.
- Unix socket
- A same-host connection path, addressed by its filesystem entry rather than a TCP port.
- Matched account
- The server uses a user and host definition for authentication and privileges. Inspect it with
CURRENT_USER(). - Runtime grant
- Allow the exact table and operations the application needs, separate from schema administration.
- Seed data
- Known synthetic rows for the first test. Verify before retrying to avoid duplicate logical records.
- Restore verification
- Restore only to an approved destination and check the resulting schema, counts and specific values.
Official sources
- Amazon Linux MariaDB package example
- Amazon Linux DNF package management
- Ubuntu MySQL installation and accounts
- RHEL family MySQL and MariaDB package guidance
- MariaDB systemd service guide
- MariaDB security utility and initial socket authentication
- MySQL data directory initialization
- MySQL client transports
- MySQL account user and host names
- MySQL connection and account matching
- MySQL application account creation
- MySQL privilege names and scope
- MySQL logical dump scope and restore
- MySQL bind and socket settings
- MySQL version-specific native authentication behaviour
- MySQL scoped option files
- MySQL X Plugin options
- VPC traffic control
- Systemd service and startup state checks