You are currently viewing Deploy Django API and react JS on Apache web server

Deploy Django API and react JS on Apache web server

In this guide, we are going to go through how to deploy a Django API and React JS on an Apache web server. You are required to have a Linux machine, with access to the root user. We will cover the necessary steps, from setting up the server environment to configuring Apache for serving both the front end and backend.

Resources and architecture.

Keep these points in mind and adjust them as needed as they will be referenced in the virtual host settings.

  • Root folder for React Js: /home/ubuntu/frontend
  • Root folder for Django API: /home/ubuntu/backend
  • Django virtual environment folder: /home/ubuntu/backend/venv
  • Ensure your application is working locally as expected.
  • Location for the WSGI file: /home/ubuntu/backend/myproject
  • Django is to be accessible on port 8000 and React on port 80.

Methods used to upload Data to the server.

  1. SCP (Secure Copy Protocol)
scp filename.zip username@remote_host:/path/to/upload/data 
  1. GitHub

Push your code to github and clone it to your server, in the respective folders.

git clone https://github.com/username/repository.git

Part 1: Deploy Django Rest API

We will start by deploying the backend so that we can link this with the front end locally first. Once this works, we will then proceed to set up the backend.

Step 1: Install Python, virtualenv and Set up virtualenv

sudo apt update
sudo apt install python3 python3-pip python3.12-venv
python3 --version

Create the directory, create virtualenv, and activate the virtual environment

mkdir /home/ubuntu/backend
cd /home/ubuntu/backend
python3 -m venv venv   #creates virtualenvironment in the specified path.
source venv/bin/activate  #activates the virtual environment

Step 2: Set Up and enable mod_wsgi

mod_wsgi is an Apache HTTP server module that allows you to serve Python web applications using the WSGI (Web Server Gateway Interface) specification. WSGI is a standard interface between web servers and Python web applications or frameworks, like Django.

sudo apt update
sudo apt install libapache2-mod-wsgi-py3 apache2

sudo a2enmod wsgi
sudo systemctl restart apache2

Step 3: Upload your project files and install project dependencies

Upload your project file using your preferred method to the root directory: /home/ubuntu/backend. Proceed and install your project dependencies.

pip install -r requirements.txt   #install the dependancies.
python manage.py collectstatic

Step 4: Install and Configure Django-cors-headers

Django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS). This allows in-browser requests to your Django application from other origins, ie: through this, the React Js application will be able to connect with the Django Rest API. Reference article

#Install cors headers
pip install django-cors-headers

#and then add it to your installed apps:
INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]
#add a middleware class to listen in on responses
MIDDLEWARE = [
    ...,
    "django.middleware.common.CommonMiddleware",
    ...,
]
# Add a list of origins that are authorized to make cross-site HTTP requests
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000", #update this with the domain name or Ip for your react app.
]

Step 5: Configure Apache Virtual Host for Django

Configuring an Apache Virtual Host for Django involves setting up a dedicated configuration file within Apache to define how requests to your Django application should be handled and served.

sudo nano /etc/apache2/sites-available/backend.conf
#add the following code
<VirtualHost *:8000>
    ServerAdmin [email protected]   #add your admin email
    ServerName HostIP or Domain name  #replace with the correct entry
    ServerAlias www.HostIp or www.domainname
 
    DocumentRoot /home/ubuntu/backend
 
    Alias /static /home/ubuntu/backend/static
<Directory /home/ubuntu/backend/static>
        Require all granted
</Directory>
     # ProxyPass configuration for Django on port 8000
#    ProxyPass / http://127.0.0.1:8000/
#    ProxyPassReverse / http://127.0.0.1:8000/
 
    Alias /media /home/ubuntu/backend/media
<Directory /home/ubuntu/backend/media>
        Require all granted
</Directory>
 
    <Directory /home/ubuntu/backend>
        Require all granted
    </Directory>
 
    <Directory /home/ubuntu/backend/myproject>
<Files wsgi.py>
            Require all granted
