First Steps for Deploying a Django App
Key Takeaways
Deploying a Django app using G unicorn, nginx, and setting up a virtual machine on Azure VMS or Amazon ec2, with a focus on security rules, Django project setup, and environment variables for secret keys.
Full Transcript
deploy a Django app with G unicorn and nginx taking a Django app from development to production is a demanding but rewarding process this course will take you through that process step by step providing an in-depth guide that starts at Square One With A No Frills Django application and adds in g-unicorn nginx and domain registration at the end you'll be better equipped to take your Django app into production and serve it to the world in this course you'll learn how you can take your Django app from development to production how you can host your app on a real world public domain and how to introduce G unicorn and nginx into the request and response chain to make the most out of this course you should have an introductory level understanding of python and Django if you need help in either area real python has got you covered with this learning path covering an introduction to python and these tutorials covering Django this course was created using Django 411 although the techniques covered should be very similar for any recent version of the web framework the course involves setting up a cloud virtual machine on a server run by a third party so it should be considered as touching on devops due to the fast-moving nature of cloud hosting you may need to spend time with your chosen Cloud hosts documentation to get the services you need up and running and we would consider this course to be of an intermediate to advanced level because of this however it's well worth persevering with as knowledge of how to host a Django Project online is a useful skill to have also note that the course does not cover setup methods that will persist across reboots of the Cloud Server that you choose if the server is rebooted then some of the steps such as setting environment variables will need to be repeated to get the site back online so now you know what you need and what you'll be covering in this course let's get started Cloud environment and Django setup in this course you'll use Django as the framework at the core of your web app using it for URL routing HTML rendering authentication Administration and back-end logic later on you'll supplement the Django component with two other layers G unicorn and nginx in order to serve the application scalably but before all of that you'll need to set up your environment and get the Django application itself up and running first you'll need to launch and set up a virtual machine or VM on which the web application will run you should familiarize yourself with at least one infrastructure as a service cloud service provider to provision a VM this section will walk you through the processor to high level but won't cover every step in detail using a VM to serve web app is an example of IAS where you have full control over the server software other options beside this do exist such as a serverless architecture which allows you to compose the Django app only and let a separate framework or cloud provider handle the infrastructure side or a containerized approach which allows multiple apps to run independently on their same host operating system for this course though you'll use the tried and true route of serving nginx and Django directly on iaas two popular options for virtual machines are Azure VMS and Amazon ec2 to get more help with launching the instance you should refer to the documentation for your cloud provider for Azure VMS follow that quick start guide for creating a Linux virtual machine in the Azure portal for Amazon ec2 learn how to get set up the Django project and everything else involved in this course sit on a T2 micro Amazon ec2 instance running Ubuntu Server 2204 regardless of Platform One important component of VM setup is inbound security rules these are fine-grained rules that control the inbound traffic to your instance create the inbound rules seen on screen for initial development which you'll modify in production the first role allows TCP over Port 8000 from your personal computers ipv4 address allowing you to send requests to your Django app when you serve it in development on Port 8000. the second rule allows inbound traffic from network interfaces and instances that are assigned to the same Security Group using the security group ID as the source this is a rule included in the default AWS security group that you should tie to your instance the third rule allows you to access your VM via SSH from your personal computer you'll also want to add an outbound rule to allow outbound traffic to do things such as install packages from your local computer you will then be able to SSH into the instance this command logs you into your VM as the user Ubuntu here the first part of the command is the path to the private key this is part of the security credentials that you tied to the VM this provides a much more secure method of access than using a username and password with this part of the setup complete in the next section of the course you'll take a look at creating a basic Django app and some setup techniques that are useful when running a site on a Cloud Server creating a cookie cutter Django app you're not concerned with making a fancy Django project with complex URL routing or Advanced database features for this course instead you want something that's plain small and understandable allowing you to test quickly whether your infrastructure is working to that end you can take the following steps to set up your app first SSH into your VM and make sure that you have the latest versions of python and a sqlite 3 installed in the case of this VM python 3.10 is the system Python and the python version that ships with Ubuntu 2204 upgrading the distribution ensures you receive bargain security fixes from the latest python release optionally you could install another python version entirely such as python 3.11 alongside The system-wide Interpreter which you'd need to invoke specifically as python 3.11. next create and activate a virtual environment now install Django 4.1 at this point for the purposes of on-screen Clarity the terminal prompt will be set to be shorter than the default as much of each line is being taken up by the prompt you may well not need to do this but the code to do so is included in the course files you can now bootstrap the Django projected app using Django's management commands as seen on screen this creates the Django app my app alongside the project named project you can see the structure of files created on screen as you're accessing the machine via SSH you'll be using a terminal editor such as Vim or gnu Nano on screen you'll see Nano being used as it's installed by default in many Linux distributions and is straightforward to learn open project settings.py and append your app to installed apps as seen on screen to save a file in Nano press Ctrl and O for output and hit enter you can then exit by pressing Ctrl and X open my app template my app home.html and create a short and sweet HTML page after that edit my app views.py to render that HTML page now create and open myapp urls.py to associate your new view with a URL pattern you can now edit project urls.py to include the URLs you've just added you can do one more thing while you're at it which is to make sure the Django secret key used for cryptographic signing isn't hard-coded in settings.py which git will likely track open up project settings.py Nano import the OS module as you will be needing it and then remove the hard-coded secret key you can do this by pressing Ctrl k at the beginning of the line then enter the code scene on screen to read the secret key from the environment and raise an error if it's not found this tells Django to look in your environment for secret key rather than including it in your application source code for larger projects check out Django Environ to configure your Django application with environment variables finally you'll need to set the key in your environment here's how you can do that on Ubuntu Linux using openssl to set the key to an 80 character string you can cap the contents of Django secret key to see that openssl has generated a cryptographically secure hex string key also you can print out the value of the environment variable to check that the script has correctly stored the value with all that in place you're ready to go your minimal app is complete and set up in the next section of the course you'll see how to get the site up and running with Django's development server using Django's whiskey server in development in this section your test Django's development server using httpi a command line HTTP client for testing requests to your web app from the console first use CD to change back to the home directory then PWD to check the absolute location of it check that you're using the correct virtual environment and install httpi you can create an alias that will let you send a get request using HTTP to your application this Alias is get to an HTTP call with some default Flags you can now use get docs.python.org to see the response headers and body from the python documentation's home page before starting the Django development server you can check your Django project for potential problems if your check doesn't identify any issues then tell Django's built-in application server to start listening on localhost using the default Port of 8000. using no Hub and Ampersand executes the command in the background so that you can continue to use your shell no Hub will redirect standard output and standard error to the file nohub.out if it appears that no Hub hangs and leaves you without a cursor press enter to get your terminal cursor and shell prompt back you can use the jobs command to see the process identifier which will let you bring the process to the foreground or terminate it Django's run server command uses the syntax seen on screen if you leave the address Port argument unspecified as seen previously Django will default to listening on localhost Port 8000. you can use the lsof command to verify more directly that a python command was invoked to listen on Port 8000. at this point in the course your app is only listening on localhost which is the address 127001 it's not yet accessible from a browser but you can still give it its first visitor by sending a get request from the command line within the VM itself the header section seen on screen describes the software that generated the response in this case it's version 0.2 of whiskey server alongside C python 310. whiskey server is nothing more than a python class defined by Django that implements the python whiskey protocol what this means is that it adheres to the web server Gateway interface which is a standard that defines a way for web server software and web applications to interact in our example so far the Django G unicorn nginx project is the web application since you're serving the app in development there's actually no separate web server Django uses the simple server module which implements a lightweight HTTP server and fuses the concept of web server versus application server into one command run server in the next section of the course you'll see how to get your site online for the world to see
Original Description
Taking a Django app from development to production is a demanding but rewarding process. This video shows the first of several steps needed to set up a virtual machine and configure it for a Django app.
This is intended for intermediate to advanced users.
This is a portion of the complete course, which you can find here:
https://realpython.com/courses/django-app-with-gunicorn-nginx/
The rest of the course covers how to:
- Setting Up a Static Public IP Address
- Linking to a Domain
- Replacing WSGIServer With Gunicorn
- Incorporating Nginx
- Serving Static Files Directly With Nginx
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: AI Tools for PMs
View skill →Related Reads
📰
📰
📰
📰
A Practical Guide to Implementing the REINFORCE Algorithm in Python (Part 5)
Medium · Machine Learning
Gimitest: A Comprehensive Tool for Testing Reinforcement Learning Policies
ArXiv cs.AI
RLVP: Penalize the Path, Reward the Outcome
ArXiv cs.AI
Self-Review Reinforcement Learning (SRRL) with Cross-Episode Memory and Policy Distillation
ArXiv cs.AI
🎓
Tutor Explanation
DeepCamp AI