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

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

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

问题

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

问题出在其中一个服务通过mongoose连接mongodb时,例如下面是authentication服务连接authenticationdatabase时的错误信息:

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

最后是mongoose的连接器:

  1. const mongoose = require('mongoose');
  2. const connectionString = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_NAME}:${process.env.DB_PORT}`;
  3. // 设置Mongoose连接事件监听器
  4. const db = mongoose.connection;
  5. mongoose.set('strictQuery', false)
  6. db.set('strictQuery', false);
  7. db.on('connecting', () => {
  8. console.log('Connecting to MongoDB...');
  9. });
  10. db.on('connected', () => {
  11. console.log('Connected to MongoDB');
  12. });
  13. db.on('error', (error) => {
  14. console.error('Error connecting to MongoDB:', error);
  15. process.exit(1); // 如果连接到数据库时出现错误,退出进程
  16. });
  17. db.on('disconnected', () => {
  18. console.log('Disconnected from MongoDB');
  19. });
  20. // 连接到MongoDB
  21. mongoose.connect(connectionString);
  22. module.exports = db;

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

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

英文:

In this case I have two services and their respective database

  1. version: '3.8'
  2. services:
  3. authentication:
  4. build:
  5. context: ./authentication
  6. dockerfile: dockerfile
  7. environment:
  8. PORT: 3001
  9. DB_PORT: 27017
  10. DB_NAME: authenticationdatabase
  11. DB_USER: username
  12. DB_PASSWORD: password
  13. SIGNATURE_KEY: DITMOETGEINJECTEERDWORDEN
  14. volumes:
  15. - ./authentication:/authentication
  16. ports:
  17. - 3001:3001
  18. authenticationdatabase:
  19. image: mongo:latest
  20. environment:
  21. - MONGO_INITDB_DATABASE=authenticationdatabase
  22. - MONGO_INITDB_ROOT_USERNAME=username
  23. - MONGO_INITDB_ROOT_PASSWORD=password
  24. ports:
  25. - 27017:27017
  26. restart: always
  27. volumes:
  28. - authentication_db_volume:/data/authentication
  29. hosting:
  30. build:
  31. context: ./hosting
  32. dockerfile: dockerfile
  33. environment:
  34. PORT: 3002
  35. DB_PORT: 27017
  36. DB_NAME: hostingdb
  37. DB_USER: username
  38. DB_PASSWORD: password
  39. CLOUDINARY_URL: ${CLOUDINARY_URL}
  40. JWT_SIGNATURE_KEY: DITMOETGEINJECTEERDWORDEN
  41. volumes:
  42. - ./hosting:/hosting
  43. ports:
  44. - 3002:3002
  45. restart: always
  46. depends_on:
  47. - hostingdb
  48. hostingdb:
  49. image: mongo:latest
  50. environment:
  51. - MONGO_INITDB_DATABASE=hostingdb
  52. - MONGO_INITDB_ROOT_USERNAME=username
  53. - MONGO_INITDB_ROOT_PASSWORD=password
  54. ports:
  55. - 27018:27017
  56. restart: always
  57. volumes:
  58. - hostingdb_volume:/data/hosting
  59. volumes:
  60. authentication_db_volume:
  61. 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:

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

And finally here is the connector for mongoose:

  1. const mongoose = require('mongoose');
  2. const connectionString = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_NAME}:${process.env.DB_PORT}`;
  3. // Set up Mongoose connection event listeners
  4. const db = mongoose.connection;
  5. mongoose.set('strictQuery', false)
  6. db.set('strictQuery', false);
  7. db.on('connecting', () => {
  8. console.log('Connecting to MongoDB...');
  9. });
  10. db.on('connected', () => {
  11. console.log('Connected to MongoDB');
  12. });
  13. db.on('error', (error) => {
  14. console.error('Error connecting to MongoDB:', error);
  15. process.exit(1); // Exit the process if there is an error connecting to the database
  16. });
  17. db.on('disconnected', () => {
  18. console.log('Disconnected from MongoDB');
  19. });
  20. // Connect to MongoDB
  21. mongoose.connect(connectionString);
  22. 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:

确定