Configure the RDS PostgreSQL Database Using the AWS CDK in Node.js

Chandan Kumar
Stackademic
Published in
3 min readApr 5, 2024

--

Photo by Colton Sturgeon on Unsplash

To configure and use an RDS PostgreSQL database using the AWS CDK in Node.js, you’ll need to follow several steps. These include setting up your AWS CDK project, adding the necessary CDK packages for RDS, creating the PostgreSQL database instance, configuring security groups for database access, and finally connecting to your database.

1. Setting Up Your AWS CDK Project

If you haven’t already, you’ll first need to install the AWS CDK CLI and initialize a new CDK project:

npm install -g aws-cdk
cdk init app --language=typescript

Although the initialization command specifies TypeScript, the AWS CDK supports both TypeScript and JavaScript. If you’re using JavaScript, the process remains largely the same.

2. Install RDS Package

You’ll need the RDS package to work with Amazon RDS. Install it using npm:

npm install @aws-cdk/aws-rds @aws-cdk/aws-ec2

3. Creating the PostgreSQL Database

In your CDK stack file (e.g., lib/my-stack.ts or lib/my-stack.js), add the following code to create a PostgreSQL database:

import * as cdk from '@aws-cdk/core';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as rds from '@aws-cdk/aws-rds';

export class MyDatabaseStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

// Create a VPC for our database
const vpc = new ec2.Vpc(this, 'MyVpc', {
maxAzs: 2 // Default is all AZs in the region
});

// Create the RDS instance
const dbInstance = new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.postgres({
version: rds.PostgresEngineVersion.VER_12_3,
}),
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
vpc,
vpcSubnets: {
subnetType: ec2.SubnetType.PUBLIC,
},
allocatedStorage: 20,
maxAllocatedStorage: 100,
securityGroups: [], // We will add this next
deleteAutomatedBackups: true,
removalPolicy: cdk.RemovalPolicy.DESTROY, // NOT recommended for production code
databaseName: 'mydatabase',
credentials: rds.Credentials.fromGeneratedSecret('postgres'), // Username 'postgres' and an auto-generated password
});

// Output the auto-generated password and the DB instance endpoint
new cdk.CfnOutput(this, 'DBEndpoint', { value: dbInstance.dbInstanceEndpointAddress });
new cdk.CfnOutput(this, 'DBPassword', { value: dbInstance.secret?.secretValue.toString()! });
}
}

4. Configure Security Group

To allow connections to your database, you’ll need to adjust the security group settings. Modify the securityGroups property in the DatabaseInstance construct as needed, or let CDK create a new security group and adjust it post-creation

const dbSecurityGroup = new ec2.SecurityGroup(this, 'DatabaseSecurityGroup', {
vpc,
description: 'Allow postgresql access to db',
allowAllOutbound: true, // Can be set to false
});
dbSecurityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(5432), 'allow PostgreSQL access');

// Then, include it in the RDS DatabaseInstance properties:
securityGroups: [dbSecurityGroup],

5. Deploy Your CDK Stack

Deploy your CDK stack to AWS:

cdk deploy

6. Connect to Your PostgreSQL Database

Once deployed, you can connect to your PostgreSQL database using the endpoint and credentials output by the CDK deployment. Use a PostgreSQL client and the credentials to establish a connection.

Remember, for production environments, you should adjust the removal policy and ensure your database is not publicly accessible unless necessary. Always follow the principle of least privilege when configuring access to your AWS resources.

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--