Search code examples
djangodockermulti-tenantdocker-network

Communication between two docker containers based on multi-tenant architecture


I have two django projects (mircroservices), running in separate docker containers. Both projects are using django-tenant-schemas. How can I send a request from serice-bar to service-foo on url http://boohoo.site.com:18150/api/me/, 18150 is the PORT of project-a? I need to use the tenant url so that project-a can verify the tenant and process the request.

I can send a request by using the container name, but that doesn't work because if I use http://site.foo:18150/api/me, it sends the request successfully, but there's no tenant with definition site.foo.

Here's the docker-compose.yml:

version: '3.3'

services:
  db:
    container_name: site.postgres
    image: postgres
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres

  foo:
    container_name: site.foo
    build:
      context: ../poll
    command: python /app/foo/src/manage.py runserver 0.0.0.0:18150
    depends_on:
      - db
    environment:
      - DB_HOST=site.postgres
      - DJANGO_SETTINGS_MODULE=main.settings.dev
    stdin_open: true
    tty: true
    ports:
      - "18150:18150"

  bar:
    container_name: site.bar
    build:
      context: ../toll
    command: python /app/bar/src/manage.py runserver 0.0.0.0:18381
    depends_on:
      - db
    environment:
      - DB_HOST=site.postgres
      - DJANGO_SETTINGS_MODULE=main.settings.dev
    stdin_open: true
    tty: true
    ports:
      - "18381:18381"


Solution

  • You can do this using aliases on the default (or any other...) network. For more info on this feature, see the documentation. I checked and this is supported by your current compose file version (3.3) although I do suggest you move up to the latest supported one if possible (3.7).

    For compactness, I'm only reproducing the modified foo service declaration below where I only added the necessary networks stanza.

      foo:
        container_name: site.foo
        build:
          context: ../poll
        command: python /app/foo/src/manage.py runserver 0.0.0.0:18150
        depends_on:
          - db
        environment:
          - DB_HOST=site.postgres
          - DJANGO_SETTINGS_MODULE=main.settings.dev
        networks:
          default:
            aliases:
              - boohoo.site.com
        stdin_open: true
        tty: true
        ports:
          - "18150:18150"
    

    After this change, your foo service container will be reachable from any other container on the same network either with foo (the service name), site.foo (your custom container name) or boohoo.site.com (the network alias).