A Guide to Safely Exposing Django Development Apps

Django‘s development server runs locally, preventing sharing apps for testing. Deploying to staging can feel wasteful for temporary needs. Tools like ngrok expose Django apps locally by tunneling to unique public URLs.

This guides you through concepts, tools and techniques for publicly accessing Django apps with ngrok tunnels. We‘ll build a demo app, expose it securely with ngrok, and explore various options for developing, testing and sharing Django projects safely.

The Need for Accessible Demo Django Environments

Django includes a handy built-in development server for rapid prototyping. But running locally on port 8000 limits sharing your apps for:

  • Demoing to clients and stakeholders
  • External user testing and feedback
  • Collaborating with remote teammates
  • Showing work at conferences or meetings

Full hosting and infrastructure adds overhead just for temporary visibility. Instead, ngrok creates secure tunnels from the public internet to your local port 8000. This makes Django projects externally accessible for demos without deployment.

Preparing Prerequisites

To apply ngrok effectively with Django, some baseline experience helps:

Python and Virtual Environments – Have Python 3.6+ installed. Know concepts like virtual environments and package management with pip.

Django Framework – Install Django and understand projects, apps, views and using the runserver command.

Networking Concepts – Be familiar with localhost, ports, HTTP and accessing computers over the network.

ngrok Installation – Download and install ngrok client on your operating system from ngrok.com. Test it runs with ngrok help.

With those foundations, we can demonstrate exposing a disposable Django test app.

Building a Disposable Django Demo App

To experiment safely, we‘ll build an ephemeral Django project:

# Create and activate virtual env 

$ python3 -m venv testenv
$ source testenv/bin/activate

# Install Django 

$ pip install django

# Create project and app
$ django-admin startproject demo
$ cd demo
$ python manage.py startapp testapp

# Add view
# demo/testapp/views.py
from django.http import HttpResponse

def test(request):
    return HttpResponse("Hello world") 

# Set url
# demo/testapp/urls.py
from django.urls import path 
from .views import test

urlpatterns = [
    path(‘‘, test, name=‘test‘)

# Run development server
$ python manage.py runserver

This disposable app prints "Hello world" when accessed. Now we‘ll use ngrok to publicly expose it.

Accessing Local Django Sites with ngrok Tunnels

The ngrok client creates secure tunnels from a public endpoint to a local port and host. To expose our Django test app running on the default port 8000, we tell ngrok:

ngrok http 8000

ngrok generates a unique URL like http://80396a32.ngrok.io/ that tunnels externally to our internal port 8000.

However, visiting this URL yields a Django 400 "Bad Request" error:

Invalid HTTP_HOST header: ‘80396a32.ngrok.io’. You may need to add  
‘80396a32.ngrok.io’ to ALLOWED_HOSTS.

Django includes security restricting accessible hosts. We must update settings:

# demo/settings.py

ALLOWED_HOSTS = [‘localhost‘, ‘‘]

# Update to:

This allows all hosts temporarily. We can now connect successfully!

While easy for demos, allowing all hosts lowers security. Next we‘ll explore better practices.

Securing Django Apps Exposed Publicly

Opening access for sharing also invites abuse if applications run in production environments:

  • Attackers can steal or corrupt customer data
  • API keys and credentials may leak
  • Vulnerabilities open doors for more critical exploits

Use ngrok tunnels only briefly with non-sensitive apps. For internal environments, we recommend:

  • Enable user login and restrict unauthorized data access
  • Never expose production credentials
  • Run newer Django versions with latest security patches

For staging or production systems, further harden apps:

  • Whitelist specific allowed hosts
  • Mandate HTTPS and enable HSTS
  • Configure CORS cross-origin restrictions
  • Implement security middleware and headers
  • Maintain DNS correctly pointing only to site
  • Utilize a cloud WAF like Cloudflare

Continually reassess exposures and have a plan to disable access.

Customizing and Automating ngrok Tunnels

Basic ngrok usage works for quick demos. For more control, explore:

Subdomains – Generate preset subdomains like demo.ngrok.io for prettier, professional URLs.

Saved Configs – Store tunnel definitions in YAML files instead of ephemeral commands.

Inspection – Inspect HTTP traffic and metadata through ngrok‘s web interface.

Integration – Couple ngrok with Nginx as a reverse proxy for added flexibility.

Automation – Script ngrok invoking and teardown to limit exposure windows.

Routing – Segment app areas by path with local proxies.

Carefully consider each enhancement regarding complexity and security.

Alternative Approaches to Publicly Hosting Django

While fantastic for temporary testing, services like PythonAnywhere better suit staging applications. Compare approaches:

Low-Code SaaS – Services like Heroku emphasize convenience over control. Handy for early prototyping.

Shared Hosting – Traditional web hosts work well for ongoing hosting with Django support.

Cloud PaaS – Platforms like AWS Elastic Beanstalk and Azure App Service excel at scaling.

Containers – Docker containers manage dependencies reliably across environments. Orchestrators like Kubernetes facilitate container deployments.

Serverless – "Backend-as-a-Service" platforms like AWS Lambda executions scale automatically.

Evaluate options beyond basic tunnels for more robust hosting strategies.

Carefully Balancing Accessibility and Security

Django‘s development server runs locally by default, preventing access for testing and demos. While secure, this limits sharing your applications.

Exposing apps risks attack vectors and unintended access without proper precautions. ngrok opens local servers to the public internet with tunnels. For disposable test apps, this quickly enables demos after updating Django‘s host security.

However be extremely wary of using tunnels with production systems. Temporary holes opened for convenience can lead to credential leaks, data theft and serious vulnerabilities. Only utilize ngrok briefly with non-sensitive apps after hardening configurations securely.

For more robust hosting needs, shift focus onto staging providers, cloud platforms or containerized solutions. Evaluate each technology by weighingaccessibility against security considerations.

Plan ahead before developing with Django to ensure you can share applications safely when needed. But resist taking shortcuts that could endanger customer data or leak sensitive credentials. With mindfulness toward security, ngrok and Django together help developers collaborate by quickly testing ideas publicly.