Django is a high-level Python framework for developing web applications, while Nginx is a powerful HTTP server. The use of Django with Nginx can provide an efficient, robust web application setup. However, configuring Django and Nginx to work together may seem complex, especially for beginners. In this case, a third party software is used to establish a connection between these two, usually called a WSGI server. A popular choice is Gunicorn.
Before proceeding, ensure that you have installed Python, Django, Nginx, and Gunicorn on your server. Below is a step by step guide on how to configure Django with Nginx.
Step 1: Create and configure your Django Application.
After you’ve set up your Django application(‘myproject’ for example), you should set the Django project to serve static files which will later be picked up by Nginx:
```
```
python manage.py collectstatic
```
Step 2: Install and configure Gunicorn.
Gunicorn can be installed with the command:
```
pip install gunicorn
```
To start a Gunicorn server use the following command:
```
gunicorn —bind 0.0.0.0:8000 myproject.wsgi
```
Step 3: Configure Nginx to Proxy Pass to Gunicorn
Create a new Nginx server block configuration file in directory at `/etc/nginx/sites-available/myproject` with the following lines:
```
server {
listen 80;
server_name your-server-domain-or-IP;
```
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
```
Then, test Nginx configuration and restart Nginx:
```
sudo nginx -t
sudo service nginx restart
```
Step 4: Set up Gunicorn to run on startup
Modify the ‘/etc/systemd/system/gunicorn.service’ systemd script:
```
[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/myproject
ExecStart=/home/ubuntu/env/bin/gunicorn —access-logfile – —workers 3 —bind unix:/home/ubuntu/myproject/myproject.sock myproject.wsgi:application
```
Enable and start the Gunicorn service:
```
sudo systemctl enable gunicorn
sudo systemctl start gunicorn
```
With these settings in place, Nginx should serve your static files while also being able to communicate with Gunicorn to process dynamic requests.
These instructions are adapted from the DigitalOcean tutorials and Django documentation.
- https://www.djangoproject.com/
- https://docs.djangoproject.com/en/3.2/howto/static-files/
- https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04
- https://docs.gunicorn.org/en/latest/install.html
- https://nginx.org/en/docs/