Chapter 12: Technology Stacks — LAMP, LEMP, MEAN, MERN
12.5 Installing MongoDB from the official repository
For this Linux exercise, use MongoDB’s signed official package repository. First check your operating system release and processor architecture, then follow the matching instructions on a disposable machine.
या Linux सरावासाठी MongoDB ची अधिकृत signed package repository वापरा. आधी OS release आणि processor architecture तपासा. मग नवीन test machine वर त्यासाठीच्या सूचना वापरा.
इस Linux अभ्यास के लिए MongoDB की आधिकारिक signed package repository इस्तेमाल करें। पहले OS release और processor architecture जाँचें। फिर नई test machine पर उसी platform के निर्देश अपनाएँ।
This lesson uses the MongoDB 8.0 Community series. Verify your distribution, release and architecture before installing. For a different series, follow the version-specific vendor documentation and supported upgrade path. Run one matching set of commands on a fresh, dedicated lab system.
Amazon Linux 2023
Confirm Amazon Linux 2023 and a supported architecture before adding this repo to your dedicated lab instance.
sudo tee /etc/yum.repos.d/mongodb-org-8.0.repo >/dev/null <<'MONGODB_REPO'
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/amazon/2023/mongodb-org/8.0/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-8.0.asc
MONGODB_REPO
dnf info mongodb-org mongodb-org-server
sudo dnf install mongodb-org
sudo systemctl start mongod
systemctl is-active mongodUbuntu 22.04 / 24.04
On a fresh Ubuntu 22.04 or 24.04 lab host, verify the release before writing the source. If the release check reports an unsupported release, use the matching vendor guide instead.
set -eo pipefail
. /etc/os-release
case "${ID:-}:${VERSION_CODENAME:-}" in
ubuntu:jammy|ubuntu:noble) printf 'Ubuntu suite: %s
' "$VERSION_CODENAME" ;;
*) printf 'Use the matching vendor guide for your release.
' >&2; exit 1 ;;
esac
sudo apt-get update
sudo apt-get install gnupg curl
curl -fsSL https://pgp.mongodb.com/server-8.0.asc |
sudo gpg --output /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
printf 'deb [arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg] https://repo.mongodb.org/apt/ubuntu %s/mongodb-org/8.0 multiverse
' "$VERSION_CODENAME" |
sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
sudo apt-get update
apt-cache policy mongodb-org mongodb-org-server
sudo apt-get install mongodb-org
sudo systemctl start mongod
systemctl is-active mongod($VERSION_CODENAME is jammy on 22.04 and noble on 24.04.)
CentOS Stream 9 (RHEL 9 family)
Use this repository only on a supported RHEL 9-family release and architecture listed in the official guide.
sudo tee /etc/yum.repos.d/mongodb-org-8.0.repo >/dev/null <<'MONGODB_REPO'
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/8.0/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-8.0.asc
MONGODB_REPO
dnf info mongodb-org mongodb-org-server
sudo dnf install mongodb-org
sudo systemctl start mongod
systemctl is-active mongodMongoDB and SELinux on CentOS
With SELinux enforcing, mongod may log permission denials (or fail to start) because of its monitoring features. MongoDB publishes an official SELinux policy (the mongodb-selinux project on MongoDB's GitHub) — install it as described in the MongoDB installation docs for RHEL. For a quick lab, check sudo service mongod status and sudo ausearch -m avc -ts recent.
Verify and basic use
systemctl is-active mongod
systemctl is-enabled mongod
sudo ss -ltnp 'sport = :27017'
mongosh --norc --quiet 'mongodb://127.0.0.1:27017/?directConnection=true' --eval 'db.adminCommand({ ping: 1 })'These settings target the packaged IPv4 loopback TCP example. Adjust the test destination if you explicitly configured a different private endpoint. Verify data access separately with the intended application account.
| Item | Value |
|---|---|
| Service | mongod |
| Config file | /etc/mongod.conf (YAML) |
| Data directory | /var/lib/mongo (RPM) or /var/lib/mongodb (Ubuntu) |
| Log | /var/log/mongodb/mongod.log |
| Default bind | 127.0.0.1 port 27017 |
| Shell | mongosh |
// inside mongosh
show dbs
use notesdb
db.notes.insertOne({ text: "Hello MongoDB", createdAt: new Date() })
db.notes.find()
Never expose MongoDB to the internet
For a same-host lab, keep the listener local. A separately hosted application needs a deliberately configured private path. Enable access control, create the first administrator through the documented local procedure for a fresh server, and use a separate least-privilege app account. Keep credentials out of command-line arguments and public configuration.
Ravindra Bagale's Tip
Check the actual MongoDB listener and match it to the intended private client. Ping shows the server responds. Verify permission separately by reading a known document using the application account.
Ravindra Bagale's Tip – मराठी
MongoDB कोणत्या address किंवा socket वर चालतो ते तपासा. Ping ने server उत्तर देतो का ते समजते. App account वापरून ठरावीक document वाचता येतो का ते वेगळे तपासा.
Ravindra Bagale's Tip – हिंदी
MongoDB किस address या socket पर सुन रहा है, यह जाँचें। Ping से पता चलता है कि server जवाब देता है। App account से तय document पढ़कर उसकी अनुमति अलग से जाँचें।
Lab
तुमच्या lab machine वर आधी OS release, architecture आणि official package source तपासा. मग खालील खाजगी instance मध्ये ping, reader account ने note वाचणे, आणि write नाकारला जाणे या तीन गोष्टी वेगळ्या तपासा.
Start by deciding which database process the notes app should reach
Mauli Dairy has a screen for its delivery notes and an API route for fetching one. The store needs a database process to retain those records even when the application restarts. On a new Linux lab instance the first practical question is which package installs the right database server for that particular machine. A second question comes immediately after: how will you prove the process your application reaches is the one you just set up? A terminal printing a version only proves which executable it found. It does not show which process is running or which set of files it opened.
MongoDB Community Server is the database software used here. The mongod program owns the running database and its storage. A service manager can supervise that program on a Linux system. mongosh is the interactive MongoDB Shell, a separate client you can use from a terminal to connect and send commands. A Node application calls a client driver to speak the database protocol from its own code. Installing the shell does not start a database. Starting a database does not automatically connect a running application to its intended environment. The previous architecture lesson puts these three roles in one request path.
Say you deploy the notes app on a fresh EC2 instance. Someone recommends an RPM command from an old CentOS example. Another person says to use APT because that is what they ran locally. Both instructions might be helpful on their own machines. EC2 is a service for launching virtual servers, not the name of the installed Linux distribution. Your selected machine image determines the distribution and release. The instance type and image determine the CPU architecture the packages must run on. An official repository organized for Ubuntu 24.04 on a 64-bit Intel-compatible processor is the wrong source for an Amazon Linux instance of another architecture.
Start with the MongoDB version documentation for the exact platform and release you intend to maintain. The examples here use the 8.0 Community series and the vendor's OS-specific repository instructions. If you want a different major release, use the documentation and platform support table for that major. Replacing the number in a copied URL can select the wrong key, an unavailable repository, or an inappropriate upgrade path. New setup and an in-place upgrade have different prerequisites. A maintained database with real records needs a tested backup and an approved version transition before you change where its packages come from.
| Package question | Example answer | Evidence to keep |
|---|---|---|
| What is the operating system release? | Ubuntu 24.04 LTS, code name Noble | Values read from the target's /etc/os-release |
| Which machine architecture? | x86_64 from the kernel, amd64 for the APT architecture | Kernel and installed package-tool architecture results |
| Which database series and package source? | MongoDB 8.0 Community through the matching official repository | Repository URL, signing key source and candidate package details |
| Which process is actually in use? | Running mongod under the packaged unit or a separately started fixture | Runtime version, exact connection destination and actual data check |
It helps to record these answers in a simple install note before touching the system. On a new test server, state how you will recognize the correct process, where its data lives and how to remove that fresh server cleanly. On a shared system, first identify the database owner and any existing unit or data. A package install may start or replace service files depending on the operating system. Use a new disposable machine for first practice so you can learn the sequence without risking a running store.
Trace repository setup and signing before installing
A package repository publishes program packages and metadata describing what versions and architectures are available. A package manager reads that metadata to find a candidate version and dependencies, downloads files and installs them. The MongoDB Community package family commonly uses mongodb-org as a metapackage, a package which brings in related pieces. The server component contains mongod. The interactive shell and database-tool components can follow their own release schedules. Keep records of both the actual server version and the shell version when reporting a problem. They do not need to contain the same digits.
First identify the machine using these commands. They are read-only. The second command describes the kernel's CPU architecture. APT and RPM tools have their own notation or package architecture settings, so confirm the form expected by your program. The covered Ubuntu repository examples are 22.04 Jammy and 24.04 Noble. The covered RPM examples are Amazon Linux 2023 and supported CentOS Stream 9 or other RHEL 9-family platforms. Check the vendor platform table for your architecture and exact environment.
cat /etc/os-release
uname -m
if command -v dpkg >/dev/null; then dpkg --print-architecture; fi
if command -v rpm >/dev/null; then rpm --eval '%{_arch}'; fi
The configuration for an RPM repository specifies a base URL, whether it is enabled and whether package signature verification is required. For 8.0 on AL2023 the official base path family starts with yum/amazon/2023/mongodb-org/8.0/. A documented RHEL 9-family setup instead uses yum/redhat/9/mongodb-org/8.0/. The $basearch component is evaluated by the package manager. Preserve it literally when writing the repo file. Pasting an unquoted shell string with that content may remove the variable before the package manager sees it. Keep the documented signature check enabled and use the vendor's matching public key. An accepted signature helps establish package integrity and trusted signer according to the package manager's configured key policy.
On Ubuntu the repository line identifies both the release and the package series. For 24.04 the vendor publishes a noble/mongodb-org/8.0 suite and for 22.04 it publishes jammy/mongodb-org/8.0. In this context, a suite is the combination of release and package family in the repository metadata. The signed-by identity limits which apt keyring will be used to authenticate that repository. The MongoDB Ubuntu guide shows installing the key into a dedicated keyring and declaring it in the source line. Check that the key file is accessible to the package manager and that the names in both places match. HTTPS protects the transport, and verification also relies on a trusted public key rather than accepting any downloaded package.
Use only the repository instructions for your verified OS family. On a fresh disposable instance, check for an existing conflicting package first. MongoDB's Ubuntu guide distinguishes its mongodb-org packages from a distro package named mongodb. If an existing installation owns data or service settings, do not treat it as an empty practice machine. Review how that installation was created and how to preserve or migrate its data. After installing the intended repository, check the result from the relevant package manager rather than mixing the examples.
# Ubuntu, after setting up only its documented source and key
sudo apt-get update
apt-cache policy mongodb-org mongodb-org-server
sudo apt-get install mongodb-org
# AL2023 or the covered RHEL 9 family, after configuring its own repo
sudo dnf repolist
dnf info mongodb-org mongodb-org-server
sudo dnf install mongodb-org
apt-get update refreshes repository metadata and does not itself install the database. Its output should include the intended repository and no ignored signing error. apt-cache policy shows candidate versions and origins. The RPM commands show enabled repositories and package details before installing. Look for the expected family and version series. Read the dependency and package changes proposed by the final command. The example omits an automatic yes flag so you can examine that plan. If your distribution's official setup says to use a named equivalent package manager, follow it. AL2023 defaults to DNF and retains a YUM command pointing to DNF.
A missing candidate does not mean you should point at an unrelated distribution. First check the target architecture, release and selected series. Confirm the repository is reachable and the package manager reports no signature errors. APT verifies signed repository release metadata. The RPM example specifies package signature checks at install time. If the package manager is resolving a different configured source, review why. For example, installing a particular patch version of the metapackage alone may still allow a different component package version under the dependency rules. Consult the vendor's specific-version instructions when an application requires a coordinated package set. Also arrange a process for supported security updates. Holding a package indefinitely without a maintenance plan can keep defects in use.
Verify the service, listener and storage as separate facts
On the fresh Linux system, the installed service typically uses the mongod unit and reads /etc/mongod.conf. A unit is a systemd description of how the service runs. A service can be installed but inactive. A successful start and being enabled for future boot are also different. Choose when the fixture should start automatically before changing that boot behavior. Read the vendor instructions for the operating system's init service. For common systemd lab systems, commands like these help you confirm what started and what is listening.
# On your fresh, dedicated Linux system after package installation
mongod --version
mongosh --version
sudo systemctl start mongod
systemctl is-active mongod
systemctl is-enabled mongod
sudo ss -ltnp 'sport = :27017'
mongosh --norc --quiet 'mongodb://127.0.0.1:27017/?directConnection=true' \
--eval 'db.adminCommand({ ping: 1 })'
The command reading the version of mongod reports the program in the shell path. A different installed copy might run under the actual service, so inspect the service definition and, after authenticating where necessary, query the server you connected to for its version. is-active tells you whether systemd considers the unit active now. is-enabled helps determine startup configuration. The socket-listing command checks connections of the configured port. If you chose another port or an explicitly local socket rather than TCP, inspect that target. A packaged localhost example usually uses TCP loopback and port 27017. A result showing a wildcard bind means the process is listening more broadly than that local example, so inspect the configuration and access policy before using it.
A response containing ok: 1 from a MongoDB ping means an endpoint accepted a MongoDB command. It verifies more than a process ID, but ping can succeed without proving access to the application collection. A database may require authentication for data while still responding to ping. Connect to the exact intended endpoint. Record a successful lookup using the intended account, database and collection, along with a controlled negative permission test where appropriate. The next exercise makes that contrast visible using a private instance of the same database engine and fabricated notes.
Lab: prove the application can read one note with its intended account
The next steps use a copy of the vendor server executable you already have. They do not start the Linux system service or reconfigure a host's normal MongoDB instance. Use a regular-user Bash shell, Node.js and npm, and a compatible MongoDB 8.0 server executable. The Node driver is used for repeatable checks of exactly what the application can do. The shell example above remains a useful separate packaged-service check. If you installed software on a disposable Linux box for this lesson, run the role exercise under an ordinary user and give it the time and disk space needed to initialize an entirely new database directory.
The exercise starts with access control already enabled. It binds to a Unix socket inside a private directory and uses no network bind address. The first local connection can create one administrator while the instance has no user or role documents. This rule is called the localhost exception. Once the first user has been created, a normal client needs the right credential and role for data access. We will create a user administrator, a scoped writer for the seed data and a different reader for the application. All names and data are specific to the throwaway instance. Do not run a first-user test against an existing database.
Step 1. Prepare a private daemon, log and client dependency
set -eu
test "$(id -u)" -ne 0
command -v node >/dev/null
command -v npm >/dev/null
mongo_bin=${MONGOD_BIN:-$(command -v mongod || true)}
test -x "$mongo_bin"
umask 077
install_lab=$(mktemp -d /tmp/rb-mongo-install.XXXXXX)
printf 'Private MongoDB check: %s\n' "$install_lab"
mongo_pid=
stop_install_db() {
if [ -n "$mongo_pid" ]; then
kill -TERM "$mongo_pid" 2>/dev/null || true
wait "$mongo_pid" 2>/dev/null || true
mongo_pid=
fi
}
install_cleanup() {
stop_install_db
case "$install_lab" in
/tmp/rb-mongo-install.??????) rm -rf -- "$install_lab" ;;
esac
}
trap install_cleanup EXIT
mkdir "$install_lab/data" "$install_lab/socket"
printf '%s\n' '{"name":"private-mongo-install-check","private":true,"version":"1.0.0"}' \
> "$install_lab/package.json"
npm --prefix "$install_lab" install --ignore-scripts --save-exact mongodb@6.21.0
mongo_socket="$install_lab/socket/dairy.sock"
MONGO_LESSON_URI=$(node -p '"mongodb://" + encodeURIComponent(process.argv[1]) + "/?directConnection=true"' "$mongo_socket")
export MONGO_LESSON_URI
start_install_db() {
"$mongo_bin" --auth --dbpath "$install_lab/data" --bind_ip "$mongo_socket" \
--unixSocketPrefix "$install_lab/socket" --filePermissions 0700 \
--logappend --logpath "$install_lab/mongod.log" &
mongo_pid=$!
for attempt in $(seq 1 40); do
if test -S "$mongo_socket"; then return 0; fi
if ! kill -0 "$mongo_pid" 2>/dev/null; then break; fi
sleep 0.25
done
printf 'Read %s/mongod.log to investigate startup.\n' "$install_lab" >&2
return 1
}
"$mongo_bin" --version
start_install_db
This configuration invokes the database directly and holds its files and sockets under the new workspace. The data directory is initially empty, so the process initializes it. The package command puts the driver into this temporary project's dependencies without changing the installed database or adding Node packages to its system service. The startup loop waits for the specific socket rather than connecting to a default port. The next block checks the protocol with a real ping and watches for a successful bootstrap operation. A socket file by itself can be stale, so the active process and connection checks have separate jobs.
Step 2. Add separate administrator, writer and reader identities
cat > "$install_lab/role-check.cjs" <<'JS'
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const fs = require('node:fs');
const path = require('node:path');
const { MongoClient } = require('mongodb');
const configPath = path.join(__dirname, 'lab-credentials.json');
const database = 'install_lab_dairy';
const knownNote = { _id: 'receiving-1', title: 'First delivery', cartons: 8 };
async function as(identity, authSource, action) {
const auth = identity ? { auth: identity, authSource } : {};
const client = new MongoClient(process.env.MONGO_LESSON_URI, {
...auth,
serverSelectionTimeoutMS: 2000,
});
try {
await client.connect();
return await action(client);
} finally {
await client.close();
}
}
function account(username) {
return { username, password: crypto.randomBytes(24).toString('hex') };
}
async function bootstrap() {
const identities = {
admin: account('labUserAdministrator'),
writer: account('labNotesWriter'),
reader: account('labNotesReader'),
};
await as(null, null, async client => {
const admin = client.db('admin');
const ping = await admin.command({ ping: 1 });
assert.equal(ping.ok, 1);
await admin.command({
createUser: identities.admin.username,
pwd: identities.admin.password,
roles: ['userAdminAnyDatabase'],
});
});
await as(identities.admin, 'admin', async client => {
const target = client.db(database);
await target.command({
createUser: identities.writer.username,
pwd: identities.writer.password,
roles: ['readWrite'],
});
await target.command({
createUser: identities.reader.username,
pwd: identities.reader.password,
roles: ['read'],
});
});
fs.writeFileSync(configPath, JSON.stringify(identities), { mode: 0o600, flag: 'wx' });
await as(identities.writer, database, async client => {
const result = await client.db(database).collection('notes').insertOne(knownNote);
assert.equal(result.acknowledged, true);
assert.equal(result.insertedId, knownNote._id);
});
console.log('Local bootstrap completed and the scoped writer inserted receiving-1.');
}
async function verify() {
const { reader } = JSON.parse(fs.readFileSync(configPath, 'utf8'));
await as(null, null, async client => {
assert.equal((await client.db('admin').command({ ping: 1 })).ok, 1);
await assert.rejects(() => client.db(database).collection('notes').findOne({ _id: knownNote._id }),
error => error.code === 13);
});
await as(reader, database, async client => {
const notes = client.db(database).collection('notes');
assert.deepEqual(await notes.findOne({ _id: knownNote._id }), knownNote);
await assert.rejects(() => notes.updateOne(
{ _id: knownNote._id }, { $set: { cartons: 99 } }),
error => error.code === 13);
await assert.rejects(() => client.db('other_fixture').collection('notes').findOne({}),
error => error.code === 13);
assert.deepEqual(await notes.findOne({ _id: knownNote._id }), knownNote);
});
console.log('Ping succeeds anonymously; anonymous reads and reader writes are denied.');
console.log('The reader sees receiving-1 with 8 cartons in its assigned database.');
}
const action = { bootstrap, verify }[process.argv[2]];
assert.equal(typeof action, 'function');
action().catch(error => {
console.error(error.name, error.code ?? '', error.message);
process.exitCode = 1;
});
JS
node --check "$install_lab/role-check.cjs"
node "$install_lab/role-check.cjs" bootstrap
The initial ping proves the program can reach the exact private server. The next call creates a high-privilege user administrator in the admin authentication database. This account can assign other roles and must be guarded. It is no longer an unauthenticated bootstrap operation when that administrator creates the two service accounts. The account used to write a seed record can write in the sample database. The application reader can perform reads there and is not given generic administration or write access. Real teams can create even more tightly scoped privileges when a role should address one collection only.
The authentication database records where a user's identity is stored. The user administrator lives in the admin database, whereas the writer and reader identities for this example are created in the sample database. When opening a connection the client identifies that location through authSource. A successful connection with an administrative login does not prove that a differently scoped application login is correct. Using the wrong authentication database for a correct username can lead to an authentication failure.
The script generates its throwaway passwords in memory, then saves them to one local file with restrictive permissions for the second process. The credential values are not in the code or command-line arguments. A single disposable learner uses all three for this experiment so future checks can be separate executions. A maintained server would provide each process only its own approved credential and follow the relevant storage and password rotation policy. A private convenience file for this lab is not a credential-distribution design for a deployed app.
Step 3. Check denied access, allowed access and persistence
node "$install_lab/role-check.cjs" verify
stop_install_db
start_install_db
node "$install_lab/role-check.cjs" verify
install_cleanup
trap - EXIT
test ! -e "$install_lab"
printf 'Private MongoDB fixture removed.\n'
Read these results in order. A client with no credentials could send ping but could not read the stored note. The reader account matched the note with eight cartons. A write attempt using that reader within the private exercise was denied, then another authorized read confirmed the value survived unchanged. Reading a collection in another database was also denied. We repeat the checks after stopping and starting the exact same daemon in the same folder. The fixture retains its data and account boundaries after restart. The cleanup removes all its test-only data, credentials and client packages. Installed service files and real databases remain outside this operation.
Work through two machines with different package and connection evidence
Take an Ubuntu 24.04 test server whose kernel output is x86_64 and whose package-tool output is amd64. These names are common descriptions of the same architecture family used in different tools. The source for this example specifies Noble and offers amd64 packages. Suppose the package policy output shows a candidate in the 8.0 series with a source under noble/mongodb-org/8.0. Record that conclusion before installing rather than attempting an RPM command. If the release output instead says jammy, you have an Ubuntu 22.04 system and should use the corresponding official suite. A copied path can exist and serve metadata yet still be wrong for this machine.
On a second server, the operating-system release shows Amazon Linux 2023 and the architecture is aarch64. You must check that both the release and architecture are supported for the selected MongoDB series. On the RPM side, the documented repository is arranged by platform family, release and package architecture. After the package manager expands its architecture variable, the source should be the supported Amazon Linux 2023 directory for aarch64. The presence of a Red Hat repository with an architecture directory of the same name is not enough evidence to use it. OS releases can require different shared libraries and packaging assumptions.
These machines can provide equivalent application behavior with different package commands and filesystem layouts. For both, record that the server responds to a document lookup using the desired client account. The comparison should include the same visible record values and errors. The working API cares that the intended database operation succeeds; it shouldn't infer Linux's package manager from a note body. For an operator the installation provenance still matters when fixing updates, inspecting the correct unit or finding paths. Treat platform evidence and application acceptance as complementary.
Think about where the user records and delivery notes belong. A freshly installed MongoDB instance may not show a notes database until you create data or a collection. Selecting a name in the shell is a choice of where to send future operations. It doesn't prove that data already exists. The role test stores a document with an explicit string identifier in the chosen database. Looking it up by the wrong type, for example an object identifier rather than an exact string, can yield no match even with valid credentials. Verify the note collection, its key representation and the selected database before changing network policy or account permissions.
Suppose an installation calls its data database dairy_notes, and the app's user was created there. Its connection needs the same authentication source as that user. Another deployment could keep account definitions in admin while granting a scoped privilege on dairy_notes. Its client would authenticate against admin and query the data database. Reading an example connection URI is easier when you can describe its two jobs. A connection hostname and port select a server. The authentication settings select an account's location. The application then chooses a database and collection for its work. Write down all three when reproducing a failure.
If an authorized terminal connects to the installed system service, keep passwords out of the typed URI and scripts, and follow the shell's documented password prompt or your team's sanctioned secret handling. In an app no person is sitting at a prompt, so the service needs a private provisioned secret and rotation procedure. During an investigation copy only the relevant non-secret parts of configuration, such as the target database and server identity. Shell history, console transcripts and process listings can retain command arguments. In this lesson the test generates passwords at runtime and passes them to the driver inside the private program.
You can keep first-install proof small and repeatable. On a disposable host, record the selected repository and the package manager's successful resolution. Verify the installed process and chosen listener. Inspect a ping to see that it speaks the expected protocol. Then move to an authorized read and reproducible expected value, using a plain observer that doesn't share the backend's startup logic. Last, record that an unintended operation is rejected. These checks detect different errors. They also give a future teammate enough information to reproduce one stage of a failure without guessing at the others.
Once a second service starts using the database, decide how to distinguish deployment environments. One way in a lab is a harmless note with a distinct key that exists only in the intended practice database. Never add a test record to a production store without the owner's approval and a defined cleanup. A release pipeline can use an isolated fixture, and an authorized production check can use a designated read-only known record. Document whether it uses the same credentials and connection path as the receiving application. If a separate administrator runs the check from a workstation, its success may not cover the network restrictions and roles the API encounters.
Finally, avoid claiming a readiness outcome from the wrong machine. If the public page lives on one EC2 instance and the database on a second, the app's network path and the operator's SSH path are separate. The successful read that helps the app is the one made from its intended network and identity. In the same-host exercise, both the lab worker and the independent probe open the exact private socket path. The package install exercises and the private authorization exercise make these scopes visible on purpose. A portable fixture verifies database behavior without establishing that every distribution's package service has been configured on your behalf.
Read the installed configuration next to the process that uses it
When you configure an installed Linux service, first ask which file the unit tells the daemon to read. A fresh vendor package often points it at /etc/mongod.conf. Changing another copy in your current folder won't affect the running service. Use the systemd unit listing and the service status to locate the actual configuration. Then read the network binding, logging and data path sections together. YAML represents nested options with indentation. Keep the indentation in spaces, avoid repeated sections, and understand which block a setting belongs to before attempting a change.
For example, an administrator can find a note under storage.dbPath pointing to the database files. The daemon must be able to traverse the enclosing directories and write the files it manages. Giving the terminal's login this access does not automatically give it to the unit's database user. Database writes can also fail if the partition is full or mounted read-only. If a log path points into a new directory, the service user needs appropriate access there too. A storage error may produce a service startup failure even though software installation and network settings were correct.
Identify the path via the installed config on the specific distro instead of relying on a hard-coded folder. The official RPM installation and official Ubuntu installation commonly use different data directory names. A portable archive and a system package also use different defaults and process management. Our authenticated fixture specifies its own folder and socket on each launch. The exercise's behavior does not require writing to the ordinary package paths at all. If you start one process manually while the packaged service already runs, do not point both processes at the same data directory. Open the actual test directory and test endpoint you reserved.
Binding tells the daemon which addresses it will listen on. Loopback on a server is reachable by local programs on that same server. For a local app first determine whether a TCP loopback listener or a local socket is intended. Compare the bind decision with the client connection target. An SSH command typed on a laptop uses the laptop's loopback unless the command actually runs on the server or an explicitly configured transport such as a local forward is involved. That is one reason to state where you ran each check. In a container environment, the network namespace can also change what “local” means.
A service with network clients should be restricted to the interfaces and source resources needed by the app, protected by authentication and applicable TLS, following the documented deployment design. The database may remain private while the website is public. Auth is still needed for intended network clients; a firewall is a separate access layer. Even where the app and daemon run on one instance, other processes can belong to different system users. Restricting local bind scope does not assign database roles. The exercise uses both local isolation and database access controls because they solve different parts of the problem.
A configuration change is an operational edit. Save the documented last-known-good settings using your normal backup practice and check how the package's unit applies the config before changing it. In a managed project coordinate maintenance with the people who depend on the database. After activating a new bind rule or authorization policy, verify the intended address, the actual client identity, a useful application read and the expected denial for a caller that lacks access. Simply seeing the service return to active status cannot tell whether those policy changes had their intended effects.
Troubleshoot the stage that actually failed
Say a student reports that MongoDB “doesn't work” on the dairy instance. Ask the student which stage produced the observation. A package manager might say it did not find a suitable candidate. The shell might say mongod was not found. Systemd might know about the service but show a startup failure. The client might connect without authorized access to the note collection. Those results belong to different parts of the install. Give the issue a label drawn from one concrete observation rather than changing repository, port and password all at once.
| Observation | First thing to establish | Why it matters |
|---|---|---|
| No package candidate | Actual OS release, CPU architecture, repository and metadata result | Restarting a service cannot install a package that wasn't resolved |
| Signature verification fails | Configured key path, version, source and verification message | Skipping checks would remove part of the trust decision |
| Installed but fails to start | Service unit command, journal, private file or network binding error | The service manager offers evidence before any application retries |
| Ping succeeds but reads fail | Application identity, authentication database and granted role | Basic connectivity does not grant read access |
| Login success with no expected note | The exact dataset, collection and ID type at the configured endpoint | A legitimate connection can reach a different environment or mismatched key |
For a signing problem, compare the repository's release and series with both the packaged software instructions and the configured key URL or keyring. Check the readable file after acquiring the key by the documented trustworthy route. Avoid making a broken update proceed by disabling signature verification. If a proxy or local configuration rewrites requests, inspect what actually arrives from the intended origin. Report the exact package manager error and the chosen platform. You cannot prove the repository is configured merely by opening a metadata URL in a web browser. The package manager has to authenticate it under its own policy and select from it.
For a running-unit problem on a systemd host, journalctl -u mongod lists logs from the unit when your permissions allow, but the database can additionally write to the log path from its configuration. If you recently edited that file, look for an unavailable option, invalid YAML, a path that can't be opened or a port conflict. On a distribution using SELinux, a valid Unix permission can still be blocked by mandatory policy. Consult the vendor's SELinux guidance and the actual denial. Incorrectly labeling files or disabling enforcement can introduce wider access without resolving the original path selection.
Suppose you can ping, but the API gives a 503 because the driver can't read install_lab_dairy.notes. A failed login can indicate the password didn't match or the client used the wrong authentication database. A successful login followed by an unauthorized operation means the assigned identity is insufficient for that action. Compare that distinction with a successful lookup returning no row. A properly scoped read on a collection without the expected key can be a data or endpoint error instead of a network or auth error. Review the actual application query before creating a wider role to make an error disappear.
To verify a recovery, repeat the same test inputs rather than trying a different query that happens to work. Keep one expected record, one unauthorized action and the exact connection target in the check list. If you were debugging the earlier seed, expect the reader to see receiving-1 with eight cartons. Confirm it cannot change the value and its second read still has eight. A different test using a root-level account might prove a service can run but would miss the boundary the dairy needs for its application.
Decide how to maintain, back up and remove a deliberate install
Before removing a learning installation, make an inventory of what you created. A separate instance may have a machine, an attached volume, a security group and a repository entry on its root disk. The application and database may need different retention. If the test was on a dedicated temporary machine and nobody depends on it, close the practice services and remove the disposable resources through your normal lab cleanup. If a disk or machine holds real data, treat its removal as an administrative change with a backup and owner review. On a shared machine, leaving a repository enabled changes future updates as well. Record which repository and key the exercise added before making removal choices.
Backups need a recovery procedure, not just a label on a copied folder. A running database may have in-progress operations and storage state that require a consistent backup mechanism. Choose tools appropriate to the deployment and verify supported restore compatibility for the selected versions. Practice restoring to a separate endpoint and checking a meaningful read with the correct application identity. Credentials, TLS materials, database configuration and monitoring can have separate recovery procedures. The exercise proves restart persistence from the same directory. It is not a backup test and does not establish the behavior of data kept elsewhere.
Before an upgrade, find both the server's installed package version and the running server's version. Check the support path from your current release and operational state. For a running service check authorization, database health and the app's driver compatibility. If this is the first lesson on a new machine, choosing the supported version is a package install. For a production project, changing major series can also change storage features and compatibility rules. Plan an upgrade as a named operation with a rollback plan. Reversing a repository line by itself cannot mean the data and binary can safely go back to their prior versions.
Collect a compact completion record with these results: the exact distribution and architecture, selected package series and origin, actual server and shell versions, intended endpoint, successful read as the intended app account, expected rejected operation, and where you stored the backup or removed the disposable fixture. A student can use that record to explain more than a command log. It connects the package choice to the process, the process to its storage, and the caller to a permission boundary.
Explain what each check proves
Interview answers
What is the difference between mongod and mongosh?
mongod is the server that owns storage and listens for database connections. mongosh is a client shell that can talk to a server. A Node driver is another kind of client. Installing one client does not start a daemon or prove which server a later command reaches.
Can you point an Ubuntu MongoDB install at a RHEL repository?
The packages, metadata, architecture conventions and expected dependencies differ. Identify the distro release, package architecture and intended server series first, then use the vendor source for those exact inputs. Check the selected candidate after configuring its signing key.
Why use a separate first administrator and application reader?
The administrator creates and manages users. The reader only needs to query its resource. A separate account lets you enforce that limit on the database server and prove it by comparing an allowed read and denied write. It also keeps administrative credentials out of the backend.
Would a successful ping after restart prove the note survived?
No. Ping only confirms that a server can answer a basic command. Reconnect to the same intended endpoint, authenticate with the application account, and assert the exact stored document and its expected value. This checks the reopened database files as well as the network and role.
Check your reasoning
The node process can ping successfully but cannot read the notes collection. What evidence comes next?
Compare the authentication database, identity and effective role for that read. A ping can be completed before data access is authorized. Read the actual error to distinguish login failure from an operation the logged-in identity isn't allowed to perform.
What do you expect the reader to return after the denied update to 99 cartons?
Eight cartons. The authorized reader still retrieves the original fixture value because the database refused that reader's write. A denied operation followed by a value comparison shows what happened to the stored data.
A process is active and shows a wildcard listen address. Does that match the documented local-only service example?
Review why it listens so broadly. The intended local example binds loopback. Check the effective service configuration and access policies rather than assuming a unit status certifies the intended connection scope.
Practice tasks
- On your dedicated Linux exercise machine, write down the distribution, release and architecture. Find the matching MongoDB package and key instructions. Record the exact candidate source and distinguish its package version from the client shell version.
- Compare the anonymous ping and the anonymous read in the isolated role test. Write a short explanation of why both results can occur on the same connection.
- Draft an app-facing acceptance check for another delivery record. Specify the chosen authentication database, data database, collection, key type, expected value and one denied operation. Keep the public application endpoint separate from the privileged maintenance connection.
Pick the repository by platform
Match OS release, architecture and server series. Verify the key and actual candidate.
Version, process and listener
Identify the installed binary, the running service and the exact endpoint. Each tells you a different fact.
Ping is a small check
Use an authenticated read of known data to test application access separately.
Least privilege can be tested
An intended reader sees the note and cannot write it. Repeat the checks after restarting the private server.