{{announcement.body}}
{{announcement.title}}

Deploying a Django Application to AWS EC2 Instance With Docker

DZone 's Guide to

Deploying a Django Application to AWS EC2 Instance With Docker

In AWS we have several ways to deploy Django (and not Django applications) with Docker. We can use ECS or EKS clusters. If we don't have one ECS or Kubernete...

· Web Dev Zone ·
Free Resource

In AWS, we have several ways to deploy Django (and not Django applications) with Docker. We can use ECS or EKS clusters. If we don't have one ECS or Kubernetes cluster up and running, maybe it can be complex. Today, I want to show how deploy a Django application in production mode within a EC2 host. Let's start.

The idea is create one EC2 instance (one simple Amazon Linux AMI AWS-supported image). This host doesn't initially have Docker installed. We need to install it. When we launch one instance, when we're configuring the instance, we can specify user data to configure an instance or run a configuration script during launch.

We only need to add this shell script to set up Docker:

Shell


We also need to attach one IAM role to our instance. This IAM role only need to allow us the following policies:

  • AmazonEC2ContainerRegistryReadOnly (because we're going to use AWS ECR as container registry).
  • CloudWatchAgentServerPolicy (because we're going to emit our logs to Cloudwatch).

Also, we need to set up a security group to allow incoming SSH connections to port 22 and HTTP connections (in our example to port 8000).

When we launch our instance, we need to provide a key-pair to connect via ssh. I like to put this key-pair in my .ssh/config:

Plain Text


To deploy our application we need to follow those steps:

  • Build our Docker images.
  • Push our images to a container registry (in this case ECR).
  • Deploy the application.

I've created a simple shell script called deploy.sh to perform all tasks:

Shell


This script assumes that there's a deploy.env file with our personal configuration (AWS profile, the host of the EC2, instance, the ECR, and things like that):

Plain Text


In this example, I'm using Docker Swarm to deploy the application. I want to play also with secrets. This dummy application doesn't have any sensitive information, but I've created one "ec2.supersecret" variable

Shell


That's the docker-compose.yml file:

YAML


And that's all. Maybe ECS or EKS are better solutions to deploy docker applications in AWS, but we also can deploy easily to one docker host in a EC2 instance that it can be ready within a couple of minutes.

Topics:
aws, django, docker, ec2, kubernetes, python, web dev

Published at DZone with permission of Gonzalo Ayuso , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}