This guide empowers Django developers to master the art of deploying their applications on Digital Ocean. Discover step-by-step instructions, best practices, and tips for a seamless deployment experience, ensuring optimal performance and scalability
In this guide, we'll walk you through the process of deploying a Django demo app on Digital Ocean, one of the most popular cloud hosting providers. We'll cover setting up SSL for secure communication, configuring domain settings using either Google Domains or GoDaddy, and creating a new non-root user for enhanced security. For our setup, we'll be using SQLite as the default database, Apache2 as the web server, Git for version control, and a requirements.txt file for handling dependencies.
Before we dive into the deployment process, let's take a moment to understand why Django and Digital Ocean make a winning combination. Django, known for its pragmatic design and clean, reusable code, empowers developers to build complex web applications swiftly. Its batteries-included philosophy provides a wide range of built-in tools, enabling you to focus on your application's unique features rather than reinventing the wheel.
On the other hand, Digital Ocean stands out as a preferred hosting solution for many developers due to its user-friendly interface and cost-effective pricing. Whether you are a seasoned professional or a newcomer to server management, Digital Ocean offers a seamless experience for setting up and managing cloud servers, allowing you to concentrate on your Django app's performance and scalability.
Before proceeding with the deployment and update of your Django application on Digital Ocean, make sure you have the following:
Django App: Preparing Your Django App for Deployment
Digital Ocean Account: Sign up for a Digital Ocean account to create and manage virtual droplets (servers).
Git Repository: Your Django application should be hosted in a Git repository, like GitHub, Bitbucket, or GitLab.
Domain Name (Optional): If you want to use a custom domain for your application, you should have a registered domain name from either Google Domains or GoDaddy.
Basic Understanding of Django: Familiarity with Django web framework and its project structure is necessary to follow the deployment process.
SSH Key (Optional): Generating an SSH key pair is recommended for secure access to your Digital Ocean droplet.
Ubuntu 20.04 Droplet: Create a new droplet on Digital Ocean using the Ubuntu 20.04(x64) LTS distribution as the operating system.
Now that you have the prerequisites in place, let's proceed with the deployment and update process:
In this guide, we will be setting up the subsequent Django app: Food expiry app
DigitalOcean Sign Up If you don't have a DigitalOcean account yet, you can sign up using the link below and receive $200 credit for 60 days to get started:
Start your free trial with a $200 credit for 60 days
(Note: This is a referral link, meaning both you and I will get credit.)
To ensure a smooth deployment process, it's essential to prepare your Django application adequately. Let's take a look at some of the key steps involved:
In Django, static files such as CSS, JavaScript, and images need to be served separately from dynamic content. To achieve this, we use the collectstatic
command, which gathers all static files from various locations in your Django project and places them in a single directory.
python manage.py collectstatic
For example, if you have a CSS file named styles.css
in your app's static/css
directory, running collectstatic
will place it in the STATIC_ROOT
directory (specified in your settings), making it accessible to the webserver.
During development, you might have used a local database like SQLite. In the production environment, it's crucial to use a more robust database system like PostgreSQL or MySQL. Update your Django project's settings to use the appropriate database backend and connection settings.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'your_database_name',
'USER': 'your_database_user',
'PASSWORD': 'your_database_password',
'HOST': 'localhost',
'PORT': '',
}
}
For example, if you are using PostgreSQL, you need to install the necessary package on your server:
Install the dependencies to use PostgreSQL with Python/Django:
sudo apt update
sudo apt-get -y install build-essential libpq-dev python-dev
Install the PostgreSQL Server:
sudo apt-get -y install postgresql postgresql-contrib
Adjust your Django settings for optimal performance in a production environment. Set DEBUG
to False
, update the ALLOWED_HOSTS
with your server's IP or domain name, and consider using a caching mechanism like Redis to speed up your app.
DEBUG = False
ALLOWED_HOSTS = ['your_server_ip', 'your_domain.com']
Additionally, consider using Gunicorn or uWSGI as the application server in front of your Django app to handle incoming web requests. These servers are designed for production use and can provide better performance and scalability than Django's built-in development server.
Keep sensitive information, such as secret keys and API credentials, secure by using environment variables. You can use the python-decouple
library to read environment variables from a .env
file.
pip install python-decouple
In your Django settings:
from decouple import config
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
This way, you can store sensitive information in the .env
file on your server, separate from your codebase.
Setting up your Digital Ocean account is straightforward, and we'll guide you through the process. Follow these steps:
Once you've made your decision, take action by clicking on the magical "Create" button. Witness the birth of your newly minted droplet as it gracefully appears in your profile.
Upon receiving the root password through email, proceed by selecting the appropriate IP Address to access the server via SSH:
ssh root@64.227.168.26
Upon your initial login, you'll be prompted to modify the root password.
For Unix-like OS users, you can access the server using the terminal. Meanwhile, if you are using Windows, you may opt to download PuTTY.
Alternatively, you have the option to use Digital Ocean's console if that suits your preference:
This way, you can conveniently manage your server through the method that best fits your setup.
ssh root@your_droplet_ip
adduser your_username
for limited user : create/add user for limited privillages:
root@localhost:~# adduser jai
Adding user `jai' ...
Adding new group `jai' (1000) ...
Adding new user `jai' (1000) with group `jai' ...
Creating home directory `/home/jai' ...
Copying files from `/etc/skel' ...
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for jai
Enter the new value, or press ENTER for the default
Full Name []: jai
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n] y
root@localhost:~#
usermod -aG sudo your_username
PermitRootLogin no
, and restart SSH: sudo service ssh restart
.sudo apt update && sudo apt upgrade
sudo apt install apache2
sudo ufw allow OpenSSH && sudo ufw enable
sudo apt install git
cd /var/www
git clone https://github.com/django/django.git demo_app
To transfer files from your local machine to the droplet using scp, follow these steps:
Open your terminal or command prompt on your local machine.
Use the scp command with the source file or directory and the destination on the droplet:
scp -r /path/to/your/local/project username@droplet_ip:/path/on/droplet
Replace /path/to/your/local/project
with the path to your Django project files on your local machine.
Replace username
with your droplet's username, droplet_ip
with the droplet's IP address, and /path/on/droplet
with the directory path on the droplet where you want to copy the files.
Enter your droplet's password or use your SSH key if prompted.
The files will be securely copied to the droplet, and you can now access your Django project on the server.
sudo apt install python3 python3-pip
sudo apt install python3-venv
python3 -m venv myenv
source myenv/bin/activate
root@demo-host-name % source venv/bin/activate
(venv) jai@demo-host-name %
To switch to the PostgreSQL user, open your terminal and enter the following command:
su - postgres
Once you are logged in as the PostgreSQL user, you can create a new database user and the corresponding application database. Let's assume the new user is called username
and the database is named dbname
.
To create the user, run the following command:
createuser username
Next, let's create the application database dbname
and set username
as the owner:
createdb dbname --owner username
Now, we need to set a password for the newly created user username
. We will use '123' as an example password, but it's essential to choose a strong and secure password in a real scenario.
psql -c "ALTER USER username WITH PASSWORD '123'"
Note: Please ensure to pick a strong and secure password for your application in practice. The usage of '123' here is only for simplicity's sake.
To return to the root user, simply use the following command:
exit
After following these steps, you should have a PostgreSQL database configured with a new user (username
) and database (dbname
) ready for your application's use.
cd /var/www/demo_app
pip install -r requirements.txt
python manage.py migrate
python manage.py createsuperuser
sudo nano /etc/apache2/sites-available/demo_app.conf
your_domain.com
with your domain):<VirtualHost *:80>
ServerName your_domain.com
ServerAdmin your_email
Alias /static /var/www/demo_app/static
<Directory /var/www/demo_app/static>
Require all granted
</Directory>
<Directory /var/www/demo_app/demo>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess demo_app python-home=/var/www/demo_app/myenv python-path=/var/www/demo_app/demo
WSGIProcessGroup demo_app
WSGIScriptAlias / /var/www/demo_app/demo/wsgi.py
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
sudo a2ensite demo_app
sudo service apache2 reload
1. Visit this link: To get started with Let's Encrypt and learn more about their services, please visit the official Let's Encrypt website by clicking on the following link: Let's Encrypt.
2. Install Let's Encrypt Certbot on Ubuntu with Apache: If you are using Ubuntu Focal Fossa and Apache as your web server, you can obtain and install Let's Encrypt certificates using Certbot. To do this, follow the instructions provided on the Certbot website. Click on the following link to access the guide for installing Let's Encrypt Certbot on Ubuntu with Apache: Certbot - Let's Encrypt - Ubuntu Focal Fossa - Apache.
Feel free to explore the links and follow the instructions to secure your website with Let's Encrypt certificates.
sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d your_domain.com
1. Log in to your Google Domains account.
2. Go to the DNS management page for your domain.
3. Add an "A" record with your Droplet's IP address.
Example: Suppose your Droplet's IP address is 203.0.113.45, and you want to point the main domain "example.com" to your Droplet. You would add an "A" record like this:
4. Add a "CNAME" record for the "www" subdomain (if desired) pointing to your domain.
Example: If you want to create a "www" subdomain that points to the main domain "example.com," you would add a "CNAME" record like this:
1. Log in to your GoDaddy account.
2. Access the DNS management page for your domain.
3. Add an "A" record with your Droplet's IP address.
Example: Suppose your Droplet's IP address is 203.0.113.45, and you want to point the main domain "example.com" to your Droplet. You would add an "A" record like this:
4. Add a "CNAME" record for the "www" subdomain (if desired) pointing to your domain.
Example: If you want to create a "www" subdomain that points to the main domain "example.com," you would add a "CNAME" record like this:
Let's Encrypt certificates automatically renew every 90 days. You can check the status with: sudo certbot renew --dry-run
sudo service apache2 restart
your_domain.com
) in a web browser to see the Django demo app in action!Ref Link for Linux Commands:
Reference Link : Comprehensive Linux Tutorial for Beginners with Linux Distro List [Link]
Congratulations! You've successfully deployed the Django demo app on Digital Ocean with SSL, domain configuration through Google Domains or GoDaddy, and enhanced security using a non-root user. Your web project is now accessible securely through your custom domain. Keep exploring Django and building amazing web applications. Happy coding!
DigitalOcean Sign Up : If you don't have a DigitalOcean account yet, you can sign up using the link below and receive $200 credit for 60 days to get started: Start your free trial with a $200 credit for 60 days link below: Get $200 free credit on DigitalOcean ( Note: This is a referral link, meaning both you and I will get credit.)
👩💻🔍 Explore Python, Django, Django-Rest, PySpark, web 🌐 & big data 📊. Enjoy coding! 🚀📚