How to setup dynamically , without compose, multiple django docker containers with postgres containers for each domain on the fly

How does one deal with creating multiple django docker containers and their related postgresql docker containers for N domains.

I have a local dnsserver to mimic production and i setup allow *.test.com and test.com to point to my 127.0.0.1

I have created a docker network bridge for all the docker containers running under this project so that I can reach them by name of the docker.

So when a client/tenant register for a system, say company "mycomp", I create a django docker container called mycomp_web, it is reachable at mycomp.test.com, Ngnix parses the domain and maps the revers_proxy to find mycomp_web django container. This works well. But now I need to switch from sqlite to postgresql. So i need to also create a postgresql container for each domain. So it would be something like mycomp_db.

Now the real question is ? how do I point my django instance to the right postgres container (using name of that container). Up until know I was using docker names to find the containers.

How would you set the database entry in the settings.py of django

'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'erp', 
        'USER': 'erp_user',
        'PASSWORD': '123',
        'HOST': '127.0.0.1', 
        'PORT': '5432',
    }

How would one change HOST and PORT to find the postgres docker container that matches to that domain?

So if I register a new domain like mycomp2, I ll will have mycomp2_web (django container and mycomp2_db(postgresql container) and django container will be able to find the postgres container that belongs to that domain.

I hope this makes sense.

Thanks

As Richard pointed out in the comments you should simply use the container name of the respective postgres container as the hostname in the settings.py, i.e., for mycomp2_web:

'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'erp', 
        'USER': 'erp_user',
        'PASSWORD': '123',
        'HOST': 'mycomp2_db', 
        'PORT': '5432',
    }

mycomp2_db will by resolved to the postgres containers internal IP address by the internal docker DNS. On that IP address the postgres process will be listening on always to same port - so no need to change this dynamically.


What you were trying instead according to your comment was to always expose the port of the database containers to the host - which for multiple hosts would require different randomly assigned ports. But you don't need to expose the ports to the host in the first place and can rather just use the internal IP address of the container instead - which can also be easily resolved by just using the container host name as described above.

Back to Top