Logo

dev-resources.site

for different kinds of informations.

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

Published at
1/7/2025
Categories
node
docker
postgres
mongodb
Author
fahim_hasnainfahad_7e50d
Categories
4 categories in total
node
open
docker
open
postgres
open
mongodb
open
Author
24 person written this
fahim_hasnainfahad_7e50d
open
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

docker Article's
30 articles in total
Favicon
Building bun-tastic: A Fast, High-Performance Static Site Server (OSS)
Favicon
Day 04: Docker Compose: Managing multi-container applications
Favicon
Infraestrutura para anΓ‘lise de dados com Jupyter, Cassandra, Pyspark e Docker
Favicon
Building RelaxTube: A Scalable Video Transcoding and Streaming Application
Favicon
Docker vs kubernetes
Favicon
Advanced Docker Concepts and Features
Favicon
Building and Deploying Your First Java App with Docker in Just 5 Minutes
Favicon
Realtime troubleshooting based questions docker compose
Favicon
common Docker Compose interview questions.
Favicon
[Boost]
Favicon
Docker scenario
Favicon
TOP 10 TYPES OF DOCKER COMMANDS
Favicon
how to inspect a docker container
Favicon
How to run a Nginx-web server
Favicon
Docker article Best
Favicon
Load Balancing Node.js Applications with Nginx Upstream Configuration
Favicon
Top 20 Docker Commands with Examples and Outputs
Favicon
🌟 Deploying a Live Project Without a Dockerfile Using Buildpacks 🌟
Favicon
A Conversation with Docker CTO Justin Cormack and Flux CEO Ron Efrani: The Future of Developer Environments
Favicon
Understanding Node.js Alpine Versions: A Lightweight Choice for Your Projects
Favicon
Day 03: Docker Images and Containers: Building, Pulling, and Running Docker Containers
Favicon
How would you optimize the performance of Docker containers, particularly in resource-constrained environments ?
Favicon
Docker in development: Episode 4
Favicon
Building a Local S3 Environment with MinIO: AWS SDK for Java V2 Migration Guide
Favicon
Node.js Meets PostgreSQL and MongoDB in Docker: Docker Diaries
Favicon
How to Use Docker in Your Data Science Projects: A Complete Guide
Favicon
Bringing Together Containers & SQL
Favicon
πŸš€ Are Your Docker Containers Secure? πŸ›‘οΈ In this article, learn 10 actionable strategies to protect your Docker containers like a pro
Favicon
Running PostgreSQL, MongoDB, and NestJS concurrently with Docker Compose
Favicon
Creando un notebook con Jupyter y Kotlin

Featured ones: