Deploying django application with gunicorn nginx mysql by Marouane March 19, 2024 python

Deploying django application with gunicorn nginx mysql

 

 

Installing the Packages from the linux Repositories

To begin the process, you will download and install all of the items that you need from the Ubuntu repositories. Later you will use the Python package manager pip to install additional components.

First you need to update the local apt package index and then download and install the packages. The packages that you install depend on which version of Python your project will use.

If you are using Django with Python 3.

 


Step One: Update Packages

 

sudo apt-get update

sudo apt-get upgrade

 

Step Two: Install and Create Virtualenv

 

sudo apt-get install python-virtualenv

sudo virtualenv /opt/myenv

 

Step Three: Install Django

 

pip install django

 

Step Four: Install MySQL

 

sudo apt-get install build-essential git mysql-server mysql-client libmysqlclient-dev python-dev

 

Step Five: Install NGINX

 

sudo apt-get install nginx

 

Step Six: Install Gunicorn

 

source /opt/myenv/bin/activate

pip install gunicorn

 

Step Seven: Configure MySQL

Step Eight: Clone the Django Project

 

cd /opt/myenv

source /opt/myenv/bin/activate

git clone git-url myproject

cd /opt/myenv/myproject/myproject

Edit the settings.py file with your editor of choice:

vim settings.py

 

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'myproject',

        'USER': 'root',

        'PASSWORD': 'password',

        'HOST': '127.0.0.1',

        'PORT': '',

    }

}

 

cd /opt/myenv/myproject

pip install -r requirements.txt

python manage.py syncdb

python manage.py collectstatic

 

Step Nine: Configure Gunicorn

 

gunicorn_django --bind 162.243.36.4:8001

cd /opt/myenv

sudo nano gunicorn_config.py

Add the following contents to the file:

command = '/opt/myenv/bin/gunicorn'

pythonpath = '/opt/myenv/myproject'

bind = '127.0.0.1:8001'

user = 'nobody'

/opt/myenv/bin/gunicorn -c /opt/myenv/gunicorn_config.py myproject.wsgi

 

Step Ten: Configure NGINX

 

sudo service nginx start

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

 

Add following lines in nginx Configure

 

server {

    server_name yourdomainorip.com;

 

    access_log off;

 

    location /static/ {

        alias /opt/myenv/static/;

    }

 

    location / {

            proxy_pass http://127.0.0.1:8001;

            proxy_set_header X-Forwarded-Host $server_name;

            proxy_set_header X-Real-IP $remote_addr;

            add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';

    }

}

 

 

nginx restart

 

cd /etc/nginx/sites-enabled

sudo ln -s ../sites-available/myproject

sudo rm default

sudo service nginx restart

Copyright © Marouane All Rights Reserved

Buy Me a Coffee