DEV Community

Cover image for Hosting a Django website on EC2
Waji
Waji

Posted on • Edited on

Hosting a Django website on EC2

Introduction

I have always wanted to deploy a website on my own web server. However, owning a small PC or a laptop just to use as a Linux server was quite bothersome. To assist my laziness, Amazon provides a very smooth service as to what we refer as the 'cloud'. I am pretty sure that almost everyone has at least heard of the word 'cloud' in today's world. In this post, I will be using the Amazon cloud elsewise called the AWS (Amazon Web Services) to host my django website on its EC2 instance.

EC2 Instance

Well according to Amazon themselves, Amazon Elastic Compute Cloud (Amazon EC2) provides scalable computing capacity in the Amazon Web Services (AWS) Cloud.

EC2 instances are virtual machines that run on the Amazon Web Services (AWS) infrastructure. So yeah now you don't need to physically have a web server in your room to host your own website!

Another attractive trait is that EC2 instances are created from Amazon Machine Images (AMIs), which are pre-configured virtual machine images. This means that you don't even need to install a Linux or maybe Windows server yourself! Enough talk, I will now go straight into how to actually do this πŸ˜‰

If you don't have an account with the AWS cloud, I would recommend you to create one. You can check this article and follow the steps if you are pretty new with the cloud: https://k21academy.com/amazon-web-services/aws-solutions-architect/create-aws-free-tier-account/

Creating an EC2 Instance

Yes, we need to create the server first. But no worries, it is quite simple and will take few clicks.

Once you are logged in to your AWS console, you will be able to see countless services under "services" bar.

Services

No need to panic as we are only looking at one and that is the EC2 instance service.

Once you click on the "EC2", you will redirected to the EC2 dashboard which should look like this

EC2 Dashboard
πŸ‘‰ Just a note that I already have a web server running so that is why it is showing 1 against "Instances(running)"

Right under this table, you should be able to see "Launch instance"

Launch instance

Once you are in, there will be an option to name your instance, choose an AMI, the operating system image that you want to run on your instance.

Name and AMI
You can choose whatever but just be careful as some images cost you

free
βœ”free tier eligible

Paid
❌Not free!

Once you have chosen your OS image you will be greeted to choose an instance type. The default option would probably be the Free tier compatible t2.micro instance

t2.micro

Now, we need a key pair. This is used for SSH-ing to your EC2 instance. Proceeding without a key pair isn't recommended but it is possible to select none.

Key

Next comes the network settings from where you can choose your VPC (Virtual Private Cloud)

VPC

Inside this network setting, there is very important thing you need to set up, the firewall

Firewall
In the AWS world, these are called 'security groups'. As you can see that the name and description along with SSH port 22 inbound rule is set by default.

I will add a Custom TCP port 8000 and a HTTP port 80 allowed from anywhere rule so that we can actually test our django website running

Security

You can always limit the IP address to whatever range or specific IP addresses as you like

And this is it. You can just click on "Launch Instance".

You can see that your instance is running

running

You can now access your instance using SSH or directly via AWS console.

Deploying your django website

This is the interesting part now. Once you are in your instance it is time to install the apache server and related tools

sudo apt-get update
Enter fullscreen mode Exit fullscreen mode
sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3
Enter fullscreen mode Exit fullscreen mode

The first command is to update apt package manager in Ubuntu. The second command installs apache2, pip3, and mod-wsgi(module used in Apache, for running Django server, and will be enabled automatically upon installation)

We will also need the virtual env to help with dependencies

sudo pip3 install virtualenv
Enter fullscreen mode Exit fullscreen mode

Creating an empty directory

mkdir django
Enter fullscreen mode Exit fullscreen mode

Now inside this directory I will be setting up the virtualenv as well as cloning my website from Github

cd django
Enter fullscreen mode Exit fullscreen mode
virtualenv myprojectenv
git clone "https://github.com/<username>/<repository name>.git" 
Enter fullscreen mode Exit fullscreen mode

Activating the virtualenv

source myprojectenv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Once the virtualenv is activated, we have to collect static files. For this, we need to use the vim editor

sudo vi config/settings.py
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰config is the project name that contains the settings.py

Once we are inside the settings.py, we just need to add this line at the end

import os

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATICFILES = [STATIC_ROOT]
Enter fullscreen mode Exit fullscreen mode

Also, we need to allow the instance's public IP address as well

ALLOWED_HOSTS=['EC2 Public IP address']
Enter fullscreen mode Exit fullscreen mode

Finally, as we are deploying in the production environment, we need to set debug to false

DEBUG = False
Enter fullscreen mode Exit fullscreen mode

This is it for the settings.py file

Installing the required modules with the pip command

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ if your repository doesn't have a requirements.txt file, please ensure that you have all of the dependencies installed

Migrating the database and collecting static file with the following

python manage.py makemigrations

python manage.py migrate

python manage.py collectstatic
Enter fullscreen mode Exit fullscreen mode

This will allow you to actually see your django website running if your run your django local server with the port 8000. However, this is not the optimal way as you don't want to use that. Instead, we want our website to run on the Apache server

Apache Server Configuration

We just need to tweak the configuration file that's all πŸ˜‰. To access the config file for apache,

sudo vi /etc/apache2/sites-available/000-default.conf
Enter fullscreen mode Exit fullscreen mode

Just need to replace the file contents with this

<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /static /home/ubuntu/django/Test/static
<Directory /home/ubuntu/django/Test/static>
Require all granted
</Directory>
<Directory /home/ubuntu/django/Test/config>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIPassAuthorization On
WSGIDaemonProcess Test python-path=/home/ubuntu/django/Test/  python-home=/home/ubuntu/django/myprojectenv
WSGIProcessGroup Test
WSGIScriptAlias / /home/ubuntu/django/Test/config/wsgi.py
</VirtualHost>
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ As mentioned before, the config is the project name and Test is repository name that I cloned. You will have to make sure the paths are correct and according to naming of directories and files in the Django project

And the configuration is done! But not so fast, there are some final touches.

Changing some permissions and ownership of the directory

chmod 664 ~/django/Test/db.sqlite3

sudo chown :www-data ~/django/Test/db.sqlite3
sudo chown :www-data ~/django/Test
sudo chown :www-data ~/django/Test/config
Enter fullscreen mode Exit fullscreen mode

And this is it! You just need to restart the apache service and you are good to go πŸ˜‰

Access your website over the internet using the EC2 instance's public IP address βœ”

sudo service apache2 restart
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ If for some reason the above gives a permission error, you can try giving 755 permissions to the ~ directory

sudo chmod 755 /home/ubuntu
Enter fullscreen mode Exit fullscreen mode

Conclusion

This was only an illustration of how to set up Apache and Django on AWS

When installing a production server, a number of additional variables are involved

Security is one of the most crucial aspects to pay attention to

We can restrict access to the server to a small number of IP addresses, which is great for testing and development

AWS technologies like Security Groups and IAM users can be useful for all of these uses

Final note that Django programs may be more easily deployed by using the AWS Beanstalk service

Top comments (0)