Deploying Django App on AWS EC2
Plan:
- Overview
- Project creation
- AWS registration — root and IAM users, permissions, security
- EC2 instance creation
- Amazon Linux SSH Access
- Cloning Repository To EC2 Instance
- Optional: Configuring GitHub SSH Keys
- Deploying Django Project on AWS EC2 Using Docker
- Deploying DEV and PROD versions at the same time — TODO
- Conclusion
Overview
Welcome to my article on deploying a Django application with Docker on an AWS EC2 instance.
This tutorial will walk you through the entire deployment process, making it straightforward and accessible. Even if you’re already familiar with the basics, you’ll find this guide useful for learning new tips and having a complete reference at your fingertips.
Primary focus of this guide is on the deployment steps, so you can get your Django app up and running in the cloud with ease.
What is AWS?
Amazon Web Services (AWS) is a cloud computing platform that provides a wide range of services including computing power, storage, and networking. AWS enables you to deploy and manage applications quickly and efficiently.
What is an EC2 Instance?
Amazon Elastic Compute Cloud (EC2) is a service that allows you to run virtual servers (instances) in the cloud. EC2 provides scalable computing capacity, making it ideal for running applications.
Why Use EC2?
- Control and Flexibility: EC2 provides full control over your computing resources, enabling you to configure and manage instances as needed.
- Elasticity: Easily scale your instances up or down based on demand, ensuring you have the right amount of resources at all times.
- Integration with Other AWS Services: EC2 integrates seamlessly with other AWS services like S3, RDS, and VPC, enhancing the capabilities of your applications.
- Variety of Instance Types: EC2 offers a wide range of instance types optimized for different use cases.
A brief explanation of the project
The goal of this tutorial is to demonstrate the deployment of a Django application, rather than teaching Django itself. Therefore, the project is kept as simple as possible.
This tutorial assumes that you already have Python 3.12 and Django 5.0.6 installed.
The project is a basic Django app for managing a library. The library has two primary models: Authors and Books. Each author can have multiple books, and each book is associated with a single author.
You can check out the project in my repository on GitHub: library-backend.
AWS Registration — root and IAM users, permissions, security
In this section, we will guide you through the process of registering for an AWS account, setting up root and IAM users, and understanding the importance of security when managing AWS accounts.
Step 1: Signing Up for an AWS Account
1. Navigate to the AWS Signup page to begin the registration process.
2. Provide your email address, password, and AWS account name. This account name will be used to identify your account within AWS.
3. Fill in your contact details, including your phone number and address. Choose whether the account will be used for personal or professional purposes.
4. Verify Your Identity. Provide your phone number and enter the verification code sent by AWS.
5. Enter Billing Information. Provide your payment details (note: AWS requires this even for the free tier).
6. Choose a Support Plan. AWS offers several support plans. For most users, the free Basic Support Plan will be sufficient to start with. You can upgrade this later if needed.
7. Complete the Registration. Follow the prompts to finish setting up your account. You will receive a confirmation email once your account is active.
Step 2: Understanding Root and IAM Users
- Root User: The root user is created during registration and has full access to all AWS services and resources. Use it only for account and service management tasks.
- IAM Users: AWS Identity and Access Management (IAM) allows you to create users with specific permissions. This enhances security by adhering to the principle of least privilege. Keep track of IAM user accounts, always remove them if they are not used.
Importance of Security:
- Enable Multi-Factor Authentication (MFA) for both root and IAM users.
- Create individual IAM users for each person accessing the account.
- Use strong, unique passwords and regularly rotate them.
- Regularly review IAM policies and permissions.
Step 3: Creating an IAM User
1. Go to AWS Management console and find IAM service. It might appear in recently visited, if not, look for it in the “search”.
2. Then inside IAM choose “Users” on the left panel and click “Create User”.
3. Go through user creation steps. Specify your user-name:
4. Set permissions. Select “Attach policies directly”. You will see there is a lot of permission policies to choose from, you can even create your own policy.
For our purposes and simplicity we will choose “AdministratorAccess” policy for our user. This policy provides full access to AWS services and resources. But, try not to use this policy for your users in production applications.
To be more restrictive you can search specifically for EC2 instance policies. For example, you can assign “AmazonEC2FullAccess” policy, and this will allow your IAM account to do everything with EC2 service, but nothing else with other services.
5. Finish user creation process with remaining step, click “Create User”:
After the user is created, you can’t access it right away. First thing to do is to enable console access for the user.
1. Select new created user, go to “Security credentials” and click “Enable console access”
2. Download .csv and keep it as secure as possible. General recommendation is that you do not even keep it on your machine.
The file’s format is as follows: User name,Password,Console sign-in URL
3. Sign out from your root account by choosing it on top right and clicking “Sign out”:
4. Go back to the signin console and this time choose IAM user
Account ID is the number of 12 digits from the third column of earlier saved credentials file.
5. On the next step enter your IAM user name and Password, that also can be found in credentials file:
6. After entering all these details, you should be able to access the console of your IAM account. You will notice that for some of the places the access is limited.
EC2 instance creation
In this section, we will go through the process of creating an EC2 instance, which is a virtual server in Amazon’s Elastic Compute Cloud (EC2) for running applications on the AWS infrastructure. EC2 provides scalable computing capacity, allowing you to quickly scale up or down based on your needs.
Introduction to EC2 and the Free Tier
Amazon EC2 (Elastic Compute Cloud) is a web service that provides resizable compute capacity in the cloud. It allows developers to launch virtual servers, configure security and networking, and manage storage. This flexibility makes it easy to deploy applications quickly.
AWS Free Tier: AWS offers a free tier to help new users get started with the cloud. As of today free tier in your first year includes:
- 750 hours of t2.micro (or t3.micro in the Regions in which t2.micro is unavailable) instance usage on free tier AMIs per month;
- 750 hours of public IPv4 address usage per month;
- 30 GiB of EBS storage;
- 2 million IOs;
- 1 GB of snapshots;
- 100 GB of bandwidth to the internet.
The free tier is ideal for exploring AWS services and building small applications without worrying about costs.
Creating an EC2 Instance
To create an EC2 instance, follow these steps:
1. From IAM user console go to search and find and select “EC2". This will lead you to EC2 Dashboard:
2. Select “Launch an instance” and you will see a huge form of different parameters for your instance.
- Name. Select the name for your instance.
- Application and OS Images. In the dropdown Amazon Machine Image you will see several options. For this tutorial, you can choose the Amazon Linux -> “Amazon Linux 2023 AMI”, which is eligible for the free tier.
- Instance type. Select the t2.micro instance type, which is eligible for the free tier. This instance type provides 1 vCPU and 1 GiB of memory, sufficient for small applications and testing.
- Key pair. Select “Create new key pair”, set name and choose following parameters:
After you click “Create key pair” the .pem file will be downloaded on your machine. Keep this file, it will be needed in further steps when accessing the instance.
- Network changes. For this tutorial no changes required.
- Configure storage. The default storage configuration for the AMI will be pre-selected. For the free tier, you can have up to 30 GiB of EBS storage. Adjust the storage size if necessary, but ensure it remains within the free tier limits.
3. After filling the configuration, click “Launch Instance”. It will initate a process of launching of your instance.
4. Go to your instance list by clicking “Instances” in the left panel and select your newly created instance.
5. It will take some time before you will be able to use it. Wait until the Instance state changes from “Pending” to “Running”:
6. Your instance is set up at this stage. Your Public IPv4 address or Public IPv4 DNS will be needed in the next step unit of this tutorial to access the instance.
Amazon Linux Access
In this section, we will guide you through the process of accessing your Amazon Linux EC2 instance from your local machine using SSH. This was tested on MacOS with M1 chip in Oh My Zsh terminal. But you can use standard MacOS terminal as well.
Connecting from local machine
We’ll cover the steps to use the downloaded .pem
file to establish a secure connection to your EC2 instance.
1. Move the .pem
sile to a secure socation:
mkdir -p ~/keys
mv ~/Downloads/your-key-pair.pem ~/keys/
2. Set the correct permissions for the .pem
file:
chmod 400 ~/keys/your-key-pair.pem
3. Connect to Your EC2 Instance Using SSH.
- To connect to your EC2 instance, you need the public DNS name or IP address of the instance. You can find this information in the EC2 Management Console under the “Instances” section.
- Open Terminal and use the
ssh
command to connect to your instance. Replaceyour-key-pair.pem
with the name of your key file,ec2-user
with the default username for your Amazon Linux instance, andyour-instance-public-dns
with the public DNS of your EC2 instance.
ssh -i ~/keys/your-key-pair.pem ec2-user@your-instance-public-dns
Now you should be connected to Amazon Linux terminal:
Connecting from browser
The is another way to connect to terminal, you can connect directly from browser.
1. For this simply click “Connect” button from your instance summary top right corner:
2. On the next page leave prefilled parameters and click “Connect”
3. You will see the same command prompt:
Cloning Repository To EC2 Instance
In this unit, we will go through installing Git on your AWS EC2 instance and cloning your GitHub repository via HTTPS. This setup allows you to get your code onto your EC2 instance easily.
The commands are launched in the instance to which you have already connected in previous unit.
Step 1: Install Git on Amazon Linux
Install Git using the following commands:
sudo yum update -y
sudo yum install git -y
Step 2: Clone Library Repository via HTTPS
1. Clone the Repository.
- On your EC2 instance, use the
git clone
command with the HTTPS URL of the repository discussed at the beginning of this tutorial.
git clone https://github.com/RusikPro/library-backend.git
2. Verify the Clone.
cd library-backend
ls -la
Optional: Configuring GitHub SSH Keys
If you prefer to clone your own repository via SSH for added security, follow these optional steps to generate an SSH key pair on your EC2 instance and add the public key to your GitHub account.
Step 1: Generate SSH Key Pair on EC2 Instance
1. Generate SSH Key Pair:
ssh-keygen -t ed25519 -C "your_email@example.com"
- Go through key creation steps.
- You are free to choose name by default, but for better management of keys in future it is better to customise them. In this tutorial the name is /home/ec2-user/.ssh/id_ed25519_tutorial_key
- Passphrase will be left empty for simplicity.
2. Copy the Public Key.
- Display the contents of your new public key file:
cat ~/.ssh/id_ed25519_tutorial_key.pub
- Copy the output, which starts with
ssh-ed25519
and includes your email address.
Step 2: Add SSH Key to Your GitHub Account
1. Log in to GitHub and navigate to your project.
2. Open settings of your project, choose “Deploy keys” in the left panel and click “.
3. Select name and in the key section insert earlier copied ed key.
4. Leave “Allow write access” not checked. You normally do not want to push changes from EC2 instance back to GitHub.
5. Click “Add key” and then you should be able to see your key in the list of Deploy keys.
Step 3: Start ssh-agent on EC2
- Launch ssh-agent inside EC2 instance:
eval "$(ssh-agent -s)"
- Add SSH key to the agent:
ssh-add ~/.ssh/id_ed25519_tutorial_key
- Append the following lines to the ~/.bashrc file for automatic launch of ssh-agent on the next access to EC2 instance:
# Start SSH agent if not already running
if [ -z "$SSH_AUTH_SOCK" ]; then
eval "$(ssh-agent -s)"
fi
# Add SSH key
ssh-add ~/.ssh/id_ed25519_choven
Summary
After following these steps you will be able to git clone your repository using SSH:
Deploying Django Project on AWS EC2 Using Docker
In this unit, we go through the process of installing Docker on your EC2 instance, and then using Docker to launch your cloned Django project. This will allow you to deploy your application efficiently.
Step 1: Install Docker on Amazon Linux
1. Install Docker via package manager.
sudo yum update
sudo yum install docker
docker info
Last command will show that docker service is not running.
2. Enable docker as a service.
sudo systemctl enable docker.service
sudo systemctl start docker.service
3. Add the ec2-user to the Docker Group.
sudo usermod -aG docker ec2-user
4. Log out and log back in to apply the group membership changes.
exit
ssh -i ~/keys/your-key-pair.pem ec2-user@your-instance-public-dns
5. Install docker-compose.
sudo curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
docker-compose version
Step 2: Configure Your Project
1. Navigate to your earlier cloned project. env.dev.sample file is there.
cd library-backend
2. Create new .env file from .env.dev.sample and open it.
cp .env.dev.sample .env
vim .env
3. Change the values inside.
DB_NAME=your_db
DB_USER=your_db_user
DB_PASS=your_complicated_password
DJANGO_SECRET_KEY=your_django_secret_key
# Public IPv4 address from EC2 instance console
DJANGO_ALLOWED_HOSTS=35.181.153.18
DJANGO_DEBUG=False
DJANGO_TEST_MODE=True
Note that DJANGO_ALLOWED_HOSTS you should put your public IPv4 address from EC2 instance console:
Step 3: Build and Run Your Docker Containers
1. Build your dockers using the following command.
docker-compose -f docker-compose-prod-deploy.yml build
You should see your docker container being built:
2. Run the Docker containers as daemon (-d).
docker-compose -f docker-compose-prod-deploy.yml up -d
3. Monitor logs.
docker-compose -f docker-compose-prod-deploy.yml logs -f
4. Access your website via public DNS. Note that by default the connection is set to HTTP, not HTTPS. So, before accessing the site, remove “s” from the URL:
http://ec2-35-181-153-18.eu-west-3.compute.amazonaws.com/api/health-check/
5. You can stop your instance using the following command.
docker-compose -f docker-compose-prod-deploy.yml down
6. Clear the unused docker instances time to time.
To save space on your disk, clear obsolete docker containers time to time using this command:
docker system prune
Troubleshooting
- Not being able to reach the site. If you have such issue:
it means that your proxy is not reachable from outside.
For this, go to the EC2 instance console and check Security tab:
If it is not the case, click on your security group (sg-0ca016958bb85b7e4 (launch-wizard-3)) and then “Edit inbound rules”.
You will be able to see different rules for inbound connections. Click “Add rule” and try to add HTTP with custom source 0.0.0.0/0:
After this you should be able to access the site.
Conclusion
Congratulations! You’ve successfully deployed a Django application using Docker on an AWS EC2 instance. Through this tutorial, we covered the essential steps to get your project up and running in the cloud. Here’s a quick recap of what we accomplished:
- Overview. We started by understanding the basics of AWS and EC2, and the advantages of using these services for deploying applications.
- Project Creation: We discussed the Django project setup, discussing the primary models and repository details.
- AWS Registration: We went through the steps to create an AWS account, set up root and IAM users, and emphasized the importance of security.
- EC2 Instance Creation. We created an EC2 instance, configured it with the necessary parameters, and ensured it falls within the AWS Free Tier limits.
- Amazon Linux SSH Access. We learned how to securely access the EC2 instance using SSH from a local machine and through the AWS Management Console.
- Cloning Repository to EC2 Instance. We installed Git on our EC2 instance and cloned the Django project repository using HTTPS. We also covered an optional step to set up GitHub SSH keys for secure access.
- Deploying Django Project on AWS EC2 Using Docker: We installed Docker on the EC2 instance, configured the project, built Docker images, and ran the Docker containers to deploy the Django application.
By following this tutorial, you now have a solid understanding of deploying a Django application to AWS EC2 using Docker. This setup ensures that your application is scalable and flexible.
Feel free to explore further improvements, such as setting up a CI/CD pipeline, enabling HTTPS for secure connections, or scaling your infrastructure based on demand. AWS provides a wide range of tools and services that can help you optimize and manage your deployments efficiently.
If you have any questions or encounter any issues, don’t hesitate to reach out in comments.
If this tutorial was helpful, I would be grateful for like and share.
Happy deploying !