Deploying a Django Application with MySQL, Gunicorn, and Nginx on Ubuntu 22.04 Server: A Comprehensive Guide

Last updated on: Published by: Systems Librarian 0

In this comprehensive guide, we will walk you through the process of deploying a Django application using MySQL as the database backend, Gunicorn as the application server, and Nginx as the web server on an Ubuntu server. Whether you’re a seasoned developer or just starting with Django, this step-by-step tutorial will equip you with the knowledge and code samples needed to successfully deploy your Django application. So, let’s dive in and unleash the power of Django in a production-ready setup!

Before we begin, make sure that you have an Ubuntu 22.04 server instance up and running.

Step 1: Install Required Packages

First, we need to install the necessary packages on our server. Open a terminal window and run the following command to update the package list:

sudo apt update
sudo apt upgrade -y

These two commands will update and upgrade systems packages. Once the update process is complete, run the following command to install pip3, Python development headers, MySQL development headers, and Nginx web server:

sudo apt install python3-pip python3-dev libmysqlclient-dev nginx -y

Step 2: Install MySQL and Create a Database

Run the following command to install MySQL on the server. :

sudo apt install mysql-server -y

In Ubuntu 22.04, the MySQL installation process doesn’t prompt you to set the root password during installation. Instead, set the root password manually, by following these steps:

sudo mysql -u root

Since there’s no root password set yet, you can enter the MySQL shell without specifying a password with the above command.

Now, set the root password by running the following command:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'password';

Replace password with the desired password you want to set for the root user.

Flush the privileges to ensure the changes take effect:

FLUSH PRIVILEGES;

Once you have finished, create a new database for your Django application with the following command:

CREATE DATABASE dbname;

Remember to replace dbname with the name of your database.

Next, create a new user and grant it permissions to access the database:

CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'localhost';
FLUSH PRIVILEGES;

Replace username and password with a username and password of your choice.

Then exit MySQL shell by typing \q. The output for all these commands should be as shown below

Step 3: Clone Your Django Application

Now that we have MySQL set up, let’s clone our Django application from our version control system. In this example, we’ll assume that our Django application is stored in a Git repository.

First, install Git:

sudo apt install git

Next, navigate to the directory where you want to store your application and clone it from there:

git clone https://github.com/yourusername/yourproject.git

Remember to replace https://github.com/yourusername/yourproject.git with the actual URL of your Git repository.

Step 4: Set Up a Virtual Environment

It is good practice to run your python application in a virtual environment. Create a new virtual environment for your application by running the following commands:

sudo apt install python3-venv -y
cd yourdirectory

Replace yourproject with the actual name of your application directory.

python3 -m venv myvenv

This will create a new virtual environment named myvenv in the yourproject directory.

Next, activate the virtual environment:

source myvenv/bin/activate

Step 5: Install Dependencies

With the virtual environment activated, install the required Python packages with the following command:

pip install -r requirements.txt

requirements.txt file contains all the required packages that your django application depends on.

Step 6: Configure Gunicorn

Gunicorn is a Python Web Server Gateway Interface HTTP server that can serve your Django application. Install Gunicorn with the following command

pip install gunicorn

Then create a new Gunicorn configuration file by running the following command:

nano gunicorn_config.py

Add the following contents to the file:

bind = "127.0.0.1:8000"
workers = 3

This tells Gunicorn to bind to the IP address 127.0.0.1 on port 8000, and to use three worker processes.

Save and exit the file by pressing CTRL+X, then Y, then ENTER.

Step 7: Test Gunicorn

Before we configure Nginx to serve our Django application, it is important to test Gunicorn to make sure it is working properly. Activate the virtual environment if it’s not already activated as follows:

source myvenv/bin/activate

Then start Gunicorn as shown below:

gunicorn yourproject.wsgi:application -c gunicorn_config.py

Replace yourproject with the name of your Django project.

If Gunicorn starts successfully, you should see output that looks something like this:

Press Ctrl+C to stop Gunicorn for now.

Step 8: Configure Django for production

Open the Django application’s settings file:

nano /path/to/yourproject/yourproject/settings.py

Locate the DATABASES section and update it with the MySQL database settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

Replace 'dbname', 'username', and 'password' with the actual values for your MySQL database.

Configure static files settings by ensuring the following lines of the settings file are correct:

STATIC_ROOT = '/path/to/yourproject/static/'
STATIC_URL = '/static/'

Set the DEBUG setting to False for production deployment:

DEBUG = False

This helps improve security by disabling detailed error pages.

Optionally, configure allowed hosts by adding your server’s domain or IP address to the ALLOWED_HOSTS list:

ALLOWED_HOSTS = ['yourdomain.com', 'server-ip-address']

Generate a new secret key for your Django application. You can use Django’s get_random_secret_key() function to generate one:

from django.core.management.utils import get_random_secret_key

SECRET_KEY = get_random_secret_key()

Create MySQL tables for your django application.

cd /path/to/yourdirectory
source myvenv/bin/activate
pip install mysqlclient
python manage.py migrate

Step 9: Configure Nginx

Nginx is a high-performance web server that can act as a reverse proxy for Gunicorn, allowing it to serve requests from the internet. First, create a new Nginx server block:

sudo nano /etc/nginx/sites-available/yourproject

Replace yourproject with the actual name of your project.

server {
    listen 80;
    server_name yourserver.com;
    location / {
        include proxy_params;
        proxy_pass http://unix:/path/to/yourdirectory/yourdirectory.sock;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }
    location /static/ {
        alias /path/to/yourdirectory/static/;
    }

}

Replace yourserver.com with your server’s domain name or IP address.

Save and exit the file by pressing CTRL+X, then Y, then ENTER.

Next, enable the server block by creating a symbolic link:

sudo ln -s /etc/nginx/sites-available/yourproject /etc/nginx/sites-enabled/

Check that the configuration is valid with the following command

sudo nginx -t

If the configuration is valid, you will see output as shown below

Next, add www-data user to the group that has permission to write to the socket file

sudo usermod -aG systemuser www-data

Replace systemuser with an actual username on your system

Finally, reload Nginx:

sudo systemctl reload nginx

Step 10: Automate Gunicorn Startup with systemd

Manually starting Gunicorn every time the server reboots is inconvenient. To automate the process, we’ll create a systemd service unit file.

Create a Gunicorn systemd unit file:

sudo nano /etc/systemd/system/gunicorn.service

Add the following content to the file:

[Unit]
Description=Gunicorn service for yourproject
After=network.target

[Service]
User=yourusername
Group=www-data
WorkingDirectory=/path/to/yourproject
ExecStart=/path/to/myvenv/bin/gunicorn --workers 3 --bind unix:/path/to/yourproject/yourproject.sock yourproject.wsgi:application

[Install]
WantedBy=multi-user.target

Replace yourusername with your username, /path/to/yourproject with the absolute path to your project directory, and /path/to/myvenv with the absolute path to your virtual environment.

Save and exit the file by pressing CTRL+X, then Y, then ENTER.

Next, reload systemd to load the new unit file:

sudo systemctl daemon-reload

Now, start the Gunicorn service:

sudo systemctl start gunicorn

Verify that the service has started successfully:

sudo systemctl status gunicorn

To enable Gunicorn to start automatically on system boot, run the following command:

sudo systemctl enable gunicorn

Gunicorn will now start automatically whenever the server reboots.

Conclusion

In this tutorial, we went through the steps to deploy a Django application using MySQL, Gunicorn, and Nginx on an Ubuntu server. By following these steps, you should now have a fully functional Django application that can serve requests in a production environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.