Hosting a Node.js website with a MySQL database on Amazon Web Services (AWS) Elastic Compute Cloud (EC2) is a popular, cost-effective way to deploy scalable web applications. AWS EC2 offers flexibility and scalability, enabling you to create virtual servers where you can install and configure the necessary software to support your application.
In this comprehensive guide, we’ll cover how to:
- Set up an EC2 instance
- Configure Security Groups to ensure safe access
- Install Node.js and MySQL
- Deploy a Node.js application
- Connect Node.js to MySQL
- Test and secure your setup
Let’s get started!
1. Setting Up an EC2 Instance
Step 1: Log in to AWS and Launch an EC2 Instance
- Log into your AWS account at the AWS Management Console.
- Go to EC2 Dashboard and click Launch Instance.
- Choose an Amazon Machine Image (AMI). Amazon Linux 2 is recommended because it’s compatible with Node.js and MySQL, and is optimized for performance on AWS.
- Select the instance type based on your application requirements. For beginners or low-traffic applications, the t2.micro instance is a good choice, as it is eligible for AWS’s Free Tier.
- Configure your instance settings, such as the number of instances (usually 1), storage volume (8 GB default is often enough), and tags if needed.
- Under Security Group Settings, set up the access rules (we’ll go over this more thoroughly in Step 2).
- Click Review and Launch. Before launching, you’ll be prompted to create a new key pair or use an existing one for SSH access. Download this .pem file securely, as you’ll need it to access your instance.
Step 2: Connect to Your EC2 Instance via SSH
- After launching, you can access your instance’s public IP or DNS address from the EC2 dashboard.
- Open your terminal and navigate to the directory where your .pem key file is stored.
- Use the command below to SSH into your instance, replacing <your-key.pem> with the actual filename and <your-ec2-public-ip> with your instance’s public IP address:
ssh -i "your-key.pem" ec2-user@your-ec2-public-ip
- Once connected, you’ll have access to the EC2 instance, allowing you to configure and deploy your application.
2. Configuring Security Groups
Security groups are essential for controlling access to your EC2 instance, ensuring that only approved connections are allowed.
Setting Security Group Rules
- Go to the EC2 Dashboard > Network & Security > Security Groups.
- Create a new Security Group or edit an existing one associated with your instance.
- Configure the following inbound rules:
- SSH (port 22): Enable this for your IP address to allow secure SSH access to your instance. You can find your IP at https://www.whatismyip.com.
- HTTP (port 80): Allow from anywhere (0.0.0.0/0) if your application will be publicly accessible.
- MySQL (port 3306): Allow from specific IP addresses or your local network to secure MySQL access.
3. Installing Node.js and NPM on EC2
With your instance set up, you’ll need to install Node.js and npm, the package manager for JavaScript, on the server.
- Update your package manager to ensure you’re installing the latest versions:
sudo yum update -y
- Install Node.js and npm. AWS provides an Amazon Linux 2 AMI, which has easy-to-follow steps for Node.js installation:
curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash -
sudo yum install -y nodejs
- Verify that Node.js and npm were installed correctly:
node -v
npm -v
- Optionally, you can install common libraries like express and mysql by running:
npm install express mysql
- Create a package.json file to document dependencies:
json
{
"name": "my-node-app",
"version": "1.0.0",
"main": "app.js",
"dependencies": {
"express": "^4.17.1",
"mysql": "^2.18.1"
}
}
- With Node.js and npm installed, you’re now ready to configure MySQL.
4. Setting Up MySQL
Option 1: Installing MySQL on the Same EC2 Instance
If you prefer to keep everything on one server, you can install MySQL directly on your EC2 instance.
- Install MySQL server:
sudo yum install mysql-server -y
- Start the MySQL service:
sudo service mysqld start
- Secure your MySQL installation:
sudo mysql_secure_installation
- Create a new database and user for your application:
sql
mysql -u root -p
CREATE DATABASE myappdb;
CREATE USER 'myappuser'@'localhost' IDENTIFIED BY 'securepassword';
GRANT ALL PRIVILEGES ON myappdb.* TO 'myappuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
Option 2: Using Amazon RDS for MySQL
For better scalability, you may want to separate the database by hosting it on Amazon RDS.
- Go to the RDS Dashboard in AWS and select Create Database.
- Choose MySQL as the database engine, and select a free-tier eligible instance type if available.
- Configure database settings, like username and password, and create the database.
- Make note of the endpoint (hostname) and port, which you’ll need to connect your Node.js application to the database.
5. Deploying the Node.js Application
Step 1: Upload Your Application to EC2
To get your code onto the server, you can either push it from a version control system (e.g., Git) or upload it via SCP.
- Copy files using SCP:
scp -i "your-key.pem" -r /path/to/your/app ec2-user@your-ec2-public-ip:/home/ec2-user/
- Set up a simple Express application. Create an app.js file in your project’s root directory with the following content:
javascript
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World! Your Node.js app is running on AWS EC2.');
});
app.listen(80, () => {
console.log('Server is running on port 80');
});
- Run the application:
node app.js
- To keep your app running in the background, use a process manager like PM2:
sudo npm install pm2 -g
pm2 start app.js
pm2 startup
pm2 save
6. Connecting Node.js to MySQL
Update app.js to include a MySQL connection.
- Create a MySQL connection in your Node.js application. Here’s a sample setup:
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'localhost', // Use RDS endpoint if using Amazon RDS
user: 'myappuser',
password: 'securepassword',
database: 'myappdb'
});
db.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database');
});
app.get('/data', (req, res) => {
db.query('SELECT * FROM your_table', (err, results) => {
if (err) throw err;
res.send(results);
});
});
- Ensure the database connection is configured properly, handling errors as needed. Replace host, user, password, and database with your actual values.
7. Testing and Securing the Application
Testing
- Open a web browser and go to your EC2 instance’s public IP address. If your configuration is correct, you should see a “Hello, World!” message on the main page.
- Test other routes (e.g., /data) to verify that the MySQL connection and data retrieval are functioning.
Securing the Application
- Set up HTTPS with a service like Let’s Encrypt for secure communication.
- Store sensitive data (e.g., database credentials) in environment variables instead of hardcoding them. Consider using a .env file with dotenv:
javascript
require('dotenv').config();
const db = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
});
- Limit MySQL access in the security group to specific IP addresses.
- Update your dependencies and regularly patch your OS for security.
Conclusion
Deploying a Node.js application with MySQL on AWS EC2 gives you a powerful platform for web applications. Following these steps, you’ve created an EC2 instance, configured Node.js and MySQL, and secured your setup. AWS’s flexibility allows for easy scaling, and with additional tools like CI/CD pipelines and containerization, you can make deployment even more efficient. Enjoy your new web application hosted on the cloud!
You can check our latest writes here