</Files>
</Directory>
 
    WSGIDaemonProcess backend python-home=/home/ubuntu/backend/venv python-path=/home/ubuntu/backend
    WSGIProcessGroup backend
    WSGIScriptAlias / /home/ubuntu/backend/myproject/wsgi.py
 
    ErrorLog ${APACHE_LOG_DIR}/backend_error.log
    CustomLog ${APACHE_LOG_DIR}/backend_access.log combined
</VirtualHost>

Step 6: Enable the New Site and Restart Apache

#cd /etc/apache2/sites-available/ #Not necessary. Shows the path where the virtual host are.
sudo a2ensite backend #Enable the new virtual host
sudo systemctl reload apache2 #Reload Apache to apply the changes

Step 7: Ensure Apache modules are enabled and Update Apache Ports Configuration

Make sure that the proxy and proxy_http modules are enabled in Apache. You can enable them using the following commands:

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo systemctl restart apache2

To access the Django application on port 8000, we need to Update Apache Ports Configuration and add this port.

sudo nano /etc/apache2/ports.conf
#then add the following Line
Listen 8000

Step 8: Check File and Directory Permissions

Ensure that Apache has read and executed permissions on your project directories. Run the following to give the necessary permissions and ownership.

sudo chown -R www-data:www-data /home/ubuntu/backend
sudo chown www-data:www-data db.sqlite3
sudo chmod -R 755 /home/ubuntu/backend
sudo chmod 775 /home/ubuntu/backend
sudo chmod 755 /home/ubuntu
sudo chmod 664 db.sqlite3  #If you are using the sqlite3 database.

#Restart apache to apply the changes
sudo systemctl reload apache2

At this stage, your web application should be accessible on the HTTP protocol of the domain name if configured, or through the IP. If you have configured a domain name and wish to secure your web application with a free SSL certificate; check out this guide: Configure free SSL certificate on Apache

Common errors during deployment

Permission related errors when:
1. Installing dependancies using pip
2. Running the collectstatic command
Solution for permission related errors: Change file/folder ownerships using the following.
sudo chown -R $USER:$USER /home/ubuntu/backend
sudo chmod -R 755 /home/ubuntu/backend
sudo systemctl reload apache2  

Once resolved, refer to step Number 5 to restore the permissions and ownerships and recommended.

3. Admin dashboard static files not working. - copy the admin static files from assets folder to the static folder- Ensure you have run collectstatic command.
From the root directory: cp -r assets/admin/ static/

sudo systemctl reload apache2

In case of errors, inspect the logs by running the following command:

sudo tail -f /var/log/apache2/error.log

Part 2: Deploy React Js Application

Having deployed the backend, it is time now to deploy the front end. Ensure you update the API URLs with the updated links on your React JS application, then proceed to create a build of your React JS application. See a Guide here: Create a Production Build-React

#Run the following command to create a build of your project
npm run build
#This creates a build directory with a production build of your app

Zip the content of the build folder, upload and unzip the files under the path: /home/ubuntu/frontend. By default, if you upload the code under the path: /var/www/html which is the default root folder for Apache, the website should be accessible. Still, since we have uploaded it to a custom folder, we need to further update Apache configurations to read from the custom path.

Edit the Apache configuration for the front end.

sudo nano /etc/apache2/sites-enabled/000-default.conf
#update to the following
<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName example.com   #replace with IP or Domain name
    ServerAlias www.example.com

    DocumentRoot /home/ubuntu/frontend
    <Directory /home/ubuntu/frontend>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

OR 
#Create a new conf file and deactivate the default:
sudo nano /etc/apache2/sites-available/frontend.conf  #create a new file and add above code.
sudo a2dissite 000-default.conf   #deactivate the default apache conf file 
sudo a2ensite frontend.conf   #activate the new one.

The final step is to update the permissions of the new frontend root folder:

sudo chown -R www-data:www-data /home/ubuntu/frontend
sudo find /home/ubuntu/frontend -type d -exec chmod 755 {} \;
sudo find /home/ubuntu/frontend -type f -exec chmod 644 {} \;

At this stage, the react web application should be serving the Django API.

Make a donation to support us


Web Hosting and email hosting Packages


For web development services, SEO services, Digital marketing strategies, website set up services, web hosting and domain registration; contact Dynamic Technologies.


Related Content: