每个在docker-compose文件中的服务可以拥有自己的Mongo实例吗?

huangapple go评论81阅读模式
英文:

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

问题

在这种情况下,我有两个服务及其各自的数据库。运行此docker-compose文件完美无缺,两个mongodb实例分别运行在它们的端口上:两个mongodb实例

问题出在其中一个服务通过mongoose连接mongodb时,例如下面是authentication服务连接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

最后是mongoose的连接器:

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


// 设置Mongoose连接事件监听器
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); // 如果连接到数据库时出现错误,退出进程
});

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

// 连接到MongoDB
mongoose.connect(connectionString);

module.exports = db;

单独运行每个服务都完全正常,但合并后会导致端口阻塞或其他我看不到或找不到的问题。请帮忙解决。

尝试使用docker命令的expose选项来修复端口问题,或者插入mongo命令以使其监听不同的端口,但都没有成功。

英文:

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

答案1

得分: 0

我的解决方案来自于在构建时建立了一个更好的依赖关系。允许次要的Mongo镜像在构建之前等待前一个数据库解决了我的问题。在docker-desktop中先运行第一个数据库,然后运行服务,允许它们连接,然后为第二个数据库和服务重复这个过程。这个方法非常有效,所以请使用depends_on 每个在docker-compose文件中的服务可以拥有自己的Mongo实例吗?

英文:

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 每个在docker-compose文件中的服务可以拥有自己的Mongo实例吗?

huangapple
  • 本文由 发表于 2023年6月13日 01:14:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定