Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
FREEDOM251

Freedom251 › Blog › DevOps

How to Monitor MongoDB With Grafana and Prometheus on Ubuntu

By Freedom251 Team · · 10 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The dependable Ubuntu architecture is MongoDB → Percona mongodb_exporter on port 9216 → Prometheus → Grafana. Create a separate MongoDB monitoring user, run the exporter as a non-root systemd service, let Prometheus scrape its /metrics endpoint, and point Grafana at Prometheus. The result is time-series visibility into exporter reachability, connections, replication health and WiredTiger cache pressure without giving the monitoring process administrative credentials.

What the monitoring stack does

MongoDB does not expose Prometheus-format time series directly. The exporter connects to MongoDB, reads the statistics permitted to its monitoring account, and translates them into metrics. Prometheus periodically requests those metrics from the exporter. Grafana queries Prometheus and turns the stored series into dashboards, variables and alerts.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Component Role Typical location in this setup
MongoDB Database being observed Local Ubuntu host or a reachable MongoDB server
mongodb_exporter Collects MongoDB statistics and serves Prometheus metrics Ubuntu host, listening on TCP 9216
Prometheus Scrapes and stores time-series data Same host or a separate monitoring host
Grafana Queries Prometheus and displays dashboards and alerts Same host or a separate monitoring host

Keep the exporter endpoint private. It is an operational endpoint, not a public web service; allow only the Prometheus server to reach port 9216.

Prerequisites and choices

  • An Ubuntu server with a working mongod service and permission to create a MongoDB user.
  • Prometheus and Grafana installed from their current official releases. Package versions change, so do not copy an old version number from an older Ubuntu tutorial.
  • Network access from Prometheus to the exporter on TCP 9216.
  • A plan for storing the MongoDB URI and password outside process arguments and shell history.
  • Administrative access to create a systemd unit, install a binary under /usr/local/bin, edit Prometheus configuration and add a Grafana data source.

For the exporter, a native binary supervised by systemd is the clearest Ubuntu default. A container is possible, but it adds container networking, secret handling and lifecycle decisions. Community guides have pinned different Percona exporter releases, including 0.40.0 and 0.42.0; treat those numbers as historical examples and verify the current Percona release before downloading.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Create a least-privilege MongoDB monitoring user

Do not reuse a full administrator account. The commonly documented role combination is clusterMonitor on the admin database plus read on the local database. This lets the exporter inspect server and replication information without granting application-write privileges.

  1. Open the MongoDB shell as an account allowed to create users.
  2. Switch to the admin database.
  3. Create a dedicated account with a long, unique password and the two roles shown below.
mongosh
use admin
db.createUser({
  user: 'mongodb_exporter',
  pwd: passwordPrompt(),
  roles: [
    { role: 'clusterMonitor', db: 'admin' },
    { role: 'read', db: 'local' }
  ]
})

passwordPrompt() keeps the password out of the command text. If your shell version does not provide it, enter the password through your approved secret-management procedure rather than placing it in a shell command copied into history.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use authSource=admin in the exporter URI because the account is defined in admin. For a local, authenticated MongoDB instance, the URI in the environment file can follow this pattern:

MONGODB_URI=mongodb://mongodb_exporter:${MONGODB_EXPORTER_PASSWORD}@127.0.0.1:27017/?authSource=admin

The shell variable is expanded by the service environment, not committed as a literal password. For a replica set or a remote deployment, use the appropriate members, TLS options and replica-set parameters required by that deployment; do not silently disable certificate verification to make a connection succeed.

Install the Percona exporter binary

Choose and verify the release

Download the Linux architecture tarball from Percona’s mongodb_exporter releases, then inspect the release notes and checksum for the version you selected. Current release numbers are volatile, and setup guides have disagreed, so pin a version deliberately instead of assuming that 0.40.0 or 0.42.0 is current.

Place the executable

After extracting the archive, copy the exporter executable to a root-owned path and make it executable. The exact archive filename depends on the release and CPU architecture; the installation operation itself is stable:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo install -m 0755 mongodb_exporter /usr/local/bin/mongodb_exporter
/usr/local/bin/mongodb_exporter --help

Use the help output to confirm the URI flag names for the downloaded release. The guides used a MongoDB connection URI together with --collect-all and --compatible-mode. If a newer release changes a flag, follow that binary’s help output rather than forcing an obsolete command line.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Run a foreground smoke test

Before creating a service, start the exporter interactively with the URI and collection flags. Keep the terminal open while testing:

export MONGODB_URI='mongodb://mongodb_exporter:${MONGODB_EXPORTER_PASSWORD}@127.0.0.1:27017/?authSource=admin'
/usr/local/bin/mongodb_exporter --mongodb.uri=$MONGODB_URI --collect-all --compatible-mode

In another terminal, query the local metrics endpoint:

curl http://localhost:9216/metrics | grep mongodb_up

