Setup Django with Nginx, Postgres and Gunicorn on Ubuntu 22.04

Setup Django with Nginx, Postgres and Gunicorn on Ubuntu 22.04. In this guide, we introduce Django, its major features, and advantages then show you how to set up Django with Nginx, Postgres and Gunicorn on Ubuntu 22.04.

There are various advantages of using Django for web development. It is fast to develop with, as it handles much of the code and provides a set of ready to use components. The software is also highly scalable, you use it to build websites with hundreds of millions of visitors.

What is Django?

To start with, Django is a high level Python web framework that allows developers to quickly create secure and maintainable websites. To free developers concentrating on designing the actual program, it aims to offer a set of tools and conventions for creating online apps that handle several difficulties associated with web development.

Additionally, the Django framework works with a sizable and vibrant community of developers that produce third party packages to increase its capability. Finally, Django has excellent documentation, making it easy to learn and use.

Key features of Django

Django is a high level Python web framework that provides tools and conventions for building web applications. Some key features of Django are:

  • Automatic database schema migrations: Comes with tools for automatically creating and applying database schema migrations making it easy to make changes to the database structure of a Django app as it evolves.
  • Robust security system: Cross site scripting (XSS), cross site request forgery (CSRF), and SQL injection are just a few of the popular web assaults that Django has built in defenses against. In addition, Django offers a safe approach to store user accounts and passwords. It avoids pitfalls like saving passwords directly rather than hashing them or keeping session information in cookies where it is vulnerable.
  • Support for multilingual applications: Django makes it easy to build applications in multiple languages. Provides tools for defining translations of text strings and for handling language specific formatting of dates, times, and numbers.
  • An Easy to use template engine: Django comes with a template engine that allows developers to define the structure of a Django app’s user interface using simple templates.
  • Serialization support: Django has built in support for serializing and deserializing data in several formats, including JSON and XML. These features make Django a versatile and powerful tool for building secure and maintainable websites. Whether building a simple blog or a complex web application, Django has the features you need to get the job done.

Advantages of using Django

Some advantages of using Django for web development are:

  • Fast development: Django’s set of tools and conventions handle much of the boilerplate code and provide a set of ready to use components, making it fast to develop.
  • Scalability: Django has been used to build websites that have handled hundreds of millions of visitors, so it scales to handle large amounts of traffic.
  • Large, active community: Django has a large, active community of developers who contribute to the framework and create third party packages to extend its functionality implying a wealth of resources and support available for Django developers.
  • Excellent documentation: Django has excellent documentation, which makes it easy to learn and use.
  • “Batteries included” philosophy: Django follows the “batteries included” philosophy, which means that it has many features out of the box, so you don’t have to build everything from scratch that saves a lot of development time.

Overall, Django is a powerful and useful web framework that offers many advantages for developers.

Now we have reached the main part of the article How to Setup Django with Nginx, Postgres and Gunicorn on Ubuntu 22.04.

How to Setup Django with Nginx, Postgres and Gunicorn on Ubuntu 22.04

In this post, we show you how to install Django with Nginx, Postgres and Gunicorn on Ubuntu 22.04.

Prerequisites

  • An Ubuntu 22.04 server installed on your system.
  • A root user or a user with sudo privileges.

Install Required Dependencies

Before starting, update and upgrade your system packages to the latest version using the following command.

				
					apt update -y
apt upgrade -y
				
			

After updating all the system packages, you need to install some Python dependencies to your system. You install all of them using the following command.

				
					apt install python3-venv python3-pip python3-dev libpq-dev curl
				
			

Install Nginx Web Server

Then, you also need to install the Nginx web server to deploy Django on the web. You install the Nginx package using the following command.

				
					apt install nginx -y
				
			

Once the Nginx package is installed, start the Nginx and enable it to start after the system reboot.

				
					systemctl start nginx
systemctl enable nginx
				
			

Install and Configure PostgreSQL

In this post, we use the PostgreSQL as a database backend. So you need to install the PostgreSQL to your system. You install it with the following command.

				
					apt install postgresql postgresql-contrib -y
				
			

After installing the PostgreSQL server, login to the PostgreSQL with the following command.

				
					su - postgres
psql
				
			

Next, create a database and user for Django with the following command.

				
					CREATE DATABASE	djangodb;
CREATE USER djangouser WITH PASSWORD 'yourpassword';
				
			

Set different roles to Django user with the following command.

				
					ALTER ROLE djangouser SET client_encoding TO 'utf8';
ALTER ROLE djangouser SET default_transaction_isolation TO 'read committed';
ALTER ROLE djangouser SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE djangodb TO djangouser;
				
			

Next, exit from the PostgreSQL shell with the following command.

				
					\q
exit
				
			

Install Django

First, update the PIP package to the latest version using the following command.

				
					pip3 install --upgrade pip
				
			

Next, install the Python virtual environment with the following command.

				
					pip3 install virtualenv
				
			

Then, create a project directory for Django.

				
					mkdir ~/project
				
			

