Applications and operations

Connect to MySQL from Node.js

Optionally connect from Node.js with mysql2, environment-based credentials, a bounded pool, and explicit connection timeouts.

8 minute lesson

~~~

The application lessons use Node.js as an optional track. You can follow the database and operations lessons without it.

Install the promise-based mysql2 driver:

npm install mysql2

Create a bounded pool from environment variables:

import mysql from 'mysql2/promise'

export const pool = mysql.createPool({
  host: process.env.DB_HOST,
  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,
  queueLimit: 20,
  connectTimeout: 5000,
  enableKeepAlive: true,
})

Five connections is an example budget, not a universal value. Count every application replica before choosing the limit.

Call await pool.end() when a script or worker shuts down. A long-running web process keeps the pool open until its shutdown hook runs.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →