Welcome to the Django Deployment guide! ๐ฏ This tutorial is designed to guide you through the process of deploying your Django web applications. By the end of this guide, you'll have a working understanding of how to deploy your Django projects to a production environment.
Deployment is the process of making your Django application accessible to the public. In this tutorial, we'll cover the steps to deploy a Django application on a Linux-based server using Gunicorn and Nginx.
Before we dive in, make sure you have the following prerequisites:
In Django, the WSGI (Web Server Gateway Interface) file acts as a bridge between your web application and the web server. To create a WSGI file, follow these steps:
wsgi.py.wsgi.py:"""
WSGI config for myproject project.
It exposes the WSGI callable as a module-level variable named `application`.
"""
import os
import sys
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()Replace myproject with the name of your Django project.
To serve your Django project's static and media files, follow these steps:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')python manage.py collectstaticGunicorn is a WSGI HTTP Server for Python. To install Gunicorn on your server, run:
pip install gunicornCreate a new file named gunicorn_config.sh in your project's root directory with the following content:
#!/bin/bash
gunicorn myproject.wsgi:application -b 0.0.0.0:8000 -w 3 -k gthread -DReplace myproject with the name of your Django project.
Make the script executable:
chmod +x gunicorn_config.shCreate a new Nginx configuration file for your Django project:
sudo nano /etc/nginx/sites-available/myprojectAdd the following content to the file:
server {
listen 80;
server_name example.com;
location / {
include proxy_params;
proxy_pass http://localhost:8000;
}
location /static {
alias /path/to/your/project/static;
}
location /media {
alias /path/to/your/project/media;
}
}Replace example.com with your domain name and /path/to/your/project with the actual path to your Django project on the server.
Create a symbolic link from sites-available to sites-enabled:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/Test the Nginx configuration:
sudo nginx -tRestart Nginx:
sudo systemctl restart nginxStart your Django application with Gunicorn:
./gunicorn_config.shYour Django project is now live and accessible at the specified domain name!
Congratulations! You've successfully deployed your Django project to a production environment. Deployment might seem daunting at first, but with practice, it will become second nature.
๐ Note: To stop Gunicorn, use Ctrl+C in the terminal where it's running.
What is the purpose of the WSGI file in Django?