Jim
Jim

Reputation: 669

How can i link mongodb with other services in docker-compose?

i got a problem. I made a docker-compose that runs mongo and node.

The problem is there is no way i use mongo from the container, i cannot start my node server.

Here there is my docker-compose :

 version: '3'
services:
  database:
    build: ./Database
    container_name: "dashboard_database"
    ports:
      - "27017:27017"
  backend:
    build: ./Backend
    container_name: "dashboard_backend"
    ports:
      - "8080:8080"
    depends_on:
      - database
    links:
      - database

But when i start mongo without the container my node can reach it, i don't know why ...

Any idea ?

Thanks !

Upvotes: 0

Views: 1014

Answers (2)

Bilal Ali Jafri
Bilal Ali Jafri

Reputation: 1006

Dont define ports in the DB service. But afterwards only application will be able to access DB. Most probably it will work then. If you still want to access it from your PC then you should define a network. Try this

 version: '3'
services:
  database:
    build: ./Database
    container_name: "dashboard_database"
  backend:
    build: ./Backend
    container_name: "dashboard_backend"
    ports:
      - "8080:8080"
    depends_on:
      - database
    links:
      - database

And for creating network

version: '3'

networks:
  back-tier:

services:
  database:
    build: ./Database
    container_name: "dashboard_database"
    networks:
      - back-tier
    ports:
      - "27017:27017"
  backend:
    build: ./Backend
    container_name: "dashboard_backend"
    networks:
      - back-tier
    ports:
      - "8080:8080"
    depends_on:
      - database

Upvotes: 1

Thomas Herzog
Thomas Herzog

Reputation: 506

All services in docker-compose are within the docker-compose created network, and can be addressed by their service names from other services. In your case the service names are database and backend, so for instance the database can be accessed by the backend with something like tcp://database:27017. You don't need to link them anymore.

https://runnable.com/docker/docker-compose-networking

Be aware depends_on only waits until the process has been started and does not wait for the process to be ready to accept connections.

https://docs.docker.com/compose/compose-file/#depends_on https://docs.docker.com/compose/startup-order

The port mappings are only necessary if you want to make a service accessible from the local machine. In your examplte the backend service is accessible via localhost:8080.

If you want an external container to access a docker-compose service tne localhost:8080 wont work because localhost in the container isn't the same localhost as on your local machine where docker containers are running. You can create manually a docker network and connect the container and docker-compose services to it. See docker-compose-networking link and take a look at section Pre-existing Networks.

Does that help you?

Upvotes: 0

Related Questions