# Python Flask app Deployment on EC2 with CodePipeline

## Introduction

Efficiency and reliability are paramount when deploying web applications. AWS CodePipeline, when coupled with Amazon EC2, offers a robust solution for automating deployment workflows.

### **Prerequisites**

Ensure you have the following:

* An AWS account with access to CodeCommit, CodeDeploy, CodePipeline, and EC2 instances.
    
* A Flask application ready for deployment. If you don't have one, you can use [Flasklingo (a text translation app)](https://hashnode.com/post/clove91yb000408l6fq3e3xoo) which you can clone from my github repo [Flasklingo](https://github.com/codewithsky-in/flasklingo) or create a simple "Hello World" app.
    

## Let's Get Started

### **Step 1: Set Up IAM Role**

Create an IAM role for ec2 and codedeploy with CodeDeploy permissions and attach it to the EC2 instance.

Note : If you are doing this after the launching ec2 instance make sure you reboot the instance for the IAM role to be active

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710003230849/5e02fccd-0515-4d06-9199-5b56e0ae107f.png align="center")

### **Step 2: Launching an EC2 Instance**

Deploy an Ubuntu t2.micro instance.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710005874027/6ccf0a6f-1bdd-44df-88ca-b4e775f5caf1.png align="center")

### **Step 3: Configure EC2 Instance**

Connect to the EC2 instance via SSH or directly from console, then:

* Install CodeDeploy agent.
    
    ```bash
    sudo apt-get update
    sudo apt-get install ruby-full ruby-webrick wget -y
    cd /tmp
    wget https://aws-codedeploy-us-east-1.s3.us-east-1.amazonaws.com/releases/codedeploy-agent_1.3.2-1902_all.deb
    mkdir codedeploy-agent_1.3.2-1902_ubuntu22
    dpkg-deb -R codedeploy-agent_1.3.2-1902_all.deb codedeploy-agent_1.3.2-1902_ubuntu22
    sed 's/Depends:.*/Depends:ruby3.0/' -i ./codedeploy-agent_1.3.2-1902_ubuntu22/DEBIAN/control
    dpkg-deb -b codedeploy-agent_1.3.2-1902_ubuntu22/
    sudo dpkg -i codedeploy-agent_1.3.2-1902_ubuntu22.deb
    systemctl list-units --type=service | grep codedeploy
    ```
    
* Ensure the CodeDeploy agent is active.
    
    ```bash
    sudo service codedeploy-agent status
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710006073171/6904b882-a734-48ed-9dea-9619318e8340.png align="center")
    
* Install Python venv, tesseract and Gunicorn.
    
    ```bash
    sudo apt install python3.10-venv -y
    sudo apt install tesseract-ocr -y
    sudo apt-get install gunicorn -y
    ```
    

### **Step 4: Configure Nginx**

Create an Nginx service for the application and make sure the service is running.

```bash
sudo apt-get install nginx -y

sudo apt-get install libgl1-mesa-glx -y

sudo systemctl start nginx.service

sudo systemctl status nginx.service
```

### **Step 5: Set Up and enable Flasklingo service**

```bash
cd /etc/systemd/system/

sudo nano flasklingo.service

# this is the code for the service and save the file

[Unit]
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory= /var/www/flasklingo
ExecStart=/var/www/flasklingo/venv/bin/gunicorn --bind localhost:5000 main:app 
Restart=always
[Install]
WantedBy=multi-user.target
```

```bash
# Reload systemd to read the new unit file
sudo systemctl daemon-reload  
# Enable the service to start on boot
sudo systemctl enable flasklingo.service  
# Start the service
sudo systemctl start flasklingo.service
```

### **Step 6 : Setup reverse proxy**

setup an upstream for your app and configure a reverse proxy for your app

```bash
upstream flasklingo {
    server 127.0.0.1:5000;
}

server {
        listen 80 default_server;
        listen [::]:80 default_server;
       	root /var/www/flasklingo;

        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
       
        proxy_connect_timeout 75s;
        proxy_pass http://flasklingo;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        }
}
```

the sites enabled will be automatically updated or else use the below command

```bash
sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled
```

### **Step 7: Set Up CodeCommit**

Create a repository in CodeCommit and add [main.py](http://main.py), requirements.txt, and an appspec file or add your own files.

### **Step 8: Configure CodeDeploy**

* Set up a deployment application in CodeDeploy.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710002738611/61b11480-0785-40ee-8cf5-3d12a42438fe.png align="center")
    
    Create a application by selecting EC2/On-premises with your desired Application name
    
* Create a deployment group.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710261719463/e41bd514-5186-4903-b1ed-35a47abf4c98.png align="center")

### **Step 9: Set Up CodePipeline**

Create a pipeline in CodePipeline:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710261753178/4b71847f-2ef8-429b-9870-057e5c24c1a3.png align="center")

* Connect to the CodeCommit repository.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710261784282/7475b8bb-ab66-4680-825c-d7491b53fe7a.png align="center")

* Skip the build stage
    
* Add a Deploy stage with codedeploy as provider.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710261855036/3fc77631-2545-426d-9b69-11a91f8e62da.png align="center")

Review and click create pipeline.

By following these steps, you'll establish an efficient and reliable deployment workflow using AWS CodePipeline and Amazon EC2.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710267235035/dd6eeb63-b11d-42d1-99f4-67cf44089755.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710267246128/a802339f-5f2a-4513-80ec-9563f6141787.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710267252912/fd62a448-04cb-473b-bf10-945df64871cb.png align="center")

### **Conclusion:**

CodePipeline stands out as a powerful and versatile tool for streamlining software delivery pipelines. Its integration with various AWS services, such as CodeBuild and CodeDeploy, allows for automated building, testing, and deployment of applications with ease. By adopting CodePipeline, development teams can achieve faster release cycles, improved code quality, and increased collaboration among team members. Its scalability and flexibility make it an ideal choice for modern software development workflows, empowering organizations to deliver high-quality software efficiently and consistently. Embracing CodePipeline not only enhances development processes but also contributes to overall business agility and competitiveness in today's dynamic market landscape.

**Note**:  
Destroy all running ec2 instances if you don't want to occur any extra charges
