Setting up your NestJS application to connect with Amazon DocumentDB can be challenging. You might face issues with TLS/SSL configuration or security groups.
This guide will walk you through the process smoothly, ensuring a hassle-free setup.
Understanding the Connectivity requirement of DocumentDb
Before creating your DocumentDB database, it's important to know that Amazon DocumentDB is accessible by Amazon EC2 instances and other AWS services within the same VPC. You can connect also from different VPCs within the same AWS Region or across Regions using VPC peering.
If you need to access DocumentDB from outside AWS, you can use SSH tunneling.
1. Creating a New Amazon DocumentDB Cluster
Step 1: Access the AWS Console
Login to your AWS console.
In the search bar at the top of the console, type "DocumentDB" and select Amazon DocumentDB from the search results.
Step 2: Begin Cluster Creation
- On the Amazon DocumentDB page, click Create Cluster or Create your first cluster if this is your first time setting up DocumentDB.
Step 3: Configure Cluster Settings: Fill in the required information
DB Cluster Identifier: Provide a unique name for your cluster.
Authentication Method: Enter the necessary credentials (username and password) for your cluster.
Step 4: Finalize and Create the Cluster
After filling in the required details, review your configuration settings
Click Create Cluster to initiate the cluster creation process.
AWS will take a few minutes to provision your new DocumentDB cluster. Once completed, you'll have a fully functional cluster ready for use.
2. Set Up a Security Group to Allow Connectivity to the DocumentDB Cluster Within the VPC
Next, we'll need to configure security groups to allow our Nest.js application to connect to the DocumentDB cluster within the VPC.
Step 1: Create a Security Group
In your AWS Console, Search for Security Groups
Click Create Security Group.
Provide a Name and Description for the security group
Ensure you select the appropriate VPC where your DocumentDB cluster reside
Step 2: Configure Inbound Rules
Under the Inbound rules tab, click Add Rule.
Set the Type to Custom TCP
For the Port Range, enter 27017 (the default port for DocumentDB)
In the Source field, specify
Anywhere
or0.0.0.0/0
this would allow us to connect from anywhere within the vpc
Step 3: Configure Outbound Rules
Under the Outbound rules tab, click Add Rule.
Set the Type to Custom TCP
For the Port Range, enter 27017 (the default port for DocumentDB)
In the Source field, specify
Anywhere
or0.0.0.0/0
Once you've configured the rules, click Create Security Group. Your new security group is now ready to allow traffic to and from your DocumentDB cluster.
Step 4: Modify DocumentDb Security Group
Go back to the Amazon DocumentDB service in the AWS Console
Select your newly created cluster.
On the VPC Security groups section replace the current security group with the new one you created.
Click Continue to proceed.
Check the Apply Immediately box to enforce the changes without delay.
Click Modify cluster to finalize the update.
The above steps will update your cluster's security settings, ensuring your DocumentDB is fully configured and ready for use.
3. Creating Our Nest.js application and Connecting to DocumentDb
Step 1: Let's create a new NestJS project
nest new document-db-app
I would Open the project with vs code and install the necessary dependencies.
npm install @nestjs/mongoose mongoose @nestjs/config
Step 4: Download the Amazon DocumentDB Certificate Authority (CA) certificate
Navigate to your DocumentDB dashboard and click the Connectivity & Security
tab. Find and copy the link to download the Amazon DocumentDB CA certificate. Save this file in the root of your project.
Step 5: Setup Connection to Document db
//src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import * as path from 'path';
@Module({
imports: [
ConfigModule.forRoot(),
MongooseModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
uri: configService.get('DOCUMENTDB_URI'),
tls: true,
tlsCAFile: path.resolve('global-bundle.pem'),
}),
inject: [ConfigService],
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
In the app.module.ts file, we connect our NestJS application to DocumentDB using MongooseModule. Inside MongooseModule, we call the forRootAsync method to configure the connection asynchronously.
In forRootAsync, we define a useFactory function, which retrieves the database URI from environment variables using Config Module
. We also set tls: true
option to enable secure communication and specify the tlsCAFile
option to point to our downloaded CA certificate global-bundle.pem
, ensuring that the connection is authenticated.
By doing this, we set up a secure and reliable connection to DocumentDB, allowing our NestJS application to interact with the database safely.
Step 6: Setting Up the Environment Variables
Create a .env
file in the project root and add the DocumentDb connection string
DOCUMENTDB_URI=mongodb://username:password@<your-documentdb-endpoint>:27017/<your-database-name>?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false
Note: The above setup assumes you have your app running in the same VPC as your Documentdb cluster. Amazon DocumentDB does not support direct connections from outside the VPC for security reasons.
If you need to connect from your local machine for testing or development purposes you need to setup ssh tunneling through an EC2 instance. For a step-by-step guide on how to set this up, refer to this article on Connecting to DocumentDB via SSH tunneling.
Top comments (0)