I pulled and am using the docker instance of MongoDB:
version: "3.4"
services:
client:
image: myApp:1.0
ports:
- "9001:4200"
server:
image: myServer:1.0
ports:
- "3000:3000"
links:
- database
database:
image: mongo
volumes:
- "/data/db:/data/db"
ports:
- "27017:27017"
In my Server code, I connect using:
const port = process.env.PORT || 3000;
const databaseURL = process.env.DATABASE_URL || 'mongodb://127.0.0.1:27017';
const server = http.createServer(app);
server.listen(port);
server.on('listening', async () => {
console.info('Server is listening...');
try {
await MongoHelper.connect(databaseURL);
console.info('Connected to MongoDB');
} catch (err) {
console.error(err);
}
});
Running my server locally, it connects to the MongoDB just fine. However, when running my container, I get:
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at Timeout._onTimeout (/usr/src/app/node_modules/mongodb/lib/core/sdam/topology.js:430:30)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map { '127.0.0.1:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
Any help would be greatly appreciated.
You can't directly access mongodb with the address 127.0.0.1:27017
. The database service will only be accessible with the resolution name database
, the same name as the service.
So the connection string should be 'mongodb://database:27017'
. You could define another alias if you want with:
links
- "database:database_alias"
environment:
- DATABASE_URL="mongodb://database_alias:27017"
There are more details here .
Each container can now look up the hostname web or db and get back the appropriate container's IP address. For example, web's application code could connect to the URL postgres://db:5432 and start using the Postgres database.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.