Deploying Django/Wagtail on Ubuntu with Gunicorn and Nginx

Deploy Django/Wagtail on Ubuntu with Gunicorn and Nginx

Introduction:

Have you ever wondered how to create amazing websites with Django or Wagtail? These are two of the most popular and versatile frameworks for web development in Python. But creating a website is only half of the battle. You also need to make sure that your website is public, can handle real-world traffic, and delivers fast and reliable performance. To do this you need to deploy your application. That’s where Gunicorn and Nginx come in. Gunicorn is a powerful tool that runs your Django and Wagtail applications behind the scenes. Let’s dive into how we can deploy our Django or Wagtail website with Gunicorn and Nginx.

Prerequisites:

Before diving into the deployment process, ensure that you have the following prerequisites in place:

  • A Linux server with SSH access.
  • Python and pip installed on the server.
  • A Django/Wagtail project ready for deployment.
  • Virtual environment for isolating project dependencies.

Step 1: Setting up the Virtual Environment

Start by SSH-ing into your Linux server and navigating to the project directory. Create a virtual environment to isolate the project dependencies. Make sure you clone or upload your code into the server for example. Also, make sure you inserted your server’s IP or website address in ALLOWED_HOSTS

home/ubuntu/websites/djangoexample

Step 1.1: First update the package list

sudo apt update

Step 1.2: Install Python & Pip

sudo apt install python3 python3-pip

Run pip3 --version and python3 --version to check if the installation is a success or not.

Step 1.3: Creating Virtual Environment & Installing dependencies

Go to your project directory and then run this command

cd "your_project_dir" python3 -m venv venv source venv/bin/activate

Then install the requirements.txt and install gunicorn. *If these commands are showing permission issues, then use sudo

pip install -r requirements.txt
pip install gunicorn psycopg2-binary

To make sure your static files are working properly do this in your setings.py or base.py

STATIC_URL = '/static/'
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

If you already migrated your project then skip to the next part or do this

python manage.py makemigrations
python manage.py migrate
python manage.py collectstatic

Step 2: Installing Gunicorn

Install Gunicorn using pip within your virtual environment:

pip install gunicorn
deactivate #deactive the virtual environment

Step 3: Configuring Gunicorn Socket

To run your website, you need a Gunicorn socket that starts when you boot your system and waits for requests. When someone visits your website, systemd will launch Gunicorn to serve the request.

To create the Gunicorn socket, open a new file with this command:

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

Now paste the codes below and save the file using CTRL+O

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

Now, open create a new service file with this command:

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

The file name should be the same as the socket file, but with .service instead of .socket. And now paste the code below inside this file:

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=your_username 
Group=www-data
WorkingDirectory=home/ubuntu/websites/djangoexample
ExecStart=home/ubuntu/websites/djangoexample/venv/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          textutils.wsgi:application

[Install]
WantedBy=multi-user.target

Here user is your username, to get your username you can run whoami command to see your username. The group is your web server’s group, for nginx it’s www-data. Replace your_username, home/ubuntu/websites/djangoexample, and djangoexample with your actual information.

Step 4: Starting and Enabling Gunicorn Service

Start and enable the Gunicorn service:

sudo systemctl start gunicorn 
sudo systemctl enable gunicorn
sudo systemctl restart gunicorn

Step 5: Nginx Configuration as reverse proxy

Check how you can install nginx in your server. Create a Nginx configuration file using this command:

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

And paste this inside the file

server {
    listen 80;
    server_name example.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root home/ubuntu/websites/djangoexample;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

Step 6: Testing and Restarting Nginx

Now test and activate the nginx config by this command

sudo nginx -t
sudo ln -s /etc/nginx/sites-available/djangoexample /etc/nginx/sites-enabled/
sudo systemctl restart nginx

Step 7: Additional Configuration (Optional)

  • Securing Traffic: Consider setting up SSL/TLS using Let’s Encrypt to encrypt communication between the client and the server. Check How to Install SSL.
  • Monitoring and Logging: Implement monitoring tools and check logs for debugging and performance optimization.

Congratulations! You have just learned how to launch your awesome website with Django or Wagtail on an Ubuntu server using Gunicorn and Nginx. Remember to use your own project details instead of the examples we gave you and check out the official docs for more tips and tricks on how to customize and secure your website. If you face any error you can contact me on my LinkedIn or Facebook.

Fathi-Rahman

About the Author

Fathi Rahman

A junior DevOps engineer with a passion for learning and improving his skills. Previously worked as a customer engineer at Prothom Alo, where I developed a keen interest in server management, coding, and DevOps. In my free time, I enjoys writing articles, learning.

Leave a Reply

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

Related Posts