Connect NestJS to PostgreSQL Through Teleport Like a Pro!
Connecting NestJS to PostgreSQL through Teleport
Imagine this: You’re a developer at a fast-growing tech startup. The application you’re building needs secure, efficient database access, and as your infrastructure expands, so does the demand for security. Your database is tucked away in a private network, and traditional SSH tunneling doesn’t feel safe or scalable enough.
Enter Teleport. Your team is eager to try it, and you’ve been tasked with connecting your NestJS application to a PostgreSQL database through a secure Teleport proxy.
In this post, I’ll share the complete journey—roadblocks and all—on how I set up my NestJS app to connect securely to PostgreSQL through Teleport’s database access. If you’re ready to save hours of searching and setup, this guide is for you!
Why Teleport for Database Access?
Teleport offers role-based, secure access to infrastructure, including databases, servers, and Kubernetes clusters. It’s like giving your app a VIP pass to the database, but one that checks IDs, logs every action, and guards against unauthorized access.
Teleport’s database access proxy can serve as a middleman between your private database and your app, ensuring only authorized and authenticated users or applications gain access.
Step 1: Set Up the Teleport Database Proxy
Let’s start by setting up a local Teleport proxy that will act as our secure bridge to PostgreSQL. Begin by logging in to Teleport and establishing a proxy for your database.
- Open your terminal and authenticate to Teleport using your credentials.
- Run the following command, substituting <database_name> with the name of your database:
tsh proxy db <database_name> --port 9000
This command creates a local endpoint on your machine, typically accessible at localhost:9000. It will act as the gateway between your application and the database.
Fig. 1: Using Teleport to securely proxy to the database.
Step 2: Secure Your Teleport Credentials
After you’ve connected, Teleport generates three essential files for secure access:
- ca_file: The Certificate Authority file that verifies the authenticity of the connection.
- cert_file: Your client certificate.
- key_file: Your private key for connecting securely.
Store these files in a secure location in your project folder, or specify their absolute paths. These files will be necessary to establish a trusted connection between your NestJS app and PostgreSQL.
?? Tip: Make sure to restrict access to these files and avoid committing them to version control.
Step 3: Configure the Database Connection in NestJS
Now that we have our proxy and certificates, it’s time to configure the database connection in NestJS.
In typeorm.config.ts, update your database connection settings. Here’s how to set up TypeORM to use the Teleport proxy and SSL certificates:
import { TypeOrmModule } from '@nestjs/typeorm';
import * as fs from 'fs';
import * as path from 'path';
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost', // Teleport proxy usually runs on localhost
port: 9000, // Ensure this matches your `tsh proxy db` port
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
ssl: {
ca: fs.readFileSync(path.resolve(__dirname, 'path/to/ca_file')).toString(),
cert: fs.readFileSync(path.resolve(__dirname, 'path/to/cert_file')).toString(),
key: fs.readFileSync(path.resolve(__dirname, 'path/to/key_file')).toString(),
rejectUnauthorized: true, // Set to false for local testing
},
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
synchronize: true, // Set to false in production
}),
Replace 'path/to/ca_file', 'path/to/cert_file', and 'path/to/key_file' with the actual paths to your certificate files.
?? Note: rejectUnauthorized: true should be used in production to ensure the server’s certificate is verified. Set it to false only for local testing.
Step 4: Run the Application
With everything configured, you’re ready to run your NestJS application. This will establish a secure connection to the PostgreSQL database through Teleport.
npm run start
Your NestJS app is now securely connected to PostgreSQL via Teleport. ??
Troubleshooting Common Issues
- getaddrinfo ENOTFOUND Error: This often occurs if the Teleport proxy isn’t running. Verify that tsh proxy db is active and using localhost.
- TypeScript Module Errors: If TypeScript doesn’t recognize fs, you may need to install Node.js types:
- Session Expiration: Teleport sessions may expire periodically, requiring re-authentication. Use tsh to log back in and keep the proxy active.
Conclusion
Securing database access doesn’t have to be a complex maze. By leveraging Teleport’s proxy and SSL certificate-based connection, you can add an extra layer of security and compliance to your application.
With Teleport, you don’t just gain access; you gain control, visibility, and peace of mind knowing your database is safe. Plus, you’ve now got the knowledge to empower others to tackle the same challenges with confidence.
Feel free to reach out with any questions or share your own experiences in the comments below. Happy coding!
#NestJS #PostgreSQL #Teleport #SecureDatabaseAccess #DatabaseSecurity #BackendDevelopment #NodeJS #TypeORM #Cybersecurity #DevOps #FullStackDevelopment #WebDevelopment #DatabaseProxy #SSLConnections #CloudInfrastructure #DataSecurity #TechTutorial #SoftwareEngineering #CloudSecurity #SecureCoding
Director Technology | Product Manager | Engineering Manager | CSPO? | CSM? | Leading SAFe| SAFe? | Product Owner | Scrum Master | Senior Software Architect | Agile | Consultant | Digital Transformation Specialists
4 个月Very informative