Merijn Monfils
Merijn Monfils

Reputation: 11

Can each service in a docker-compose file have their own mongo instance?

In this case I have two services and their respective database

version: '3.8'

services:
  authentication:
    build:
      context: ./authentication
      dockerfile: dockerfile
    environment:
      PORT: 3001
      DB_PORT: 27017
      DB_NAME: authenticationdatabase
      DB_USER: username
      DB_PASSWORD: password
      SIGNATURE_KEY: DITMOETGEINJECTEERDWORDEN
    volumes:
      - ./authentication:/authentication
    ports:
      - 3001:3001

  authenticationdatabase:
    image: mongo:latest
    environment:
      - MONGO_INITDB_DATABASE=authenticationdatabase
      - MONGO_INITDB_ROOT_USERNAME=username
      - MONGO_INITDB_ROOT_PASSWORD=password
    ports:
      - 27017:27017
    restart: always
    volumes:
      - authentication_db_volume:/data/authentication

  hosting:
    build:
      context: ./hosting
      dockerfile: dockerfile
    environment:
      PORT: 3002
      DB_PORT: 27017
      DB_NAME: hostingdb
      DB_USER: username
      DB_PASSWORD: password
      CLOUDINARY_URL: ${CLOUDINARY_URL}
      JWT_SIGNATURE_KEY: DITMOETGEINJECTEERDWORDEN
    volumes:
      - ./hosting:/hosting
    ports:
      - 3002:3002
    restart: always
    depends_on:
      - hostingdb

  hostingdb:
    image: mongo:latest
    environment:
      - MONGO_INITDB_DATABASE=hostingdb
      - MONGO_INITDB_ROOT_USERNAME=username
      - MONGO_INITDB_ROOT_PASSWORD=password
    ports:
      - 27018:27017
    restart: always
    volumes:
      - hostingdb_volume:/data/hosting
volumes:
  authentication_db_volume:
  hostingdb_volume:

Running this docker-compose file works perfectly, and both instances of mongodb run on their respective ports: both mongodb instances

The issue comes from when one of the services connects with mongodb through mongoose, for example here is authentication service connecting with authenticationdatabase:

Error connecting to MongoDB: MongooseServerSelectionError: connection timed out
  at NativeConnection.Connection.openUri (/authentication/node_modules/mongoose/lib/connection.js:825:32)
  at /authentication/node_modules/mongoose/lib/index.js:414:10
  at /authentication/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5
  at new Promise (<anonymous>)
  at promiseOrCallback (/authentication/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)
  at Mongoose._promiseOrCallback (/authentication/node_modules/mongoose/lib/index.js:1288:10)
  at Mongoose.connect (/authentication/node_modules/mongoose/lib/index.js:413:20)
  at Object.<anonymous> (/authentication/services/mongoose.js:27:10)
  at Module._compile (internal/modules/cjs/loader.js:1114:14)
  at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10) {
reason: TopologyDescription {
  type: 'Unknown',
  servers: Map(1) { 'authenticationdatabase:27017' => [ServerDescription] },
  stale: false,
  compatible: true,
  heartbeatFrequencyMS: 10000,
  localThresholdMS: 15,
  setName: null,
  maxElectionId: null,
  maxSetVersion: null,
  commonWireVersion: 0,
  logicalSessionTimeoutMinutes: null
},
code: undefined

And finally here is the connector for mongoose:

const mongoose = require('mongoose');
const connectionString = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_NAME}:${process.env.DB_PORT}`;


// Set up Mongoose connection event listeners
const db = mongoose.connection;
mongoose.set('strictQuery', false)
db.set('strictQuery', false);
db.on('connecting', () => {
  console.log('Connecting to MongoDB...');
});

db.on('connected', () => {
  console.log('Connected to MongoDB');
});

db.on('error', (error) => {
  console.error('Error connecting to MongoDB:', error);
  process.exit(1); // Exit the process if there is an error connecting to the database
});

db.on('disconnected', () => {
  console.log('Disconnected from MongoDB');
});

// Connect to MongoDB
mongoose.connect(connectionString);

module.exports = db;

Running each service individually works perfectly fine, but combined causes a port block or something else which I can't see or find. Please help.

Tried port fixing with the docker command expose, or inserting the mongo command so that it listens to different ports, unsuccesful

Upvotes: 1

Views: 39

Answers (1)

Merijn Monfils
Merijn Monfils

Reputation: 11

My solution came from building a better dependency when building. Allowing the secondary mongo image to wait for the previous database before building solved my issue. Also in docker-desktop running the first database, then the service, allowing those to connect then repeat for the second database and service. This worked perfectly, so use those depends_on :)

Upvotes: 0

Related Questions