In this tutorial, our main goal is to guide you through the process of setting up a Django application to run in a production environment using Gunicorn and Nginx. Gunicorn is a Python WSGI HTTP Server that usually stands between a web framework (like Django) and an HTTP client. Nginx, on the other hand, is a web server which can act as a reverse proxy for Gunicorn, serving static files more efficiently than Gunicorn.
By the end of this tutorial, you will learn how to:
Prerequisites:
First, we need to install Gunicorn and Nginx. On an Ubuntu server, you can do this using the following commands:
sudo apt-get update
sudo apt-get install python3-gunicorn nginx
Next, we need to configure Gunicorn to serve our Django application. To do this, navigate to your Django project's directory and run the following command:
gunicorn myproject.wsgi:application --bind 127.0.0.1:8000
Replace myproject
with the name of your Django project. This command tells Gunicorn to serve the Django application on localhost at port 8000.
After Gunicorn is set up, we need to configure Nginx to reverse proxy to Gunicorn. Open the Nginx configuration file using the following command:
sudo nano /etc/nginx/sites-available/default
In this file, add the following configuration:
server {
listen 80;
server_name your_domain www.your_domain;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/username/myproject;
}
location / {
include proxy_params;
proxy_pass http://127.0.0.1:8000;
}
}
Replace your_domain
with your server's domain name, and replace username
and myproject
with your username and the name of your Django project, respectively.
Here's an example of how you can run Gunicorn to serve your Django application:
cd /home/username/myproject
gunicorn myproject.wsgi:application --bind 127.0.0.1:8000
In this example, we first navigate to our Django project's directory. Then, we run the gunicorn
command to serve our application.
Here's an example of an Nginx configuration file:
server {
listen 80;
server_name your_domain www.your_domain;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/username/myproject;
}
location / {
include proxy_params;
proxy_pass http://127.0.0.1:8000;
}
}
In this file, we configure Nginx to listen on port 80 (the default HTTP port), and to reverse proxy to Gunicorn at 127.0.0.1:8000
.
In this tutorial, we've learned how to install Gunicorn and Nginx, how to configure Gunicorn to run a Django application, and how to configure Nginx to reverse proxy to Gunicorn. We've also seen some examples of these configurations.
Next steps for learning include exploring more about deploying Django applications, learning about different ways to configure Gunicorn and Nginx, and understanding how to secure your application in a production environment.
Remember, practice is key when it comes to learning new concepts. Happy coding!