Deploy A Django Application on Ubuntu 20.04 and Postgres¶
Step 1 — Installing Packages from the Ubuntu Repositories¶
sudo apt update
sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx curl
Install Postgres¶
sudo apt install postgresql postgresql-contrib
Creating users¶
sudo -u postgres psql
create database dbname;
create user myuser with encrypted password 'password';
grant all privileges on database mydb to myuser;
Quit the console
\q
Creating a virtual environment¶
sudo -H pip3 install --upgrade pip
sudo -H pip3 install virtualenv
Create project folder
cd /var/www
Clone your project from source control git clone https://giturl cd project_folder
Add Virtual Environment
virtualenv venv
source venv/bin/activate
Install Required packages
pip install -r requirements.txt
Set credentials in settings.py
Make migrations
python manage.py createsuperuser python manage.py collectstatic sudo ufw allow 8000 python manage.py runserver 0.0.0.0:8000 pip install gunicorn sudo chown[Service] User=currentuser Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application
[Install] WantedBy=multi-user.target
sudo chown> The first command changes the group ownership of the folder to that of
> the webserver. The second command gives members of the `www-data`
> group read, write, enter-directory rights, and the group `s` flag
> will ensure that any files that get created inside that directory take
> `www-data` as the group - so if you create a file as `myuser` the
> `www-data` user will have access.
[Learn more here](https://askubuntu.com/questions/244406/how-do-i-give-www-data-user-to-a-folder-in-my-home-folder)
## Start the socket
Enable the socket so that when a connection is made to it, it will start the gunicorn.service
sudo systemctl enable gunicorn.socket
Confirm that the socket started successfully by running
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /var/www/eac_rde_backend;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn_rde.sock;
}
} Create a symbolic link to the sites-enabled dir
sudo ln -s /etc/nginx/sites-available/projectname /etc/nginx/sites-enabled Test your Nginx configuration for syntax errors:
sudo nginx -t If no errors are reported, go ahead and restart Nginx:
sudo service nginx restart Delete the 8000 rule in the firewall settings since we no longer need it
sudo ufw delete allow 8000 Allow traffic via the 80 and 443 ports:
sudo ufw allow 'Nginx Full' ```
Sam