Next, navigate to the project directory and create a virtual environment.

				
					cd ~/project
virtualenv djangoenv
				
			

After that, activate the Python virtual environment.

				
					source djangoenv/bin/activate
				
			

Finally, install Django and Gunicorn using the following command.

				
					pip install django gunicorn psycopg2-binary
				
			

Next, create a Django project with the following command.

				
					django-admin startproject djangoproject ~/project
				
			

Configure Django

Next, edit the Django configuration file and define your database settings and other parameters.

				
					nano ~/project/djangoproject/settings.py
				
			

Change the following lines:

				
					ALLOWED_HOSTS = ['django.yourdomain.com', 'localhost']
DATABASES = {  
	'default': {     
		'ENGINE': 'django.db.backends.postgresql_psycopg2',       
		'NAME': 'djangodb',       
		'USER': 'djangouser',        
		'PASSWORD': 'yourpassword',        
		'HOST': 'localhost',       
		'PORT': '',    
	}
}
STATIC_URL = '/static/'
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

				
			

Save and close the file then migrate the database with the following command.

				
					./manage.py makemigrations
./manage.py migrate
				
			

Next, create a Django superuser with the following command.

				
					./manage.py createsuperuser
				
			

Define your user and password as shown below.

				
					Username (leave blank to use 'root'): dadmin
Email address: hitjethva@gmail.com
Password: 
Password (again): 
Superuser created successfully.
				
			

Then, copy all static files.

				
					./manage.py collectstatic
				
			

Now, start the Django server with the following command.

				
					./manage.py runserver 0.0.0.0:8000
				
			

You should see the following screen.

Press the CTRL+C to stop the server. Next, start the Django using Gunicorn.

				
					gunicorn --bind 0.0.0.0:8000 djangoproject.wsgi
				
			

If everything is fine, you should see the following screen.

Press the CTRL+C to stop the server.

Now, deactivate the virtual environment using the following command.

				
					deactivate
				
			

Create a Systemd Service File for Django

Next, you need to create a systemd service file to manage the Django. First, create a Gunicorn socket file.

				
					nano /etc/systemd/system/gunicorn.socket
				
			

Add the following configuration.

				
					[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target

				
			

Next, create a Gunicorn service file.

				
					nano /etc/systemd/system/gunicorn.service
				
			

Add the following configuration.

				
					[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/root/project
ExecStart=/root/project/djangoenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock djangoproject.wsgi:application
[Install]
WantedBy=multi-user.target

				
			

Save and close the fiel then set proper ownership to the project directory and reload the systemd configuration using the following command.

				
					chown -R www-data:root ~/project
systemctl daemon-reload
				
			

Next, start and enable the Gunicorn service with the following command.

				
					systemctl start gunicorn.socket
systemctl enable gunicorn.socket
				
			

You can verify the Gunicorn status using the following command.

				
					systemctl status gunicorn.socket
				
			

Sample output.

				
					● gunicorn.socket - gunicorn socket
     Loaded: loaded (/etc/systemd/system/gunicorn.socket; disabled; vendor preset: enabled)
     Active: active (listening) since Thu 2023-02-02 04:41:00 UTC; 24s ago
   Triggers: ● gunicorn.service
     Listen: /run/gunicorn.sock (Stream)
     CGroup: /system.slice/gunicorn.socket

Feb 02 04:41:00 linux systemd[1]: Listening on gunicorn socket.

				
			

Configure Nginx for Django

Next, create an Nginx configuration file for Django to access the Django via port 80.

				
					nano /etc/nginx/conf.d/django.conf
				
			

Add the following configurations.

				
					server {  
	listen 80;     
	server_name django.yourdomain.com;    
	location = /favicon.ico { access_log off; log_not_found off; }    
	location /static/ {         
		root /root/project;     
	}    
	location / {         
		include proxy_params;         
		proxy_pass http://unix:/run/gunicorn.sock;     
	}
}

				
			

Save and close the file then restart the Nginx service to apply the changes.

				
					systemctl restart nginx
				
			

Access Django Web Interface

Well, Django is now installed and configured with Nginx, Postgres and Gunicorn. You now access the Django admin interface using the URL http://django.yourdomain.com/admin. You should see the Django login page.

Provide your Django admin username, password then click on the Login button. You should see the Django dashboard on the following screen.

Thank you for reading How to Setup Django with Nginx, Postgres and Gunicorn on Ubuntu 22.04. We shall conclude. 

Setup Django with Nginx, Postgres and Gunicorn on Ubuntu 22.04 Conclusion

In short, Django is a powerful and versatile web framework for Python developers. Its key features, such as automatic database schema migrations, a robust security system, and support for multilingual applications, make it a versatile tool for building secure and maintainable websites. The advantages of using Django, including its fast development process, scalability, and large, active community, make it an attractive choice for many web projects. Whether you are a seasoned web developer or new to the field, Django is worth considering for your next project.

Do check out more of Django content in our blog, by navigating here

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

2 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x