Recently, I had to create a NodeJS application where I had to connect to 2 different database in PostgreSQL and MongoDB. For application scaling, I had to use Docker and Kubernetes. Here's how I connected all these inside docker.
In order to run this whole thing using
docker-compose
, visit this repo: https://github.com/fahadfahim13/node-pg-mongo-docker.git
Project Setup
Run the following commands with your preferred project name:
mkdir node-postgres-mongo
cd node-postgres-mongo
npm init -y
The install these dependencies:
npm install express pg mongoose dotenv
Inside this project, create an index.js
file and a .env
file.
Also, create a config
folder, and inside this folder, create mongodb.js
and postgres.js
files for configuration.
The index.js file should look like this:
const express = require('express');
const pgPool = require('./config/postgres');
const connectMongoDB = require('./config/mongodb');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 8088;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, async () => {
try {
// Initialize database connections
await connectMongoDB();
await pgPool.connect();
console.log('PostgreSQL connected successfully');
console.log(`Server is running at http://localhost:${port}`);
} catch (error) {
console.error('Error during startup:', error);
process.exit(1);
}
});
The config/postgres.js
should look like this:
const { Pool } = require('pg');
require('dotenv').config();
const pgPool = new Pool({
host: process.env.POSTGRES_HOST || 'postgres-db', // PostgreSQL container name
port: 5432,
user: process.env.POSTGRES_USER || 'admin',
password: process.env.POSTGRES_PASSWORD || 'admin123',
database: process.env.POSTGRES_DB || 'testdb',
});
module.exports = pgPool;
The config/mongodb.js
should look like this:
const mongoose = require('mongoose');
require('dotenv').config();
const connectMongoDB = async () => {
try {
const mongoURI = `mongodb://${process.env.MONGO_INITDB_ROOT_USERNAME || 'root'}:${process.env.MONGO_INITDB_ROOT_PASSWORD || 'root123'}@${process.env.MONGO_INITDB_ROOT_CONTAINER || 'mongo-container'}:27017/testdb?authSource=admin`;
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));
console.log('MongoDB connected successfully');
} catch (error) {
console.error('MongoDB connection error:', error);
process.exit(1);
}
};
module.exports = connectMongoDB;
Docker Setup
Create Dockerfile
Create a file named Dockerfile
inside root directory of the nodejs project and paste this code:
FROM node:18
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8088
CMD ["npm", "start"]
Network creation
In order to connect all containers, we need one docker network by which all containers can connect. Run the following commands:
docker network create node-postgres-mongo # Creates a network named node-postgres-mongo
docker network ls # Lists all networks available in docker to check
PostgreSQL container setup
docker pull postgres # Pulls image if not available in local
docker run --name postgres-db --network node-postgres-mongo -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=admin123 -e POSTGRES_DB=testdb -p 5432:5432 -d postgres # Runs the DB in a container named postgres-db
After this, if you run docker ps
, you should see a container named postgres-db
.
MongoDB container setup
docker pull mongo # Pulls if image is not available in local
docker run --name mongo-db --network node-postgres-mongo -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=root123 -p 27017:27017 -d mongo # Creates a container in the same network named mongo-db
NodeJS container run
docker build -t node-pg-mongo . # Build the image with name node-pg-mongo in the root directory
docker run --name node-pg-mongo --network node-postgres-mongo -p 8088:8088 -d node-pg-mongo # Run the image into container named node-pg-mongo in the same network
All Done! Now if we run docker logs node-pg-mongo
, we can see the logs of the running application and it can connect to both mongodb
and postgres
:
In order to run this whole thing using docker-compose
, visit this repo: https://github.com/fahadfahim13/node-pg-mongo-docker.git
Top comments (0)