# Deploy Django App
Will show you how to deploy a Django application on Ubuntu server. The server can be run from any hosting provider, if you can access via ssh - you can follow along with these commands.
# Getting project ready
Start by adding the allowed domains in your settings file. Assuming you are deploying to a named domainn.
ALLOWED_HOSTS = [
........
'yourdomain.com',
'www.yourdomain.com',
.........
]
We will deploy using gunicorn, so you need to make sure it is installed inside of your virtual environment
pip install gunicorn
Test Gunicorn is installed correctly:
gunicorn --bind 0.0.0.0:8000 yourproject.wsgi
Deactivate
deactivate
# Create System and Service File
Start by creating systemd socket file
sudo nano /etc/systemd/system/gunicorn.socket
Paste inside the file
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target
Create a service file for gunicorn
sudo nano /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=yourusername
Group=www-data
WorkingDirectory=/home/yourusername/path-to-your-projectdir
ExecStart=/home/yourusername/path-to-your- projectdir/yourprojectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
yourproject.wsgi:application
[Install]
WantedBy=multi-user.target
Check everything is correct in the file, then run:
sudo systemctl start gunicorn.socket
sudo systemctl enable gunicorn.socket
Check status
sudo systemctl status gunicorn.socket
sudo systemctl status gunicorn
# Configure nginx to serve Django app
sudo apt update
sudo apt install nginx
Create new server block for your project
sudo nano /etc/nginx/sites-available/yourproject
Inside the file
server {
listen 80;
listen [::]:80;
server_name yourdomain.com www.yourdomain.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/yourusername/path-to-youprojectdir;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
Enable the file
sudo ln -s /etc/nginx/sites-available/yourproject /etc/nginx/sites-enabled
Check configuration
sudo nginx -t
Restart Nginx
sudo systemctl restart nginx
Allow Nginx Firewall
sudo ufw allow 'Nginx Full'
# Secure your website with Certbot
We need to install certbot before we get started, if you already have certbot installed, you can skip this.
sudo apt-get update
sudo apt install python3-certbot-nginx
Install the certificate
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com