3-how-to-deploy-a-flask-api-on-aws-using-docker-and-cicd-pipelines.html

How to Deploy a Flask API on AWS Using Docker and CI/CD Pipelines

In the world of web development, deploying your applications efficiently is just as crucial as building them. Flask, a lightweight Python web framework, is a popular choice for creating APIs, and when combined with Docker and AWS, it provides a powerful platform for deployment. In this article, we will walk you through the steps to deploy a Flask API on AWS using Docker and Continuous Integration/Continuous Deployment (CI/CD) pipelines.

What is Flask?

Flask is a micro web framework for Python designed to make it easy to build web applications quickly. It is lightweight and modular, allowing developers to choose the components they need. Flask is particularly popular for creating RESTful APIs, making it an excellent choice for modern web applications.

Why Use Docker?

Docker is a platform that allows developers to package applications and their dependencies into containers. This ensures that applications run consistently across different environments. Here are some benefits of using Docker for your Flask API:

  • Isolation: Each application runs in its own container, which eliminates conflicts between dependencies.
  • Scalability: Docker containers can be easily scaled up or down based on demand.
  • Portability: Docker containers can run on any system that supports Docker, making deployment straightforward.

Setting Up Your Flask API

Before deploying your Flask API, you need to create a simple application. Here’s a minimal example:

Step 1: Create a Flask Application

Create a directory for your project and navigate into it:

mkdir flask-api
cd flask-api

Next, create a file named app.py and add the following code:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api', methods=['GET'])
def hello_world():
    return jsonify(message="Hello, World!")

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Step 2: Create a Requirements File

Create a file named requirements.txt to manage your dependencies:

Flask==2.0.1

Step 3: Create a Dockerfile

Now, let’s create a Dockerfile to containerize your Flask application. Create a file named Dockerfile in the same directory:

# Use the official Python image from the Docker Hub
FROM python:3.9-slim

# Set the working directory
WORKDIR /app

# Copy the requirements file and install dependencies
COPY requirements.txt requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application code
COPY app.py app.py

# Expose the port on which the app runs
EXPOSE 5000

# Command to run the application
CMD ["python", "app.py"]

Step 4: Build the Docker Image

To build the Docker image, run the following command in the terminal:

docker build -t flask-api .

Step 5: Run the Docker Container

You can run your container using the command:

docker run -p 5000:5000 flask-api

Your Flask API should now be accessible at http://localhost:5000/api.

Deploying on AWS

Now that your Flask API is containerized, the next step is to deploy it on AWS. We'll use Amazon Elastic Container Service (ECS) for this purpose.

Step 6: Push Docker Image to Amazon ECR

  1. Create a repository in Amazon ECR: Go to the AWS Management Console, navigate to ECR, and create a new repository.

  2. Authenticate Docker to your ECR registry:

bash aws ecr get-login-password --region <your-region> | docker login --username AWS --password-stdin <your-account-id>.dkr.ecr.<your-region>.amazonaws.com

  1. Tag your Docker image:

bash docker tag flask-api:latest <your-account-id>.dkr.ecr.<your-region>.amazonaws.com/flask-api:latest

  1. Push the image to ECR:

bash docker push <your-account-id>.dkr.ecr.<your-region>.amazonaws.com/flask-api:latest

Step 7: Create an ECS Cluster and Task Definition

  1. Create an ECS Cluster: In the ECS Console, create a new cluster (choose "Networking only" for Fargate).

  2. Create a Task Definition: Define a new task that uses your Docker image from ECR. Specify the container port as 5000 and the memory and CPU settings as needed.

  3. Run the Task: Launch the task in your cluster.

Step 8: Set Up CI/CD with AWS CodePipeline

  1. Create a CodePipeline: In the AWS Console, navigate to CodePipeline and create a new pipeline.

  2. Source Stage: Connect your pipeline to a source repository (like GitHub) where your Flask API code resides.

  3. Build Stage: Use AWS CodeBuild to build your Docker image. A sample buildspec.yml file could look like this:

```yaml version: 0.2

phases: pre_build: commands: - echo Logging in to Amazon ECR... - $(aws ecr get-login --no-include-email --region $AWS_DEFAULT_REGION) build: commands: - echo Build started on date - docker build -t flask-api . - docker tag flask-api:latest .dkr.ecr..amazonaws.com/flask-api:latest post_build: commands: - echo Pushing the Docker image... - docker push .dkr.ecr..amazonaws.com/flask-api:latest ```

  1. Deploy Stage: Set up deployment to your ECS service.

Conclusion

Deploying a Flask API on AWS using Docker and CI/CD pipelines enhances your workflow by automating deployment and ensuring consistency across environments. With the steps outlined in this guide, you can set up a robust deployment strategy that scales with your application's needs.

Whether you are building a simple API or a complex service, mastering these tools will significantly streamline your deployment process. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.