A line containing mongodb_up confirms that the exporter reached MongoDB and published its health metric. An empty response, connection refusal or an authentication error must be fixed before involving Prometheus or Grafana.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run the exporter safely with systemd

Store the URI in an environment file

Keeping the URI in an environment file prevents the password from appearing in the process list and in the unit’s command line. Create a root-readable file:

sudo install -m 0600 /dev/null /etc/default/mongodb_exporter
sudoedit /etc/default/mongodb_exporter

Put the URI there, with the password supplied according to your secret policy:

MONGODB_URI=mongodb://mongodb_exporter:${MONGODB_EXPORTER_PASSWORD}@127.0.0.1:27017/?authSource=admin

If you use a separate password variable, ensure the service manager actually receives it; an unexpanded variable produces an authentication failure. Restrict ownership and permissions so ordinary users cannot read the credentials.

Create the unit

The unit should start after MongoDB, run as a dedicated account and restart after an unexpected exit. One documented Ubuntu example uses the existing mongodb service account rather than root; use a different unprivileged account if that better matches your host’s policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
[Unit]
Description=MongoDB Prometheus exporter
After=mongod.service
Wants=mongod.service

[Service]
Type=simple
User=mongodb
Group=mongodb
EnvironmentFile=/etc/default/mongodb_exporter
ExecStart=/usr/local/bin/mongodb_exporter --mongodb.uri=${MONGODB_URI} --collect-all --compatible-mode
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Save it as /etc/systemd/system/mongodb_exporter.service. Confirm that the User can execute the binary and read the environment file. If your system uses a different MongoDB service name, adjust the After and Wants lines to match it.

Enable and start it

sudo systemctl daemon-reload
sudo systemctl enable mongodb_exporter
sudo systemctl start mongodb_exporter
sudo systemctl status mongodb_exporter
sudo journalctl -u mongodb_exporter -n 50 --no-pager

Then repeat the local check:

curl http://localhost:9216/metrics | grep mongodb_up

Do not proceed until the service remains active and the metric appears consistently. A service that continually restarts usually indicates a malformed URI, missing environment variable, unsupported flag or permission problem; the journal normally identifies which one.

Add the exporter to Prometheus

Edit the Prometheus configuration and add a scrape job. The documented example uses a 30-second interval and a 10-second timeout:

scrape_configs:
  - job_name: mongodb
    scrape_interval: 30s
    scrape_timeout: 10s
    static_configs:
      - targets:
          - localhost:9216

Use localhost:9216 only when Prometheus runs on the same machine. If Prometheus is elsewhere, replace it with the exporter host’s private address and firewall that address narrowly. Ensure the target is not exposed to the public internet.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

After saving the file, restart or reload Prometheus according to your installation:

sudo systemctl restart prometheus
sudo systemctl status prometheus

In Prometheus, open the targets page and check that the mongodb target is UP. Query mongodb_up; a value of 1 indicates that the exporter currently reaches MongoDB, while 0 indicates that the exporter is running but its database connection is unhealthy. A down target means Prometheus cannot reach the exporter at all.

Connect Grafana to Prometheus

  1. Sign in to Grafana.
  2. Open Configuration → Data sources.
  3. Select Add data source, then choose Prometheus.
  4. Enter the Prometheus server URL. Use the internal URL reachable from the Grafana server, not necessarily the browser’s localhost.
  5. Select Save & test and confirm the connection succeeds.

Once the data source works, you have two dashboard approaches.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Import a community MongoDB dashboard

Import a dashboard from Grafana’s dashboard catalog or a trusted internal export, then select the Prometheus data source you just configured. Dashboard IDs and panel expressions change over time, so verify that an imported dashboard matches your exporter release and inspect its queries before relying on it for alerting.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build panels yourself

A hand-built dashboard avoids hidden assumptions and makes it easier to adapt labels. Start with panels for:

Panel Purpose What to verify
Exporter reachability Shows mongodb_up Value is 1 for the intended instance
Scrape health Shows whether Prometheus is collecting the job The target remains up and scrape errors stay at zero
Connections Tracks connection use and saturation Compare current use with the configured connection ceiling
Replication Tracks replica lag and member health Alert before lag threatens application read or failover assumptions
WiredTiger cache Tracks cache fill percentage and pressure Investigate sustained high fill, not a single spike

Metric names and label sets can vary with exporter versions and collection flags. Use Grafana’s query editor or Prometheus’s expression browser to discover the exact series emitted by your binary instead of copying an expression that targets a different release.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Alert on the failures that matter

Exporter or database unreachable

Alert when mongodb_up is 0 for a sustained period, and separately alert when the Prometheus target is down. The distinction matters: a target-down alert points to the exporter, network or process; a zero health metric points to the exporter process being reachable but unable to use MongoDB.

Connection saturation

