How to deploy a Django Application on Ubuntu?
Django is a Python tool that makes it easy and fast to build safe websites without doing a lot of work yourself.. It has many ready-to-use features, so you don’t need to start from zero.
It started in 2003 and became open-source in 2005. Today, it’s one of the most popular ways to make websites using Python.
Django follows the Model-View-Template (MVT) pattern and includes features like login systems, database handling, and built-in security.
Why Use Django?
Fast Development – Helps build web apps quickly with reusable parts.
Secure – Protects against common security threats.
Scalable – Works well for big platforms like Instagram and Spotify.
Versatile – Used for websites, APIs, and AI applications.
In this article, we will learn how to deploy a Django application on Ubuntu. Here, we have chosen Ubuntu 22.04 OS to deploy the Django project.
Set up Python 3 Tools and libraries
Ubuntu 22.04 and other Debian-based Linux versions already come with Python 3 installed. But to make sure everything is up to date, first refresh your system’s package list by running:
apt update
Then update all installed packages:
apt upgrade
The -y option automatically answers “yes” to every question. Depending on your Linux version, you might still need to confirm a few things during the upgrade.
Once that’s done, you can check your Python 3 version with:
python3 -V
You’ll see something like:
Python 3.10.12
To install Python tools and libraries, we’ll need pip, which helps you add extra Python packages to your system. Install it with:
apt install -y python3-pip
You can now add any Python library by using:
pip3 install package_name
For example, to install NumPy, use:
pip3 install numpy
Let’s also install a few more tools to make sure your programming environment is ready:
apt install build-essential libssl-dev libffi-dev python3-dev
After this, Python and pip will be ready to use, and you’ll be all set to create a virtual environment for your development projects.
Setting Up a Virtual Environment
A virtual environment lets you create a separate space on your server just for one Python project. This way, every project can have its own tools and libraries, and they won’t interfere with each other.
Using separate environments makes it easier to manage and avoid problems when different projects need different versions of the same package.
You can create unlimited environments as you want. Each one is just a folder with some files that help it act like its own little world for Python.
Install venv
We’ll use Python’s built-in venv tool to create environments. First, install it with:
apt install -y python3-venv
Create a Folder to Store Your Environments
You can create a folder to keep all your environments organized:
mkdir environments
cd environments
Now you’re inside the folder where you’ll create your Python environments.
Create Your Virtual Environment
Run this command to make a new environment named my_env:
python3 -m venv my_env
This will create a folder named my_env. You can look inside with:
ls my_env
You’ll see some folders like bin, lib, and a file called pyvenv.cfg. These files help keep your project’s settings and packages separate from the rest of the system.
Activate the Environment
To start using your new environment, run:
source my_en v/bin/activate
You’ll notice your command line now starts with (my_env) — this means the environment is active.
Now, any Python or pip commands you run will only apply inside this environment, not system-wide.
Now your virtual environment is ready, and you can install whatever Python packages you need without affecting other projects or the system.
Install and configure Apache
Apache is one of the most popular web servers in the world. It’s used to host websites and web apps. It has strong features like handling different media types, adding modules easily, and working well with other software..
Ubuntu makes it easy to install Apache using built-in tools.
First, update your package list:
apt update
Then install Apache:
apt install apache2
After you confirm, Ubuntu will install Apache and everything it needs to run.
Set Up a Virtual Host for Your Website (Recommended)
When you’re using the Apache web server, virtual hosts help you manage multiple websites on the same server — kind of like Nginx server blocks. Each site can have its own settings and files.
Let’s set up a virtual host for your website. In this example, we’ll use your_domain, but you should replace that with your actual domain name (like example.com).
1. Create a Website Directory
Apache is set to serve files from /var/www/html by default. But if you want to host multiple sites, it’s better to create a separate folder for each one.
Create a new folder:
mkdir /var/www/your_domain
Then give yourself permission to edit it:
chown -R $USER:$USER /var/www/your_domain
Set correct permissions so Apache can read your files:
chmod -R 755 /var/www/your_domain
2. Create a Test Web Page
Let’s add a simple HTML page to test your site:
nano /var/www/your_domain/index.html
Paste this into the file:
<HTML>
<head>
<title>Welcome to your_domain!</title>
</head>
<body>
<h1>Success! The your_domain virtual host is working!</h1>
</body>
</html>
Save and exit the file.
3. Create a Virtual Host Config File
Now we’ll tell Apache how to serve this website by creating a new configuration file:
nano /etc/apache2/sites-available/your_domain.conf
Paste the following:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName your_domain
ServerAlias www.your_domain
DocumentRoot /var/www/your_domain
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
ServerName is your main domain.
ServerAlias is any other name that should point to the same site.
DocumentRoot tells Apache where your site’s files are.
Save and exit the file.
4. Enable the Virtual Host
Enable your new site:
a2ensite your_domain.conf
Disable the default site:
a2dissite 000-default.conf
Test Apache for errors:
apache2ctl configtest
You should see:
Syntax OK
Now restart Apache:
systemctl restart apache2
5. Test in Your Browser
Visit http://your_domain or server-IP-address in your browser. You should see your test message:
Success! The your_domain virtual host is working!
MySQL Installation and Configuration:
MySQL is a free database system that stores and manages data for websites and apps. It’s commonly used with the LAMP stack, which stands for Linux, Apache, MySQL, and PHP/Python/Perl. MySQL uses SQL (Structured Query Language) to work with data.
Step 1: Install MySQL on Ubuntu 20.04
To install MySQL, start by updating your package list:
apt update
Then install MySQL with:
apt install mysql-server
Start the MySQL service:
systemctl start mysql.service
This installs and starts MySQL, but doesn’t ask you to set a password yet — so let’s fix that next.
Step 2: Secure Your MySQL Setup
Run the MySQL security script to make your installation more secure:
mysql_secure_installation
You’ll go through several questions like:
Do you want to set up a password checker? (optional)
Do you want to set a root password? (yes!)
Remove anonymous users? (yes)
Disallow remote root login? (yes)
Remove test database? (yes)
Choose Y (yes) for most options unless you have a reason not to.
Step 3: Change Root Password (Optional)
If you want to set or change the root password manually:
Log into MySQL:
mysql
Run this command (replace ‘your_password’ with your real password):
ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘your_password’;
Exit MySQL:
exit
Step 4: Create a New MySQL User
Using the root user, log in:
mysql -u root -p
Enter the password of the root user that you have set in the previous step.
Create a new user (replace nick and password with your values):
CREATE USER ‘nick’@’localhost’ IDENTIFIED BY ‘password’;
Give that user permissions:
GRANT ALL PRIVILEGES ON *.* TO ‘nick’@’localhost’ WITH GRANT OPTION;
Update MySQL permissions:
FLUSH PRIVILEGES;
Exit MySQL:
exit
Now you can log in with your new user:
mysql -u nick -p
To create a new database, run the following command from your MySQL console:
CREATE DATABASE database_name;
Exit MySQL:
exit
Deploying your Django Project
You can deploy your Django project to your Elastic VPS from your local system or your GitHub account.
If your project is stored on GitHub, you can download it to your VPS differently. In this guide, we’ll use Git to clone the project.
Step 1: Choose Where to Deploy
We’ll deploy the project to this folder:
/var/www/djangoapp/
First, go to that folder in the terminal. If the folder doesn’t exist, you can create it using mkdir.
Step 2: Install Git (If Needed)
If Git is not installed on your server, install it with:
apt install git
Step 3: Clone Your GitHub Project
Use this command to download your project from GitHub:
git clone https://github.com/username/repository.git
Example:
git clone https://github.com/ronakbediya310/document_Qna.git
Step 4: Move the Project Files
After cloning, move all the project files into the deployment folder (/var/www/djangoapp/):
mv repository-name/* /var/www/djangoapp/
Replace repository-name with the name of the folder that Git created.
Step 5: Check the Files
To check if the files are in place, run:
ls /var/www/djangoapp/
You should see your project files listed.
Install Project Dependencies
You need to install a few tools and packages to run your Django project smoothly. Follow the steps below:
1. Install Rust and Cargo
Rust is needed for some Python packages that use it in the background.
Run this command:
curl https://sh.rustup.rs -sSf | sh
When prompted, just press Enter to start the standard installation.
After it’s done, check if it’s installed properly:
rustc --version
cargo --version
2. Install Required System Packages
These packages are needed to build some Python modules:
apt install pkg-config libmysqlclient-dev build-essential python3-dev default-libmysqlclient-dev
3. Install Django REST Framework in Your Virtual Environment
Run this to install Django REST framework to your virtual environment.
pip install djangorestframework
4. Install Django CORS Headers
This package allows your app to handle cross-origin requests (CORS).
pip install django-cors-headers
You can also add this line to your requirements.txt file:
django-cors-headers>=4.0.0
After installing, update your Django settings:
Add to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
...
'corsheaders',
...
]
Add to MIDDLEWARE (usually near the top):
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
5. Install Hugging Face Library
To use models from Hugging Face, install this:
pip install sentence-transformers
You now have all the essential packages installed to run your Django project.
6. Install Groq’s LLM with LangChain
Run the following command in the terminal to add Groq’s LLM with LangChain in your virtual environment.
pip install langchain-groq
If you also haven’t installed groq yet (which is the underlying SDK):
pip install groq
Integrate the database with Django project:
Create a .env File for Your Database Details
To help your Django project connect to the database, create a .env file and add your credentials there.
Run this command to create/edit the file:
nano .env
Add the following lines inside the file (replace with your actual details):
GROQ_API_KEY="your_groq_api_key"
DB_NAME="your_database_name"
DB_USER="your_database_user"
DB_PASSWORD="your_database_password"
DB_HOST="localhost"
DB_PORT="3306"
Save and exit the file when you’re done.
Place the wsgi.py File in the ROOT Directory
Make sure your wsgi.py file is placed inside the main ROOT directory of your project.
Important Note:
If you’re preparing your own deployment, your project folder must include:
requirements.txt – a list of all Python libraries your app needs
wsgi.py – the file that helps Apache start your Django app
Install Required Packages and Set Up Database
Run these commands in the terminal (inside your virtual environment):
pip install -r requirements.txt
python3 manage.py makemigrations
python3 manage.py migrate
This will install all the needed packages and apply database migrations.
Edit the wsgi.py File for your Virtual Environment
Edit this file:
nano /var/www/webroot/ROOT/wsgi.py
Replace its content with the following:
import os
import sys
virtenv = os.path.expanduser('~') + '/virtenv/'
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
if sys.version.split(' ')[0].split('.')[0] == '3':
exec(compile(open(virtualenv, "rb").read(), virtualenv, 'exec'), dict(__file__=virtualenv))
else:
execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
pass
sys.path.append(os.path.expanduser('~'))
sys.path.append(os.path.expanduser('~') + '/ROOT/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'ROOT.project_folder_name.settings'
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Replace project_folder_name with your actual Django project folder (the one that contains settings.py).
Run the Django Project
Run the project in your virtual environment by running the following command.
python manage.py runserver 0.0.0.0:8000
You can see that the Django application is running on port 8000.
Open your favorite browser and type server-ip-address:8000 in the address bar.
Conclusion:
To run a Django app on Ubuntu, you need to update the server, install the required software, configure the database, create a virtual environment, and connect it to a web server like Apache or Nginx. With the proper setup and security, your Django app will work smoothly and be ready for users.