简体   繁体   中英

How does docker-compose link work?

I have three containers, web, rest and db. I want rest (nodejs) to be able to access db (mongodb).

My docker-compose.yml:

version: '2'
services:
 web:
  build: front
  depends_on:
   - db
   - rest
 db:
  build: backend/mongodb
  volumes:
   - /src/docker/mongodb:/var/lib/mongodb
  restart: always
 rest:
  build: backend/rest
  restart: always
  links:
    - db:database

In my nodejs program:

MongoClient.connect("mongodb://database:27017/mytest", function (err, db) {
 ...

However, my mongo client can't reach the database and keeps restarting...

What am I doing wrong?

Containers will be reachable by their names. So, in your case, you have to use the name of the db service, which is db :

MongoClient.connect("mongodb://db:27017/mytest", function (err, db) {

Assuming your node.js application is your web service? Web can only access the db service by using the hostname db . However the rest service can access it using db or database because you have given it a link alias.

You can either replicate that links: alias in the web service definition, or change your connect string to use db instead of database .

This should work right now:

MongoClient.connect("mongodb://db:27017/mytest", function (err, ndb) {

Or with the link added:

MongoClient.connect("mongodb://database:27017/mytest", function (err, db) {

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM