Django Introduction Part11 - Deploying Django to production
pip3 install uwsgi #gcc
1 | root@vultr:~# python3 |
DisallowedHost at /
Invalid HTTP_HOST header: ‘45.77.201.180:8000’. You may need to add ‘45.77.201.180’ to ALLOWED_HOSTS.
Request Method: GET
Request URL: http://45.77.201.180:8000/
Django Version: 2.1
Exception Type: DisallowedHost
Exception Value:
Invalid HTTP_HOST header: ‘45.77.201.180:8000’. You may need to add ‘45.77.201.180’ to ALLOWED_HOSTS.
Exception Location: /usr/local/lib/python3.6/dist-packages/django/http/request.py in get_host, line 106
Python Executable: /usr/bin/python3
Python Version: 3.6.5
Python Path:
[’/home/sanring’,
‘/usr/lib/python36.zip’,
‘/usr/lib/python3.6’,
‘/usr/lib/python3.6/lib-dynload’,
‘/usr/local/lib/python3.6/dist-packages’,
‘/usr/lib/python3/dist-packages’]
Server time: Thu, 30 Aug 2018 06:38:20 +0000
修改settings.py这个文件里面的配置文件:
在 ALLOWED_HOSTS = [’’] 里面的中括号里面添加*,如下:
ALLOWED_HOSTS = [’*’]
uwsgi --http :80 --chdir /path/to/project --home=/path/to/env --module project.wsgi
Overview
Once your site is finished (or finished “enough” to start public testing) you’re going to need to host it somewhere more public and accessible than your personal development computer.
Up to now you’ve been working in a development environment, using the Django development web server to share your site to the local browser/network, and running your website with (insecure) development settings that expose debug and other private information. Before you can host a website externally you’re first going to have to:
- Make a few changes to your project settings.
- Choose an environment for hosting the Django app.
- Choose an environment for hosting any static files.
- Set up a production-level infrastructure for serving your website.
What is a production environment?
The production environment is the environment provided by the server computer where you will run your website for external consumption. The environment includes:
- Computer hardware on which the website runs.
- Operating system (e.g. Linux, Windows).
- Programming language runtime and framework libraries on top of which your website is written.
- Web server used to serve pages and other content (e.g. Nginx, Apache).
- Application server that passes “dynamic” requests between your Django website and the webserver.
- Databases on which your website is dependent.
Note: Depending on how your production is configured you might also have a reverse proxy, load balancer, etc.
The server computer could be located on your premises and connected to the Internet by a fast link, but it is far more common to use a computer that is hosted “in the cloud”. What this actually means is that your code is run on some remote computer (or possibly a “virtual” computer) in your hosting company’s data center(s). The remote server will usually offer some guaranteed level of computing resources (e.g. CPU, RAM, storage memory, etc.) and Internet connectivity for a certain price.
This sort of remotely accessible computing/networking hardware is referred to as Infrastructure as a Service (IaaS). Many IaaS vendors provide options to preinstall a particular operating system, onto which you must install the other components of your production environment. Other vendors allow you to select more fully-featured environments, perhaps including a complete Django and web-server setup.
Other hosting providers support Django as part of a Platform as a Service (PaaS) offering. In this sort of hosting you don’t need to worry about most of your production environment (web server, application server, load balancers) as the host platform takes care of those for you (along with most of what you need to do in order to scale your application). That makes deployment quite easy, because you just need to concentrate on your web application and not all the other server infrastructure.
Some developers will choose the increased flexibility provided by IaaS over PaaS, while others will appreciate the reduced maintenance overhead and easier scaling of PaaS. When you’re getting started, setting up your website on a PaaS system is much easier, and so that is what we’ll do in this tutorial.


Choosing a hosting provider
There are well over 100 hosting providers that are known to either actively support or work well with Django (you can find a fairly extensive list at Djangofriendly hosts). These vendors provide different types of environments (IaaS, PaaS), and different levels of computing and network resources at different prices.
Some of the things to consider when choosing a host:
- How busy your site is likely to be and the cost of data and computing resources required to meet that demand.
- Level of support for scaling horizontally (adding more machines) and vertically (upgrading to more powerful machines) and the costs of doing so.
- Where the supplier has data centres, and hence where access is likely to be fastest.
- The host’s historical uptime and downtime performance.
- Tools provided for managing the site — are they easy to use and are they secure (e.g. SFTP vs FTP).
- Inbuilt frameworks for monitoring your server.
- Known limitations. Some hosts will deliberately block certain services (e.g. email). Others offer only a certain number of hours of “live time” in some price tiers, or only offer a small amount of storage.
- Additional benefits. Some providers will offer free domain names and support for SSL certificates that you would otherwise have to pay for.
- Whether the “free” tier you’re relying on expires over time, and whether the cost of mig rating to a more expensive tier means you would have been better off using some other service in the first place!
The good news when you’re starting out is that there are quite a few sites that provide “evaluation”, “developer”, or “hobbyist” computing environments for “free”. These are always fairly resource constrained/limited environments, and you do need to be aware that they may expire after some introductory period. They are however great for testing low traffic sites in a real environment, and can provide an easy migration to paying for more resources when your site gets busier. Popular choices in this category include Heroku, Python Anywhere, Amazon Web Services, Microsoft Azure, etc.
Getting your website ready to publish
Many of the Django project settings (specified in settings.py) should be different for production, either for security or performance reasons.
Tip: It is common to have a separate settings.py file for production, and to import sensitive settings from a separate file or an environment variable. This file should then be protected, even if the rest of the source code is available on a public repository.
The critical settings that you must check are:
-
DEBUG
This should be set as
Falsein production (DEBUG = False). This stops the sensitive/confidential debug trace and variable information from being displayed. -
SECRET_KEY
This is a large random value used for CSRF protection etc. It is important that the key used in production is not in source control or accessible outside the production server. The Django documents suggest that this might best be loaded from an environment variable or read from a serve-only file.
1 | # Read SECRET_KEY from an environment variable |
Let’s change the LocalLibrary application so that we read our SECRET_KEY and DEBUGvariables from environment variables if they are defined, but otherwise use the default values in the configuration file.
Open settings.py, disable the original SECRET_KEY configuration and add the new lines as shown below in bold. During development no environment variable will be specified for the key, so the default value will be used (it shouldn’t matter what key you use here, or if the key “leaks”, because you won’t use it in production).
1 | # SECURITY WARNING: keep the secret key used in production secret! |
Then comment out the existing DEBUG setting and add the new line shown below.
1 | # SECURITY WARNING: don't run with debug turned on in production! |
You can set the environment variable to False by issuing the following command:
1 | export DJANGO_DEBUG=False |
we can also use decouple to simplify this.
1 | pip install python-decouple |
1 | from decouple import config |
Heroku
This section provides a practical demonstration of how to install on the Heroku PaaS cloud.
Why Heroku?
Heroku is one of the longest running and popular cloud-based PaaS services. It originally supported only Ruby apps, but now can be used to host apps from many programming environments, including Django!
We are choosing to use Heroku for several reasons:
- Heroku has a free tier that is really free (albeit with some limitations).
- As a PaaS, Heroku takes care of a lot of the web infrastructure for us. This makes it much easier to get started, because you don’t worry about servers, load balancers, reverse proxies, or any of the other web infrastructure that Heroku provides for us under the hood.
- While it does have some limitations these will not affect this particular application. For example:
- Heroku provides only short-lived storage so user-uploaded files cannot safely be stored on Heroku itself.
- The free tier will sleep an inactive web app if there are no requests within a half hour period. The site may then take several seconds to respond when it is woken up.
- The free tier limits the time that your site is running to a certain amount of hours every month (not including the time that the site is “asleep”). This is fine for a low use/demonstration site, but will not be suitable if 100% uptime is required.
- Other limitations are listed in Limits (Heroku docs).
- Mostly it just works, and if you end up loving it, scaling your app is very easy.
While Heroku is perfect for hosting this demonstration it may not be perfect for your real website. Heroku makes things easy to set up and scale, at the cost of being less flexible, and potentially a lot more expensive once you get out of the free tier.
How does Heroku work?
Heroku runs Django websites within one or more “Dynos”, which are isolated, virtualized Unix containers that provide the environment required to run an application. The dynos are completely isolated and have an ephemeral file system (a short-lived file system that is cleaned/emptied every time the dyno restarts). The only thing that dynos share by default are application configuration variables. Heroku internally uses a load balancer to distribute web traffic to all “web” dynos. Since nothing is shared between them, Heroku can scale an app horizontally simply by adding more dynos (though of course you may also need to scale your database to accept additional connections).
Because the file system is ephemeral you can’t install services required by your application directly (e.g. databases, queues, caching systems, storage, email services, etc). Instead Heroku web applications use backing services provided as independent “add-ons” by Heroku or 3rd parties. Once attached to your web application, the dynos access the services using information contained in application configuration variables.
In order to execute your application Heroku needs to be able to set up the appropriate environment and dependencies, and also understand how it is launched. For Django apps we provide this information in a number of text files:
- runtime.txt: the programming language and version to use.
- requirements.txt: the Python component dependencies, including Django.
- Procfile: A list of processes to be executed to start the web application. For Django this will usually be the Gunicorn web application server (with a
.wsgiscript). - wsgi.py: WSGI configuration to call our Django application in the Heroku environment.
Developers interact with Heroku using a special client app/terminal, which is much like a Unix bash script. This allows you to upload code that is stored in a git repository, inspect the running processes, see logs, set configuration variables and much more!
In order to get our application to work on Heroku we’ll need to put our Django web application into a git repository, add the files above, integrate with a database add-on, and make changes to properly handle static files.
Once we’ve done all that we can set up a Heroku account, get the Heroku client, and use it to install our website.
Create the app for Heroku
Procfile
Create the file Procfile (no extension) in the root of your GitHub repository to declare the application’s process types and entry points. Copy the following text into it:
1 | web: gunicorn movie.wsgi --log-file - |
The “web:” tells Heroku that this is a web dyno and can be sent HTTP traffic. The process to start in this dyno is gunicorn, which is a popular web application server that Heroku recommends.
Gunicorn
Gunicorn is the recommended HTTP server for use with Django on Heroku (as referenced in the Procfile above). It is a pure-Python HTTP server for WSGI applications that can run multiple Python concurrent processes within a single dyno.
While we won’t need it serve our application during development, we’ll install it so that it becomes part of our requirements for Heroku to set up on the remote server.
Install Gunicorn locally on the command line using pip:
1 | pip3 install gunicorn |
Database configuration
We can’t use the default SQLite database on Heroku because it is file-based, and it would be deleted from the ephemeral file system every time the application restarts (typically once a day, and every time the application or its configuration variables are changed).
The Heroku mechanism for handling this situation is to use a database add-on and configure the web application using information from an environment configuration variable, set by the add-on. There are quite a lot of database options, but we’ll use the hobby tier of the Heroku postgres database as this is free, supported by Django, and automatically added to our new Heroku apps when using the free hobby dyno plan tier.
The database connection information is supplied to the web dyno using a configuration variable named DATABASE_URL. Rather than hard-coding this information into Django, Heroku recommends that developers use the dj-database-url package to parse the DATABASE_URLenvironment variable and automatically convert it to Django’s desired configuration format. In addition to installing the dj-database-url package we’ll also need to install psycopg2, as Django needs this to interact with Postgres databases.
dj-database-url (Django database configuration from environment variable)
Install dj-database-url locally for Heroku to set up on the remote server:
1 | $ pip3 install dj-database-url |
Open settings.py and copy the following configuration into the bottom of the file:
1 | # Heroku: Update database configuration from $DATABASE_URL. |
Note:
- We’ll still be using SQLite during development because the
DATABASE_URLenvironment variable will not be set on our development computer. - The value
conn_max_age=500makes the connection persistent, which is far more efficient than recreating the connection on every request cycle. However, this is optional and can be removed if needed.
psycopg2 (Python Postgres database support)
Django needs psycopg2 to work with Postgres databases and you will need to add this to the requirements.txt for Heroku to set this up on the remote server.
Django will use our SQLite database locally by default, because the DATABASE_URLenvironment variable isn’t set in our local environment. If you want to switch to Postgres completely and use our Heroku free tier database for both development and production then you can. For example, to install psycopg2 and its dependencies locally on a Linux-based system you would use the following bash/terminal commands:
1 | sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib |
Installation instructions for the other platforms can be found on the psycopg2 website here.
However, you don’t need to do this — you don’t need PostgreSQL active on the local computer, as long as you give it to Heroku as a requirement, in requirements.txt (see below).
Serving static files in production
During development we used Django and the Django development web server to serve our static files (CSS, JavaScript, etc.). In a production environment we instead typically serve static files from a content delivery network (CDN) or the web server.
Note: Serving static files via Django/web application is inefficient because the requests have to pass through unnecessary additional code (Django) rather than being handled directly by the web server or a completely separate CDN. While this doesn’t matter for local use during development, it would have a significant performance impact if we were to use the same approach in production.
To make it easy to host static files separately from the Django web application, Django provides the collectstatic tool to collect these files for deployment (there is a settings variable that defines where the files should be collected when collectstatic is run). Django templates refer to the hosting location of the static files relative to a settings variable (STATIC_URL), so that this can be changed if the static files are moved to another host/server.
The relevant setting variables are:
STATIC_URL: This is the base URL location from which static files will be served, for example on a CDN.STATIC_ROOT: This is the absolute path to a directory where Django’s “collectstatic” tool will gather any static files referenced in our templates. Once collected, these can then be uploaded as a group to wherever the files are to be hosted.STATICFILES_DIRS: This lists additional directories that Django’s collectstatic tool should search for static files.
Whitenoise
There are many ways to serve static files in production (we saw the relevant Django settings in the previous sections). Heroku recommends using the WhiteNoise project for serving of static assets directly from Gunicorn in production.
Note: Heroku automatically calls collectstatic and prepares your static files for use by WhiteNoise after it uploads your application. Check out WhiteNoise documentation for an explanation of how it works and why the implementation is a relatively efficient method for serving these files.
The steps to set up WhiteNoise to use with the project are given here :
WhiteNoise
Install whitenoise locally using the following command:
1 | $ pip3 install whitenoise |
To install WhiteNoise into your Django application, open settings.py, find the MIDDLEWARE setting and add the WhiteNoiseMiddleware near the top of the list, just below the SecurityMiddleware:
1 | MIDDLEWARE = [ |
Optionally, you can reduce the size of the static files when they are served (this is more efficient). Just add the following to the bottom of settings.py:
1 | # Simplified static file serving. |
Requirements & Runtime
The Python requirements of your web application must be stored in a file requirements.txt in the root of your repository. Heroku will then install these automatically when it rebuilds your environment. You can create this file using pip on the command line (run the following in the repo root):
1 | pip3 freeze > requirements.txt |
After installing all the different dependencies above, your requirements.txt file should have at least these items listed (though the version numbers may be different). Please delete any other dependencies not listed below, unless you’ve explicitly added them for this application.
1 | dj-database-url |
1 | -r requirements-dev.txt |
1 | dj-database-url |
Make sure that a psycopg2 line like the one above is present! Even if you didn’t install this locally then you should still add this to the requirements.txt.
The runtime.txt file, if defined, tells Heroku which programming language to use. Create the file in the root of the repo and add the following text:
1 | python-3.7.6 |
Note: Heroku only supports a small number of Python runtimes (at time of writing, this includes the one above). Heroku will use a supported runtime irrespective of the value specified in this file.
Save changes to Github and re-test
Next lets save all our changes to Github. In the terminal (whilst inside our repository), enter the following commands:
1 | git add -A |
Before we proceed, lets test the site again locally and make sure it wasn’t affected by any of our changes above. Run the development web server as usual and then check the site still works as you expect on your browser.
1 | python3 manage.py runserver |
We should now be ready to start deploying LocalLibrary on Heroku.
Create and upload the website
To create the app we run the “create” command in the root directory of our repository. This creates a git remote (“pointer to a remote repository”) named heroku in our local git environment.
1 | heroku create |
Note: You can name the remote if you like by specifying a value after “create”. If you don’t then you’ll get a random name. The name is used in the default URL.
We can then push our app to the Heroku repository as shown below. This will upload the app, package it in a dyno, run collectstatic, and start the site.
1 | git push heroku master |
If we’re lucky, the app is now “running” on the site, but it won’t be working properly because we haven’t set up the database tables for use by our application. To do this we need to use the heroku run command and start a “one off dyno” to perform a migrate operation. Enter the following command in your terminal:
1 | heroku run python manage.py migrate |
We’re also going to need to be able to add books and authors, so lets also create our administration superuser, again using a one-off dyno:
1 | heroku run python manage.py createsuperuser |
Once this is complete, we can look at the site. It should work, although it won’t have any books in it yet. To open your browser to the new website, use the command:
1 | heroku open |
Managing addons
You can check out the add-ons to your app using the heroku addons command. This will list all addons, and their price tier and state.
1 | > heroku addons |
Here we see that we have just one add-on, the postgres SQL database. This is free, and was created automatically when we created the app. You can open a web page to examine the database add-on (or any other add-on) in more detail using the following command:
1 | heroku addons:open heroku-postgresql |
Other commands allow you to create, destroy, upgrade and downgrade addons (using a similar syntax to opening). For more information see Managing Add-ons (Heroku docs).
Setting configuration variables
You can check out the configuration variables for the site using the heroku config command. Below you can see that we have just one variable, the DATABASE_URL used to configure our database.
1 | > heroku config |
If you recall from the section on getting the website ready to publish, we have to set environment variables for DJANGO_SECRET_KEY and DJANGO_DEBUG. Let’s do this now.
Note: The secret key needs to be really secret! One way to generate a new key is to use the Django Secret Key Generator.
We set DJANGO_SECRET_KEY using the config:set command (as shown below). Remember to use your own secret key!
1 | > heroku config:set DJANGO_SECRET_KEY='eu09(ilk6@4sfdofb=b_2ht@vad*$ehh9-)3u_83+y%(+phh&=' |
We similarly set DJANGO_DEBUG:
1 | > heroku config:set DJANGO_DEBUG= |
If you visit the site now you’ll get a “Bad request” error, because the ALLOWED_HOSTSsetting is required if you have DEBUG=False (as a security measure). Open /locallibrary/settings.py and change the ALLOWED_HOSTS setting to include your base app url (e.g. ‘locallibrary1234.herokuapp.com’) and the URL you normally use on your local development server.
1 | ALLOWED_HOSTS = ['<your app URL without the https:// prefix>.herokuapp.com','127.0.0.1'] |
Then save your settings and commit them to your Github repo and to Heroku:
1 | git add -A |
After the site update to Heroku completes, enter an URL that does not exist (e.g. /catalog/doesnotexist/). Previously this would have displayed a detailed debug page, but now you should just see a simple “Not Found” page.
Debugging
The Heroku client provides a few tools for debugging:
1 | # Show current logs |
If you need more information than these can provide you will need to start looking into Django Logging.
REFERENCES
-
https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
-
Deploying static files (Django docs)
- How to deploy with WSGI (Django docs)
-
How to use Django with Apache and mod_wsgi (Django docs)
- How to use Django with Gunicorn (Django docs)
-
Heroku
- How Heroku works
- Configuring Django apps for Heroku (Heroku docs)
- Getting Started on Heroku with Django (Heroku docs)
- Django and Static Assets (Heroku docs)
- Concurrency and Database Connections in Django (Heroku docs)
- How Heroku works (Heroku docs)
- Dynos and the Dyno Manager (Heroku docs)
- Configuration and Config Vars (Heroku docs)
- Limits (Heroku docs)
- Deploying Python applications with Gunicorn (Heroku docs)
- Deploying Python and Django apps on Heroku (Heroku docs)
-
Digital Ocean






