Tuesday, January 14, 2025

 Here’s a comprehensive blog post that explains the process of setting up a Django project on an Oracle Cloud Free Tier instance using Nginx and Gunicorn, including socket file permissions management.


---


## **Setting Up a Django Project with Nginx and Gunicorn on Oracle Cloud (Free Tier)**


In this guide, we will walk through setting up a Django project on an Oracle Cloud Free Tier instance using Gunicorn as the application server and Nginx as the reverse proxy. We will also address how to handle socket file permissions for secure communication between Gunicorn and Nginx.


### **Prerequisites**

1. **Oracle Cloud Free Tier Instance**: Make sure you have an active Oracle Cloud instance running.

2. **Ubuntu Server**: This guide assumes you are using an Ubuntu-based system.

3. **Django Project**: You should already have your Django project setup. If not, create a Django project and make sure it's ready to deploy.

4. **Gunicorn & Nginx**: We’ll use Gunicorn to serve the Django application and Nginx as a reverse proxy to forward requests to Gunicorn.


---


### **Step 1: Install Required Packages**

To begin, install the required packages such as `python3.12-venv`, `git`, and `Gunicorn`:


```bash

sudo apt update

sudo apt install python3.12-venv git-all

```


Create and activate your virtual environment for the Django project:


```bash

python3.12 -m venv /home/ubuntu/orange-venv

source /home/ubuntu/orange-venv/bin/activate

```


Install your project dependencies inside the virtual environment, including `gunicorn`:


```bash

pip install gunicorn

```


---


### **Step 2: Configure Gunicorn for Your Django Project**


Create a Gunicorn systemd service to manage your application as a daemon.


Create a file for the Gunicorn service:


```bash

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

```


Add the following content:


```ini

[Unit]

Description=gunicorn daemon for Django project

After=network.target


[Service]

User=ubuntu

Group=www-data

WorkingDirectory=/home/ubuntu/orange

ExecStart=/home/ubuntu/orange-venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/orange/orange.sock orange.wsgi:application


[Install]

WantedBy=multi-user.target

```


Enable and start the Gunicorn service:


```bash

sudo systemctl start gunicorn

sudo systemctl enable gunicorn

```


---


### **Step 3: Configure Nginx to Proxy Requests to Gunicorn**


Edit the Nginx configuration for your Django project.


```bash

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

```


Add the following content:


```nginx

server {

    listen 80;

    server_name 129.154.249.103;  # Use your domain or public IP here


    # Proxy to Gunicorn via Unix socket

    location / {

        include proxy_params;

        proxy_pass http://unix:/home/ubuntu/orange/orange.sock;

    }


    # Serve static files

    location /static/ {

        alias /home/ubuntu/orange/static_root/;  # Adjust STATIC_ROOT in Django

    }


    # Optional: Serve media files if any

    location /media/ {

        alias /home/ubuntu/orange/media/;

    }

}

```


Create a symbolic link to enable the site:


```bash

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

```


Test the Nginx configuration:


```bash

sudo nginx -t

```


If the configuration test passes, restart Nginx to apply changes:


```bash

sudo systemctl restart nginx

```


---


### **Step 4: Collect Static Files**


Ensure you have collected all static files for Nginx to serve them. Run the `collectstatic` command:


```bash

python manage.py collectstatic

```


This will gather all static files in the directory defined by `STATIC_ROOT` in your `settings.py`.


---


### **Step 5: Manage Socket File Permissions**


The socket file (`orange.sock`) is used for communication between Gunicorn and Nginx. It is essential to set correct permissions for Gunicorn and Nginx to communicate securely.


#### Check Current Permissions:

You can check the socket file permissions with the `ls` command:


```bash

ls -l /home/ubuntu/orange/orange.sock

```


Output might look like this:


```plaintext

srwxrwx--- 1 ubuntu ubuntu 0 Jan 14 14:50 /home/ubuntu/orange/orange.sock

```


This means:

- **Owner (`ubuntu`)** has full permissions (read, write, execute).

- **Group (`ubuntu`)** has full permissions.

- **Others** have no permissions.


#### Change Group Permissions for Nginx:

Since Nginx typically runs under the `www-data` user, you need to ensure that `www-data` has access to the socket file. Change the group to `www-data`:


```bash

sudo chown ubuntu:www-data /home/ubuntu/orange/orange.sock

```


#### Add Nginx User to the Group:

Alternatively, you can add the `www-data` user to the `ubuntu` group so that it can access the socket file.


```bash

sudo usermod -aG ubuntu www-data

```


#### Restart Services:

After adjusting permissions, restart Gunicorn and Nginx:


```bash

sudo systemctl restart gunicorn

sudo systemctl restart nginx

```


---


### **Step 6: Verify the Setup**


Once everything is set up, verify that your Django project is running correctly:


1. Open your browser and navigate to your server's IP address (e.g., `http://129.154.249.103/`).

2. Check the static files by visiting a static resource (e.g., `http://129.154.249.103/static/style.css`).

3. If the website is not loading correctly, check the logs for errors:

   - **Gunicorn logs**: `sudo journalctl -u gunicorn`

   - **Nginx logs**: `sudo tail -f /var/log/nginx/error.log`


---


### **Troubleshooting Socket File Permissions**


Here’s how to adjust socket file permissions if you encounter issues:


1. **To change permissions of the socket file:**

   ```bash

   sudo chmod 660 /home/ubuntu/orange/orange.sock

   ```

   This grants read and write access to the owner and group but denies access to others.


2. **To change ownership of the socket file:**

   ```bash

   sudo chown ubuntu:www-data /home/ubuntu/orange/orange.sock

   ```


3. **To add or remove users from the group:**

   - **Add `www-data` to the `ubuntu` group**:

     ```bash

     sudo usermod -aG ubuntu www-data

     ```

   - **Remove `www-data` from the `ubuntu` group**:

     ```bash

     sudo gpasswd -d www-data ubuntu

     ```


---


### **Conclusion**


In this tutorial, we walked through setting up a Django project on Oracle Cloud using Gunicorn and Nginx. We also covered how to manage socket file permissions, ensuring that both Gunicorn and Nginx can securely communicate through the Unix socket. By following these steps, you can deploy Django on Oracle Cloud, ensuring secure and efficient communication between your application server and web server.