Watch connection usage against the server’s limit. A rising ratio can precede rejected clients even when query latency still looks normal. Set a warning threshold that leaves room for administrative and failover traffic, then tune it to your workload rather than copying a universal percentage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Replication lag

Alert on sustained lag for members that serve reads or participate in failover. Short spikes may be recoverable; a continuously increasing value requires investigation of disk latency, write volume, network conditions or an unhealthy member.

WiredTiger cache pressure

Track the cache fill percentage and alert on sustained high pressure. Correlate it with latency and eviction behavior before changing cache settings. A single high reading is not proof that the cache configuration is wrong.

Secure the endpoint and credentials

  • Allow TCP 9216 only from the Prometheus host or a private monitoring network.
  • Do not bind the exporter to a public interface unless a controlled, authenticated reverse proxy is intentionally part of the design.
  • Keep the MongoDB URI out of shell history, process arguments, public unit files and source control.
  • Use TLS parameters when MongoDB requires encrypted connections, and keep certificate validation enabled.
  • Review the monitoring user’s roles periodically and rotate its password using the same procedure used for other service credentials.
  • Run the exporter as an unprivileged account and keep the executable root-owned and non-writable by that account.

The exporter port is not a replacement for MongoDB authentication. It exposes collected operational data, so network restriction remains necessary even when the database itself is locked down.

Docker as an alternative

One Ubuntu walkthrough reports running the percona/mongodb_exporter image with the same collection flags. Treat this as an optional route rather than the baseline: image tags can lag or change, and you must solve container-to-MongoDB networking, secret injection, restart policy and port binding yourself. If you choose it, keep the container’s 9216 port reachable only by Prometheus, pass the URI through a secret mechanism, and verify /metrics and mongodb_up before adding the scrape job. Do not use an old, unmaintained exporter image merely because its tag appears in an older guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot in the correct order

curl cannot connect to port 9216

  • Check systemctl status mongodb_exporter and the unit journal.
  • Confirm the exporter is listening with your host’s socket inspection tool.
  • Check for a typo in ExecStart, an unreadable environment file or a binary built for the wrong architecture.
  • Verify that a local firewall is not blocking loopback or the chosen bind address.

mongodb_up is missing or equals 0

  • Test the same URI from the foreground exporter command.
  • Confirm the user exists in admin and has both documented roles.
  • Check that authSource=admin is present when the account is stored there.
  • Validate the password, TLS requirements, hostname resolution and MongoDB bind address.
  • Run the exporter with the release’s supported flags; an invalid collection flag can prevent startup or collection.

Prometheus target is down

  • From the Prometheus host, request http://exporter-host:9216/metrics.
  • Replace localhost in the scrape target when Prometheus is on another machine.
  • Open only the required firewall path from Prometheus to port 9216.
  • Check Prometheus logs after changing YAML and restart it if the configuration was not hot-reloaded.

Grafana connects but panels are empty

  • Test the Prometheus data source in Grafana.
  • Run a simple mongodb_up query in Prometheus first.
  • Check the dashboard’s selected data source, time range and instance/job variables.
  • Inspect panel queries for metric names or labels that do not exist in your exporter release.

The service works manually but not under systemd

Compare the interactive environment with the unit environment. Systemd does not inherit your shell’s exported variables, home directory or credentials. Confirm the environment file path, permissions, user ownership and exact executable path, then reload the unit after edits.

Operate and update the stack

Keep MongoDB, the exporter, Prometheus and Grafana on a planned maintenance schedule. Before upgrading the exporter, read its release notes, save the current unit and environment files, test the new binary in the foreground, and compare the emitted metric names with the dashboard queries. A version change that preserves the process name can still rename or remove series.

After an upgrade, repeat the complete health chain: exporter service active, local mongodb_up present, Prometheus target up, Prometheus query returning data and Grafana panels populated. Review alert rules after every exporter change, especially rules tied to replication and WiredTiger metrics.

Recommended implementation sequence

  1. Create the dedicated MongoDB user with clusterMonitor on admin and read on local.
  2. Install and verify a current Percona exporter release.
  3. Run a foreground smoke test and confirm mongodb_up.
  4. Move the URI into a protected environment file and create the non-root systemd unit.
  5. Restrict port 9216 to Prometheus.
  6. Add the Prometheus scrape job with the 30-second interval and 10-second timeout, then verify the target.
  7. Add Prometheus as Grafana’s data source.
  8. Import a compatible dashboard or build panels for reachability, connections, replication lag and WiredTiger cache pressure.
  9. Create alerts only after you have observed normal ranges for this deployment.

This order isolates failures. If the exporter cannot produce mongodb_up, changing Grafana dashboards cannot fix the underlying connection or permission problem; if Prometheus cannot scrape, Grafana has no data to display.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

DevOpsGrafanaMongoDBmongodb_exporterobservabilityPrometheusUbuntu

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.