Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check 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×
Skip to content
VGSources
Blog

How to Set Up Node.js and MySQL on a Linux VPS

A practical Ubuntu/Debian VPS guide to installing Node.js and MySQL, creating a secure application account, configuring localhost-only database access, and troubleshooting the service path.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

On an Ubuntu or Debian VPS, install Node.js with the official nvm workflow, install MySQL from the distribution packages, create a separate least-privilege database account, and keep MySQL bound to localhost unless a tightly restricted remote connection is genuinely required. The result is a maintainable Node.js server with a private database and service checks you can repeat after upgrades or reboots.

What you need before starting

This procedure assumes an Ubuntu or Debian-family Linux VPS with a public IP, SSH access, and a user allowed to run sudo. You should know which TCP ports your application will serve and have a way to keep an administrative SSH session open while changing firewall rules.

As an Amazon Associate I earn from qualifying purchases.

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.
  • An Ubuntu or Debian VPS with current security updates and enough disk space for your application, dependencies, logs, and database.
  • An SSH client and the server’s login name, address, and key or password.
  • sudo permission. You do not need to run the Node.js application as Linux root.
  • A domain name is optional for this installation. It is not required to test Node.js or MySQL locally.

The commands below use an account with sudo. Replace example names such as gameapp, appdb, and Strong-unique-password with your own values. Do not put a real password in shell history, source control, or a public issue.

1. Connect over SSH and update the VPS

Open an SSH session and confirm that you are on the intended machine before installing packages.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
ssh your-user@your-server-ip
hostname
whoami

Keep this session available. If you later change firewall rules and accidentally block new connections, the existing administrative session can be used to correct them.

sudo apt update
sudo apt upgrade -y

Reboot only if the package manager or your operating-system policy indicates that a reboot is required. If you do reboot, reconnect and verify the host again before proceeding.

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

2. Choose how Node.js will be installed

Node.js publishes separate Current and Long-Term Support (LTS) release channels. The LTS channel is generally the safer choice for a production VPS because it prioritizes a longer maintenance window; Current receives newer features sooner and changes more frequently. Release labels and numbers move over time. In the release page snapshot used for this guide, Node.js v24.21.0 was labeled LTS and v26.8.2 was labeled Current, so check the official release page when you install rather than copying those numbers indefinitely.

Method Version control Reproducibility Best fit Trade-offs
nvm from the official Node.js download instructions Install and switch exact release lines per user High for a named user; the selected version can be recorded in project documentation Applications operated from a user account, development, and deployments that need controlled upgrades Each user has a separate Node installation; service managers must load the user’s environment correctly
Distribution package Controlled by the Ubuntu or Debian repositories Depends on the distribution release and repository update cadence Hosts where a vendor-maintained system package is preferred May lag upstream Node.js releases; switching between release lines is less convenient
System-wide binary or third-party repository Depends on the selected vendor’s packaging policy Can be reproducible when versions are pinned, but upgrades require stricter change control Centralized service accounts managed by an operations team More system-wide impact when changing Node.js; confirm compatibility with the VPS distribution

For a single application on a VPS, nvm is a practical default because it lets you select an LTS line without replacing the operating system’s packages. If your service manager runs under a dedicated account, install and configure Node for that same account rather than installing it only for your personal SSH user.

3. Install Node.js with nvm

Install nvm for the account that will run the app

Use the current install command shown on the official Node.js download page for Linux. The command is a shell installer, so inspect the page and use its current version rather than preserving an old installer URL in a script. After installation, load the shell configuration in the current session:

source ~/.nvm/nvm.sh

If the command cannot be found after opening a new shell, load the profile file that the installer updated, for example:

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

