DEV Community

Cover image for Node.js Meets PostgreSQL and MongoDB in Docker: Docker Diaries
Fahim Hasnain Fahad
Fahim Hasnain Fahad

Posted on

Node.js Meets PostgreSQL and MongoDB in Docker: Docker Diaries

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.

NodeJS connects with PostgreSQL and MongoDB in 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

Enter fullscreen mode Exit fullscreen mode

The install these dependencies:

npm install express pg mongoose dotenv
Enter fullscreen mode Exit fullscreen mode

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);
    }
});
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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"]

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

After this, if you run docker ps, you should see a container named postgres-db.

PostgreSQL Container

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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:

NodeJS Application Logs

NodeJS Application Running
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)