Fix: Django’s Debug Toolbar not Showing Inside Docker

Context

When developing Django web applications, one of the most popular ways to debug the performance of database queries, the values of internal variables or other custom metrics is the django-debug-toolbar.

To integrate the toolbar into a Django web application, one first needs to configure a list of internal IP addresses. Only if the IP address of the web browser accessing the web application is part of this list, the toolbar will be shown. Otherwise, the toolbar is hidden (even though it is installed and included).

Problem Description

However, when developing inside a Docker container, the internal IP regularly changes and it is tedious to update the configuration all the time.

This article describes an alternative way where the current host IP is added to the INTERNAL_IPS list dynamically.

Solution Approach

Basically, the idea is to generate the INTERNAL_IPS list based on the internal IP of the host. We start with the static list containing only localhost (127.0.0.1) and then add to this list the current host’s IP. Add this code to the config/settings.py:

INTERNAL_IPS = ['127.0.0.1']

import socket
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips]

socket.gethostname() will be equal to the Docker container’s ID. The call to socket.gethostbyname_ex() will then reveal the container’s IP address. For example, in my current setup: 172.20.0.3. Finally, we add an entry to the list INTERNAL_IPS. However, we do not add the container’s IP itself but rather the container’s IP with the last octet replaced with 1. In my case, 172.20.0.1. By convention, this is the internal IP of the host itself. And just in case the container has multiple IP addresses, this transformation is performed for all of them.

References

The presented code was originally published by the cookiecutter-django project under the BSD-3 clause.

The general problem of the toolbar’s inability to cope with dynamic internal IP addresses was already discussed in this StackOverflow thread.