How to connect to named networks in docker-compose

Posted on so:

I have an app that relies on 4 backend servers (redis, mongo, graphql-websockets-subscriptions, and graphql-http) and one front end

Not configuring networks, I am able to connect my different servers while I’m in the same container, but I cannot access the mongodb database from the front-end compose-container with the url: mongodb://weallyback_default:27017/weally

When I execute docker network ls on the backend container, I get:

D:\Zied\work\WeAllyBack>docker network ls
NETWORK ID     NAME                 DRIVER    SCOPE
71d1c5f23159   bridge               bridge    local
cd980f642e7b   host                 host      local
4a50359ad823   none                 null      local
ecec643b2a2e   weallyback_default   bridge    local

This is my front-end compose config

version: "3.8"

services:
  next_server:
    image: node:14.17.3-alpine
    volumes:
      - type: bind
        source: ./
        target: /front
      - type: volume
        source: nodemodules # name of the volume, see below
        target: /front/node_modules
        volume:
          nocopy: true
    working_dir: /front
    command: yarn dev
    ports:
      - "3000:3000"
    networks:
      - weallyback_default
    environment:
      - NODE_ENV=development
      - PORT=3000

volumes:
  nodemodules:

networks:
  weallyback_default:
    external: true

I tried to name my networks, but it made things even worse (described in the SO post)

May I suggest to actualy create the weallyback network with docker network create --attachable weallyback outside of your docker-compose deployment.

Then declare it like this in your compose files:

services:
  service-a:
    networks:
      weallyback: {}
    ..
networks:
  weallyback:
     external: true
...

Or if you want to stick with letting your main stack to create the network, at least declare the network with a static name (which does not depend on --project-name, which defaults to the current folder of the docker-compose.yml):

services:
  service-a:
    networks:
      default: {}

networks:
  default:
    name: weallyback
....

Hi Metin,

Thanks for your answer, I’m new to docker and dcompose, I think I didn’t understand your proposal since I copy-pasted the syntax

networks:
      weallyback: {}

and it gives me the error:

‘.\docker-compose.yml’ is invalid because:
services.graphql_pubsub_server.networks contains {“weallyback”: {}}, which is an invalid type, it should be a string

networks can be either yaml sequences or maps. I used the map Sytax, as it allows to use additional attributes if required.

If you share you whole compose file (wrappend in a code block), we can sort out where things go wrong.