Getting started with AWS EC2 and RDS using Node.js and Postgres

Deploying a Node.js backend can be challenging, especially when configuring AWS EC2 for server hosting and RDS for database management. In this guide, we’ll set up an API with Node.js and Sequelize, deploy it on an EC2 instance, and configure an RDS PostgreSQL database to work seamlessly with the EC2 instance.
I recently gave an online session on this topic and thought of writing this blog for the ones who like reading than a video (I might be one of you🫡)
1. Setting Up the Node.js Project
Project Initialization
- Initialize a new Node.js project:
mkdir my-node-app
cd my-node-app
npm init -y
2. Install necessary dependencies
npm install express sequelize pg pg-hstore dotenv
Project Structure
Organize the project with a structure that’s scalable for future growth. Here’s an example:
my-node-app/
├── config/
│ └── config.js # Database configuration
├── models/
│ └── index.js # Sequelize models setup
├── routes/
│ └── index.js # Define API routes
├── .env # Environment variables
└── app.js # Express application setup
2. Configuring Sequelize with PostgreSQL
- Create a
.env
file to store environment variables:
DB_HOST=your_rds_endpoint
DB_PORT=5432
DB_USER=your_rds_username
DB_PASSWORD=your_rds_password
DB_NAME=your_rds_database
2. Set up the Sequelize configuration in config/config.js
:
require('dotenv').config();
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: 'postgres'
}
};
3. Define the model setup in models/index.js
:
const Sequelize = require('sequelize');
const config = require('../config/config.js')['development'];
const sequelize = new Sequelize(config.database, config.username, config.password, config);
module.exports = sequelize;
3. Building an Example API Endpoint
- Create a sample API endpoint in
routes/index.js
:
const express = require('express');
const router = express.Router();
const sequelize = require('../models/index.js');
router.get('/status', async (req, res) => {
try {
await sequelize.authenticate();
res.json({ message: 'Connection has been established successfully.' });
} catch (error) {
res.status(500).json({ message: 'Unable to connect to the database.', error });
}
});
module.exports = router;
2. Integrate the route with the Express app in app.js
:
const express = require('express');
const app = express();
const routes = require('./routes/index.js');
app.use('/api', routes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
2. AWS EC2 Setup for Node.js
Launching an EC2 Instance
- Go to AWS EC2 Dashboard and launch a new instance.
- Choose Amazon Linux 2 or Ubuntu as the instance type.
- Select an instance size (e.g., t2.micro for free-tier eligible).
- Configure security groups to allow HTTP (port 80), HTTPS (port 443), and SSH (port 22).
SSH into the EC2 Instance
- Connect to your instance using SSH:
ssh -i /path/to/your-key.pem ec2-user@your-ec2-public-dns
2. Update the instance and install Node.js and npm:
sudo yum update -y
sudo yum install -y nodejs
Setting Up Your Project on EC2
- Clone your project repository or copy your files to the server.
- Install project dependencies:
npm install
3. Set up environment variables on the EC2 instance:
export DB_HOST=your_rds_endpoint
export DB_PORT=5432
export DB_USER=your_rds_username
export DB_PASSWORD=your_rds_password
export DB_NAME=your_rds_database
4. Start the server:
node app.js
3. Setting Up PostgreSQL with AWS RDS
Creating an RDS Instance
- Go to AWS RDS Console and create a new PostgreSQL instance.
- Configure database details and select a public subnet for accessibility.
- Take note of the RDS endpoint to use in your
.env
file.
Configuring RDS Security
- In your EC2 security group, add an inbound rule to allow the RDS instance to accept connections from the EC2 IP address.
- In your RDS instance security group, add an inbound rule for the PostgreSQL port (default is 5432) to allow the EC2 instance to connect.
Connecting EC2 and RDS
After configuring the security groups, use your RDS instance endpoint in the .env
file or directly export it on EC2, as shown above.
4. Testing the API
- After starting the server, navigate to the public IP of your EC2 instance (e.g.,
http://your-ec2-public-dns:3000/api/status
). - You should see a JSON response confirming the database connection:
{
"message": "Connection has been established successfully."
}
5. Making the Application Production-Ready
To keep your Node.js server running, consider using a process manager like PM2:
- Install PM2:
sudo npm install pm2 -g
2. Start your app with PM2:
pm2 start app.js --name my-node-app
3. PM2 will keep the app running, even if the server restarts.
Conclusion
In this setup, we’ve created a Node.js API, deployed it on an EC2 instance, and connected it to an RDS PostgreSQL database. This setup ensures a scalable, production-ready backend with persistent storage and a managed database solution on AWS.