Install the release line you selected. Using an LTS alias avoids hard-coding a patch number while still keeping you on the supported LTS channel:

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
nvm install --lts
nvm alias default lts/*

Alternatively, install a specific major line when your application requires it:

nvm install 24
nvm alias default 24

The exact major number should match the release you have chosen at installation time. Verify both executables:

node -v
npm -v
which node
which npm

which node should point into the intended user’s .nvm directory when you chose the per-user method. If it points to a different system binary, your login shell and service account are using different environments.

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

Make the version explicit for deployments

Record the selected Node.js major line in your deployment notes and, where appropriate, an .nvmrc file in the project:

echo "24" > .nvmrc
nvm install
nvm use

Replace 24 with the line you selected. This does not freeze every patch release; it tells nvm which major line the project expects. Test a newer line in a separate deployment before changing the production default.

4. Install MySQL from the VPS distribution

Ubuntu documents installation through its native package repositories. Native packages integrate with the distribution’s service manager and security updates, although they can lag the newest upstream MySQL release. MySQL also documents an Oracle APT repository, vendor packages, binaries, source builds, and containers as separate installation routes. Choose one source deliberately instead of mixing packages from several sources.

Source Release freshness Support and integration Upgrade considerations
Ubuntu or Debian native repository May lag upstream Strong integration with the VPS distribution’s package manager and service tooling Follow the distribution’s tested upgrade path
MySQL APT repository Offers a choice of MySQL release series Vendor packaging with its own repository configuration Review repository transitions and compatibility before changing series
Packages, binaries, source, or containers Varies by artifact and selected version More control, but more operational responsibility Document the installation and service lifecycle; do not assume distribution commands apply unchanged

For a standard Ubuntu VPS, install the distribution package:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
sudo apt install mysql-server

On a systemd-based installation, confirm that the service is running and configured to start automatically:

sudo service mysql status
sudo systemctl status mysql

The two status commands expose the same operational question through commonly available interfaces. Use the one that matches your normal administration practice. A healthy status should show an active MySQL service rather than a failed unit.

5. Create an application database and least-privilege account

Do not configure the Node.js application with the MySQL root account. Ubuntu explains that the default root account is local and may authenticate through auth_socket, which is intended for local administration rather than an application connection. Create a database and a dedicated account instead.

Open the local MySQL administrative client:

sudo mysql

Run SQL similar to the following. Use a long, unique password generated for this application and restrict the account host to localhost when Node.js and MySQL share the VPS:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
CREATE DATABASE appdb CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
CREATE USER 'gameapp'@'localhost' IDENTIFIED BY 'Strong-unique-password';
GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'gameapp'@'localhost';
EXIT;

The exact collation available can vary with the MySQL version. If your server rejects the example collation, create the database with the server’s default supported utf8mb4 collation and continue. Grant only the operations the application needs. A migration process that must create or alter tables should use a separate, short-lived administrative path rather than giving the web process permanent schema-alteration privileges.

Test the account locally before involving Node.js:

mysql -u gameapp -p -h 127.0.0.1 appdb

Enter the application password when prompted, then run a harmless query:

SELECT CURRENT_USER(), DATABASE();
EXIT;

If the login fails, check the account name, host part, password, and database name. 'gameapp'@'localhost' and 'gameapp'@'127.0.0.1' are distinct MySQL account definitions in some connection paths, so match the host to the way your application connects.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

6. Keep MySQL private by default

When Node.js and MySQL run on the same VPS, the application can connect through the loopback interface. There is no reason to expose the database port to the public internet. MySQL configuration files live under /etc/mysql; the exact included file depends on the distribution package.

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.

Find the active bind-address setting:

sudo grep -R "^[[:space:]]*bind-address" /etc/mysql

For a single-server deployment, set the MySQL server’s bind address to 127.0.0.1 in the applicable configuration file, preserving the existing configuration format. Then restart the service:

sudo systemctl restart mysql.service
sudo systemctl status mysql

Changing the bind address is only needed when a legitimate remote client must connect. If you make that exception, bind MySQL to the required private interface, restrict source addresses with the VPS firewall and any upstream firewall, use encrypted connections, and avoid allowing the entire internet to reach TCP port 3306. A public database listener is an exposure decision, not a convenience setting.

7. Configure UFW without locking yourself out

Ubuntu identifies Uncomplicated Firewall (UFW) as its default firewall configuration tool. Netfilter enforces the resulting traffic rules. Add an SSH allowance before enabling or tightening the firewall, and use the exact SSH port if your server does not use the default.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose

Open only the web ports your application actually needs. Do not run sudo ufw allow 3306/tcp for a local Node.js/MySQL setup. If remote database access is unavoidable, replace the broad rule with a source-restricted rule for the specific administrator or application network and verify it from an allowed address before closing your existing SSH session.

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

8. Connect the Node.js application to MySQL

Install a MySQL client library in the project

From the application directory, initialize a package manifest if one does not exist and install a maintained MySQL client library. The example below uses the Promise-based mysql2 package:

mkdir -p ~/gameapp
cd ~/gameapp
npm init -y
npm install mysql2

Keep credentials outside the repository. For a simple shell-managed deployment, create a protected environment file owned by the application user:

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
 umask 077
cat > .env <<'EOF'
DB_HOST=127.0.0.1
DB_PORT=3306
DB_NAME=appdb
DB_USER=gameapp
DB_PASSWORD=replace-with-your-secret
EOF

Do not commit this file. In a production service, inject the same variables through the service manager or a secrets system instead of storing them beside the application.

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

Run a minimal connection check

The following script demonstrates the connection path and closes the pool after a query. It expects the environment variables to be present; it does not print the password.

const mysql = require('mysql2/promise');

async function main() {
  const pool = mysql.createPool({
    host: process.env.DB_HOST || '127.0.0.1',
    port: Number(process.env.DB_PORT || 3306),
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    waitForConnections: true,
    connectionLimit: 5
  });

  try {
    const [rows] = await pool.query('SELECT CURRENT_USER() AS user, DATABASE() AS db');
    console.log(rows[0]);
  } finally {
    await pool.end();
  }
}

main().catch(error => {
  console.error(error.message);
  process.exitCode = 1;
});

Save it as check-db.js and run it with the environment loaded. A shell-only example is:

set -a
. ./.env
set +a
node check-db.js

The expected result is a row showing the application account and appdb. The command proves that DNS, the local listener, credentials, and database selection work together; it is not a substitute for testing the application’s real queries.

9. Verify permissions and the complete application path

Installation status alone does not prove that the application can perform its intended work. Check the path in this order:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Run node -v and npm -v as the same Linux user that will run the application.
  2. Confirm that sudo systemctl status mysql reports an active service.
  3. Run the minimal Node.js connection check with environment-managed credentials.
  4. From the application, execute a normal read and a permitted write against a test record or test table.
  5. Attempt an operation that should be denied, such as accessing a different database, and confirm that the account does not have broader privileges than intended.
  6. Restart the VPS during a maintenance window and repeat the service and application checks after reconnecting.

The cited installation documentation establishes package and service commands; it does not guarantee a successful application test on your particular VPS. Treat the final connection and permission checks as your own deployment validation.

10. Troubleshoot common failures

Symptom Likely cause Checks and corrective action
node: command not found The shell has not loaded nvm, or Node.js was installed for another user. Run source ~/.nvm/nvm.sh, check which node, and install Node.js under the account that runs the application. A service account will not automatically inherit your interactive shell.
Node reports an unexpected version A system binary appears before the selected nvm binary in PATH. Run which node, load the intended profile, select the project version with nvm use, and make the service environment explicit.
MySQL unit is inactive or failed Package installation did not complete, configuration is invalid, or the service stopped during startup. Run sudo systemctl status mysql, inspect recent service messages with sudo journalctl -u mysql, correct the reported configuration or package error, then run sudo systemctl restart mysql.
ECONNREFUSED 127.0.0.1:3306 MySQL is stopped, listening on another address or port, or restarting after a configuration change. Check the service status, inspect bind-address under /etc/mysql, and review journalctl -u mysql. Do not respond by opening port 3306 publicly.
Access denied for user The password, account host, or database name does not match. Log in locally as an administrator, inspect the intended account definition, and ensure the application’s host value matches the account’s host part. Re-enter the secret without exposing it in a command line.
Remote administration cannot connect MySQL is intentionally bound to localhost or a firewall rule blocks the source. Decide whether remote access is truly required. If it is, use a private interface, source-restricted firewall rules, encryption, and a dedicated account; never make the listener universally reachable as a first fix.
SSH stops accepting new connections after firewall changes UFW was enabled before an SSH rule was added, or the wrong SSH port was allowed. Use the still-open administrative session to add the correct SSH rule, check sudo ufw status verbose, and only then close the session.

11. Maintain the installation safely

Node.js updates

Check the current Node.js release channels before upgrading. Install a new LTS or Current line alongside the existing one with nvm, run the application’s tests, and switch the project or service only after compatibility is confirmed. Keeping the previous line available makes rollback simpler than replacing it in place.

MySQL updates

Use the same package source you selected during installation and review distribution or repository upgrade notes before changing major release series. After updates, check:

sudo systemctl status mysql
node -v
npm -v

Then run the application connection and permission checks again. A package update can leave the service running while exposing an incompatibility in an ORM, driver, schema, or authentication setting, so validate the application path rather than relying solely on a green service status.

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

Credentials and network exposure

  • Rotate the application password through a planned change rather than editing source code in place.
  • Keep the database account limited to the required schema and operations.
  • Keep MySQL on localhost for a same-VPS application.
  • Review UFW rules after adding any new service and remove rules that are no longer needed.
  • Retain an administrative access method before making changes to SSH, firewall, or MySQL binding.

Recommended final state

A correctly configured single-VPS deployment has Node.js installed for the actual application user through a deliberate release channel, MySQL installed and active under systemd, a dedicated database and account with only required privileges, MySQL listening on localhost, UFW allowing SSH and only the web ports in use, and a repeatable Node.js connection check that uses environment-managed credentials. That arrangement keeps the routine application path simple while making the high-risk decisions—version changes, database privileges, and network exposure—explicit and reversible.

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.

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.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.