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:

  • Docker network does not work with bash entrypoint
  • Is there a way to specify a suggested tag name inside a Dockerfile?
  • Dockerfile Overriding ENV variable
  • Load Balance Web Applications on Windows Docker
  • error during connect: … http: server gave HTTP response to HTTPS client on any docker command with remote host
  • Fail pod on container failure
  • 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?

  • Unable to start node app with shell script
  • Gitlab CI: mount Apache service Docker DocumentRoot directory into main Docker
  • Google container registry golang moby authentication
  • docker cp doesn't work for this mysql container
  • denied: requested access to the resource is denied : docker
  • docker swarm create fails when tar can't find container file system
  • 2 Solutions collect form web for “How does docker-compose link work?”

    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) {
    
    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.