Working connection code and settings for MongoDB, MySQL, PostgreSQL and Redis on DignityHost MERN hosting, plus pooling tips and common errors.

Connect Node.js to MongoDB, MySQL, PostgreSQL and Redis - MERN & Node.js Hosting guide by DignityHost
  • Applies toMERN hosting plans
  • Time needed20 min
  • LevelIntermediate

Your application runs on the same server as the databases, so it connects to 127.0.0.1 and never travels over the internet. Create the database first, keep the credentials in environment variables, and reuse one connection (or pool) for the life of the process.

Node and Express app connected to MongoDB or SQL and a Redis cache

The API talks to the databases over localhost.

Get the credentials

DatabaseHow you get it
MySQL / MariaDBCreate the database and user in your panel (or with phpMyAdmin) and note the full names.
PostgreSQLCreate the database and role in the PostgreSQL manager in your panel.
MongoDBOpen a support ticket and ask for a MongoDB database and user for your account. You receive the database name, username and password. You can also use MongoDB Atlas instead.
RedisIncluded with the plan. Ask support for connection details if you want to enable it for your application.

MongoDB with Mongoose

javascript
const mongoose = require('mongoose');

async function connect() {
  await mongoose.connect(process.env.MONGODB_URI, { serverSelectionTimeoutMS: 8000, maxPoolSize: 5 });
  console.log('MongoDB connected');
}
connect().catch((e) => { console.error('MongoDB error', e.message); process.exit(1); });
.env
MONGODB_URI=mongodb://dbuser:[email protected]:27017/dbname?authSource=dbname
  • authSource is normally the database the user was created in.
  • Percent-encode special characters in the password (@ becomes %40, / becomes %2F).
  • Using MongoDB Atlas? Use the mongodb+srv:// string and allow your server's IP address in Atlas's Network Access list.

MySQL / MariaDB with mysql2

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

const pool = mysql.createPool({
  host: '127.0.0.1',
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 5,
});

const [rows] = await pool.query('SELECT NOW() AS now');

PostgreSQL with pg

javascript
const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.DATABASE_URL, // postgresql://user:[email protected]:5432/dbname
  max: 5,
  idleTimeoutMillis: 30000,
});

const { rows } = await pool.query('SELECT NOW()');

Redis with ioredis

javascript
const Redis = require('ioredis');

const redis = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379', {
  maxRetriesPerRequest: 2,
  lazyConnect: true,
});
await redis.connect();
await redis.set('greeting', 'hello', 'EX', 60);

Use Redis for caching and short-lived data (sessions, rate limits), not as the only copy of anything important.

Good connection habits

  • One pool per process. Create it at start-up and reuse it. Opening a new connection per request exhausts connections and memory.
  • Keep pools small. A pool of 3 to 5 connections is plenty for an API on shared hosting.
  • Handle errors and retries. Exit with a clear message when start-up connection fails, so the problem is visible in the log.
  • Shut down cleanly. Close pools on SIGTERM so restarts do not leave orphaned work.
  • Add a health route that runs a trivial query to confirm the database is reachable.

Common errors

ErrorLikely cause
MongoServerError: Authentication failedWrong user or password, or the wrong authSource.
ECONNREFUSED 127.0.0.1:27017Wrong port, or the database is not available for this account yet.
ER_ACCESS_DENIED_ERRORMySQL user not added to the database, or the password was changed.
password authentication failed for userPostgreSQL role or password mismatch.
Too many connectionsA new connection is created per request, or the pool is too large.

To inspect data from your own computer, use an SSH tunnel; see connect to your database over SSH.

Frequently asked questions

Should I use Atlas instead of the local MongoDB?

Local MongoDB is fastest because there is no network hop. Atlas is useful if you want managed backups, replicas or access from several servers. Either works with the same code.

Can I connect to the database from another website?

Databases accept local connections only. Use an API on your hosting, an SSH tunnel for administration, or a managed database service for remote access.

Where should the connection string live?

In environment variables set in the Application Manager, never in source code.

MongoDB, MySQL, PostgreSQL and Redis on MERN hostingNode.js 18/20/22, MongoDB, PostgreSQL, Redis and SSH on Webuzo.
MERN hosting plans →

Last reviewed 19 October 2026. Need a hand? Contact DignityHost support or open a ticket from your client area.

Was this answer helpful? 0 Users Found This Useful (0 Votes)