Django-debug-toolbar: Wrong IP when multiple networks in Docker

Created on 13 Apr 2018  ·  5Comments  ·  Source: jazzband/django-debug-toolbar

The solution used in cookiecutter-django does not work when the Django container is connected to multiple networks in Docker. The solution is something like the following (taken from this SO post):

import socket

ip = socket.gethostbyname(socket.gethostname())
INTERNAL_IPS = ['127.0.0.1', ip[:-1] + '1']

My Docker Compose configuration has the following items:

networks:
  web_network: {}
  cache_network: {}
  database_network: {}


services:
  djangoapp:
    networks:
      - database_network
      - web_network
      - cache_network

Now the IP returned by ip = socket.gethostbyname(socket.gethostname()) is not always the same. It seems to be the IP of one of the different available networks (if that makes sense). So sometimes it works, but most of the time it does not.

I ended up adding all the possible IPs based on the one returned by socket, something like:

def internal_docker_ips(base_ip):
    numbers = base_ip.split('.')
    return [
        '.'.join([numbers[0], str(i), numbers[2], str(j)])
        for i in range(1, 254) for j in (1, 3)  # all IPs ending with '.1' and '.3'
    ]

INTERNAL_IPS = [
    '127.0.0.1',
]

INTERNAL_IPS.extend(
    internal_docker_ips(
        socket.gethostbyname(
            socket.gethostname())))

# ['127.0.0.1', '172.1.0.1', '172.1.0.3', '172.2.0.1', '172.2.0.3', ..., '172.253.0.1', '172.253.0.3']

Is there a cleaner workaround for this? Did any of you have the same issue? It might not be related to Django Debug Toolbar itself but any help is appreciated and will I believe be useful for others.

Most helpful comment

This is what I do:

if DEBUG:
    # `debug` is only True in templates if the vistor IP is in INTERNAL_IPS.
    INTERNAL_IPS = type(str('c'), (), {'__contains__': lambda *a: True})()

Simply assign an object which contains all the things to INTERNAL_IPS. Of course never do this on a production host!

All 5 comments

This is what I do:

if DEBUG:
    # `debug` is only True in templates if the vistor IP is in INTERNAL_IPS.
    INTERNAL_IPS = type(str('c'), (), {'__contains__': lambda *a: True})()

Simply assign an object which contains all the things to INTERNAL_IPS. Of course never do this on a production host!

Clever! You should consider adding this answer to the mentioned SO post! I would definitely upvote it :smile:

Seems there is no further interest in this issue, and I got my answer: closing :slightly_smiling_face:

One of my colleagues uses another solution for this: actually django-debug-toolbar provides a configuration setting called SHOW_TOOLBAR_CALLBACK.

DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': lambda request: True,
}

# or

DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': lambda request: True if DEBUG else False,
}
Was this page helpful?
0 / 5 - 0 ratings