Deploying an Express.js and MySQL Project on cPanel: A Step-by-Step Guide


What is cPanel?
cPanel is a web-based control panel that simplifies website and server management for hosting accounts. It provides an intuitive interface for tasks like managing domains, databases, email accounts, file uploads, and more. Widely used by shared hosting providers, cPanel is popular among developers for its ease of use and robust features. For Node.js developers, cPanel offers tools to deploy applications, including Express.js projects with MySQL databases, making it a viable option for hosting web applications on shared servers.
In this article, we’ll walk you through deploying an Express.js application with a MySQL database on cPanel. Whether you’re launching a REST API or a full-stack app, this guide will help you get your project live.
Prerequisites
Before you begin, ensure you have:
A cPanel hosting account with Node.js support (check with your provider, e.g., A2Hosting or Namecheap).
An Express.js project with MySQL integration.
Basic knowledge of Node.js, Express.js, and MySQL.
Access to cPanel’s File Manager, MySQL Databases, and Setup Node.js App tools.
Step-by-Step Deployment Process
1. Verify Node.js Support in cPanel
Not all hosting plans support Node.js, so confirm that your provider enables it. In cPanel, look for the Setup Node.js App option under the Software section. If it’s unavailable, contact your hosting provider to enable Node.js or consider upgrading your plan.
2. Set Up a Node.js Application
Navigate to Setup Node.js App:
In cPanel, go to Software > Setup Node.js App.
Click Create Application.
Configure the Application:
Select a Node.js version (e.g., 18.x or the latest stable version).
Set Application Mode to Production.
Specify the Application Root (e.g.,
home/username/your_app_folder
), where your project files will reside.Choose an Application URL (your domain or subdomain, e.g.,
https://yourdomain.com
).Set the Application Startup File to your main file (e.g.,
index.js
orserver.js
).
Create the Application:
- Click Create to set up a virtual environment for your Node.js app. Note the command to enter the virtual environment (displayed in cPanel).
3. Create a MySQL Database and User
Access MySQL Databases:
- In cPanel, go to Databases > MySQL Databases.
Create a Database:
- Enter a name (e.g.,
yourapp_db
) and click Create Database.
- Enter a name (e.g.,
Create a User:
- Add a new user (e.g.,
yourapp_user
) with a strong password.
- Add a new user (e.g.,
Assign User to Database:
- Select the user and database, then grant All Privileges.
Note Credentials:
- Save the database name, username, and password for your Express.js configuration.
If your app is hosted on a different server, configure Remote MySQL:
Go to Databases > Remote MySQL.
Add your server’s IP address or use a wildcard (
%
) for access (note: wildcards are less secure).
4. Prepare Your Express.js Project
Your Express.js app needs to connect to the MySQL database and include all dependencies. Here’s a sample setup:
Install Dependencies:
Ensure your
package.json
includes necessary packages:"dependencies": { "express": "^4.18.2", "mysql2": "^3.6.0", "cors": "^2.8.5", "body-parser": "^1.20.2" }
Run
npm install
locally to generate thenode_modules
folder.
Configure Database Connection:
Use environment variables or a configuration file (e.g.,
db.config.js
):// db.config.js module.exports = { db: { host: 'localhost', // Use 'localhost' for cPanel-hosted databases user: 'yourapp_user', password: 'your_password', database: 'yourapp_db', port: 3306 } };
Sample Express.js Code:
Here’s a basic Express.js app with a MySQL connection:
const express = require('express'); const mysql = require('mysql2'); const cors = require('cors'); const bodyParser = require('body-parser'); const config = require('./db.config'); const app = express(); const PORT = process.env.PORT || 3000; // Middleware app.use(cors()); app.use(bodyParser.json()); // MySQL Connection const db = mysql.createConnection(config.db); db.connect((err) => { if (err) { console.error('Error connecting to MySQL: ' + err.stack); return; } console.log('Connected to MySQL as ID ' + db.threadId); }); // Sample Route: Get all users app.get('/api/users', (req, res) => { db.query('SELECT * FROM users', (err, results) => { if (err) { console.error('Error executing query: ' + err.stack); res.status(500).send('Error fetching users'); return; } res.json(results); }); }); // Start Server app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Create Database Tables:
Use phpMyAdmin in cPanel to create tables (e.g., a
users
table for the above code).Example SQL for a
users
table:CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL );
Test Locally:
- Run
node index.js
locally to ensure the app connects to a MySQL database and the routes work.
- Run
5. Upload Your Project to cPanel
Zip Your Project:
Exclude the
node_modules
folder to reduce file size.Compress your project into a
.zip
file.
Upload Files:
In cPanel, go to Files > File Manager.
Navigate to the Application Root folder (e.g.,
home/username/your_app_folder
).Delete any default files (except
.htaccess
, if present).Click Upload, select your
.zip
file, and extract it.
Install Dependencies:
- In Setup Node.js App, select your application and click Run NPM Install to install dependencies from
package.json
.
- In Setup Node.js App, select your application and click Run NPM Install to install dependencies from
6. Configure Environment Variables
If your app uses environment variables (e.g., for database credentials), add them in cPanel:
Go to Setup Node.js App > Add Variables.
Add variables like:
DB_HOST=localhost DB_USER=yourapp_user DB_PASSWORD=your_password DB_DATABASE=yourapp_db PORT=3000
7. Set the Startup File
In Setup Node.js App, ensure the Application Startup File matches your main file (e.g., index.js
). Save and click Restart to apply changes.
8. Test Your Application
Access your app via the Application URL (e.g.,
https://yourdomain.com
).Test endpoints (e.g.,
https://yourdomain.com/api/users
) using a browser or Postman.Check cPanel’s Error Log (under Metrics) or Node.js logs in the application folder for issues.
9. Configure Apache (Optional)
If your app runs on a non-standard port (e.g., 3000), set up a reverse proxy:
Edit or create an
.htaccess
file in the application root:RewriteEngine On RewriteCond %{HTTP_HOST} ^yourdomain.com$ [OR] RewriteCond %{HTTP_HOST} ^www.yourdomain.com$ RewriteRule ^(.*)$ http://localhost:3000/$1 [P,L]
Ensure Apache’s
mod_proxy
andmod_rewrite
modules are enabled (check with your provider).If your hosting uses AutoSSL, HTTPS should work automatically.
10. Troubleshoot Common Issues
Database Connection Errors:
Verify credentials and ensure the database user has privileges.
Use
localhost
as the host for cPanel-hosted databases.For remote servers, whitelist the IP in Remote MySQL.
App Not Starting:
Confirm the startup file is correct.
Check for syntax errors using cPanel’s Terminal (if available) with
node index.js
.
ER_NOT_SUPPORTED_AUTH_MODE:
Use the
mysql2
package instead ofmysql
for newer MySQL authentication protocols.Install with
npm install mysql2
and update your code.
Best Practices for Production
Security:
Store sensitive data in environment variables.
Use HTTPS (enabled via AutoSSL or a custom SSL certificate).
Regularly update dependencies (
npm update
) to patch vulnerabilities.
Performance:
Use
mysql2.createPool
instead ofcreateConnection
for better scalability:const db = mysql.createPool(config.db);
Backups:
- Regularly back up your database and files using cPanel’s Backup tool.
Conclusion
Deploying an Express.js and MySQL project on cPanel is straightforward with the right steps. By setting up a Node.js environment, configuring your database, and uploading your project, you can run your app in no time. While cPanel is convenient for shared hosting, consider cloud platforms like AWS or Heroku for more complex apps requiring greater scalability.
If you encounter issues or need to add features like a frontend, consult your hosting provider’s documentation or reach out for support. Happy coding, and enjoy seeing your app live on the web!
Subscribe to my newsletter
Read articles from Albert Kipchirchir directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
