Open In App

How to Deploy a Flask Web Server in Docker Container using AWS?

Last Updated : 28 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the current digitized era, web servers are essential as they stand for various online applications and sites. Web servers run stealthily the scenes to give the devices needed information and functional facilities irrespective of whether surfing on the internet, using a mobile app, or cloud facilities.

In this article, we will guide you through how to host your Dockerized Flask Web Server on AWS and make your application available to users globally.

What is Docker?

Docker serves as a platform that simplifies the process of developing, distributing, and running applications by utilizing containers. These containers act as self-contained packages that encompass all the elements required for running an application, including the code, runtime environment, system tools, libraries, and configurations. With Docker’s assistance developers can package their applications along, with their dependencies into containers. This enables effortless movement and deployment across environments, like development, testing, and production.

Why to Use Docker?

Docker simplifies the process of deploying web servers by packaging your application and its components into containers. These containers are lightweight and flexible. Ensure consistency across environments. Dockers versatility enables scaling of your web server, managing dependencies effectively. Streamlining development and deployment processes.

In the software industry we often encounter the problem of “It works on my system but not on yours.” However Docker provides a solution, for this. By containerizing the web server application, all necessary dependencies and environments are enclosed in an environment that can be executed on any platform, like the tested environment without encountering any issues.

What is AWS Fargate?

AWS Fargate is a component offered by Amazon Web Services (AWS) that enables serverless computing. It allows you to effortlessly run containers without the hassle of managing the underlying infrastructure. With Fargate you can focus on deploying and scaling your containerized applications while AWS takes care of server provisioning, scaling and maintenance. This service streamlines the management of your container workloads providing an cost effective solution, for deploying and overseeing applications, in an AWS containerized environment.

We will be using AWS Fargate for deploying our containerized Flask Web Server application which gives us a public IP Address as output using it, we can access our application publicly.

Tools Required

  • Docker Software Installed
  • Latest version of Python
  • A Web Browser

Steps to Deploy Flask Web Server in Docker Container using AWS

Packages Required

flask: This package is used to create a Web Server and define methods to run on it like GET, POST etc. Install it using the below command.

pip install Flask

Step 1: First create a file named “app.py” in your working directory.

Step 2: Write the below code in the Python file created.

Python3




from flask import Flask
from datetime import datetime
  
app = Flask(__name__)
  
@app.route('/')
def get():
    time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    return {
        "message": "Hello! I am currently running on a Docker Container!",
        "time": time
    }
  
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)


Code Analysis:

  1. Required packages Flask, and datetime are imported for creating Web Server and displaying time.
  2. A get() route is defined on “/” with the default HTTP GET method.
  3. When it is called, it displays a hello message with the current time using the datetime package imported previously.
  4. Finally, the Flask application is run on port 5000 which we will be using in further steps.

Step 3: Create a new file named “requirements.txt” where we type in all the pip packages that need to get installed when our docker image is built.

Write the below text file to requirements.txt

Flask

Step 4: Create a Docker File in the same directory with the name as “Dockerfile” using the below code.

FROM python:3.8-slim
WORKDIR /myDir
COPY . /myDir
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["python", "app.py"]

Code Analysis:

  1. Python image is imported using the FROM command
  2. The work directory is specified as myDir using the WORKDIR command
  3. All the files in the local working directory are copied to the newly created myDir using the COPY command
  4. All packages present in requirements.txt are installed using the RUN command
  5. Port 5000 is exposed to public access using the EXPOSE command
  6. Finally, the app.py file is run by Python using the CMD command

Step 5: Build the Docker Container using the below command in terminal

docker build -t flask-web-server .

A docker image named flask-web-server gets created and all the packages present in requirements.txt will get installed. The (.) at the end of the command specifies to use Dockerfile present in the current working folder as the template for building the container.

Note: You need to have Docker Installed on your system for the above command to work.

Step 6: Once the image is built, you can run the Docker container with the following command in the terminal

docker run -p 5000:5000 flask-web-server

The image previously created is run on the localhost.

  • -d is to specify to run the container in the background.
  • -p is used to map ports between the host machine and the Docker container. In this case, it is mapping port 5000 from the host to port 5000 in the container. This means that any traffic sent to port 5000 on your host machine will be forwarded to the Flask application running inside the container on port 5000.

After running this command, a container hash is outputted which means the container is spanned successfully!

Test the Web Server by entering http://localhost:5000 into your web browser. You can see a message and current system time as shown below.

Command

Step 7: Now we need to deploy this container to AWS Fargate, so we can access it publicly on any device.

  • For this, login to your AWS console search for “Elastic Registry Service”, and click on it.

ECS

  • Click on “Get Started”.
  • Select the repository as “Public” as of now (Change as per your need).
  • Under the repository name, give any name you wish. We are giving “flaskrepo14” as of now (It should be unique).
  • Go down and then click on “Create Repository”.

Flask repo

  • Click on your repository name and open it.

Step 8: Click on “View Push Commands” in the top right corner and enter each command into your terminal as mentioned there.

Note: You need to have AWS CLI setup on your system to execute these commands. Read this article on how to install AWS CLI.

After installing CLI, log in with your credentials and run the commands specified there.

Resolving Error

Issue

If you are on Windows and receiving the following error message when running the commands mentioned on AWS, follow the below steps to resolve it.

Error

Solution

  1. Remove the C:\Program Files\Docker\Docker\resources\bin\docker-credential-desktop.exe and C:\Program Files\Docker\Docker\resources\bin\docker-credential-wincred.exe files from your system.
  2. Open the C:\Users\YourUserName\.docker\config.json file and remove the “credsStore” line from the file.

The error gets resolved and you get a Login Succeeded message.

Cnfigure credentials

After running all the commands, your local docker image is uploaded and stored in the AWS Elastic Container Registry like below.

Copy the Image URI by going into the Repositories section which will be used later.

Latest images

Step 9: Now we need to deploy this container to AWS Fargate, so we can access it publicly on any device.

  • For this, login to your AWS console search for “Elastic Container Service”, and click on it.

ECS

  • Then, click on the “Create Cluster” button on the top right corner.

Step 10:

  • Type in the Cluster name as per your wish. We are giving “MyCluster” as of now. Keep the infrastructure option as the same i.e. “AWS Fargate (serverless)”.
  • Scroll to the bottom and click on “Create” in the bottom right corner.
  • Wait for a few minutes for your cluster to get created.

Screenshot-2023-10-22-130257

  • It would show like the above image after the cluster is created for you.

Step 11: Now select “Task definitions” at the left navigation pane. Click on three lines menu if it doesn’t appear for you.

Task Definitions

  • Now Click on “Create new task definition” in the top right corner.
  • Enter any task definition name as per wish. We are currently using “FlaskServer” .
  • Scroll down and mention CPU and Memory as per your application’s requirements. We are currently going with default settings.
  • In the Container section, give any relevant container name and paste the Image URI that we copied earlier.
  • Under Container port, mention 5000 as the port number. As we specified 5000 in our Dockerfile.
  • Go down and then click on the “Create” button. Your Task Definition will be created.

Step 12:

Run task

  • Now click on “Deploy”, “Run Task” and select “My Cluster” which we previously created.
  • Use all the default options and scroll down to the Networking section.
  • To access the web server publicly, we need a security group with public internet access. Create a security group with public internet access on all ports. You can refer to this article on how to create security groups.
  • Select the Security Group with public internet access that you created just now.
  • Go down and then click on the “Create” button.

Note: Wait for a few minutes as AWS allocates resources for your task and deploys it.

My cluster

After some time, you can see 1 Running task. It means, your container is deployed successfully.

Output

  • Click on “MyCluster” and select “Tasks”, there will be a task shown. Wait for it to get into a running state and open it.
  • Under the “Configuration” section find the Public IP Address, copy it and paste it into your web browser by specifying the port as 5000.
  • Example for me the Public IP address is 35.173.177.93 and my final URL is http://35.173.177.93:5000
  • Voila! Your Flask App is now publicly accessible to everyone on the internet safely in its docker container.

task output

Conclusion

This article highlights the role that web servers play in the world and explores how Docker, a containerization platform addresses the common issue of code that only works on specific systems. Docker solves this problem by providing an portable environment, for web applications. We have also introduced AWS Fargate, which’s a serverless computing engine and provided a guide on deploying a Flask web server in a Docker container on AWS Fargate. This approach enables efficient hosting of web applications, to people worldwide ultimately resolving compatibility issues and simplifying the deployment process.

FAQs on Docker Container

Q.1: How can I create a Docker container for a Flask Web Server?

Answer:

To complete the process you need to generate a Dockerfile that outlines the configuration of the container. Once you have created the Docker image by executing “docker build ” you can proceed to run the Docker container by utilizing “docker run” and mapping the ports.

Q.2: What is a Task Definition in the context of AWS Fargate?

Answer:

A Task Definition serves as a guide, for running containers on AWS Fargate. It includes specifications, like the container image, resource needs, networking details and security groups.

Q.3: How can I access my Flask Web Server publicly after deploying it on AWS Fargate?

Answer:

You can access your Flask Web Server publicly by obtaining the Public IP Address provided by AWS Fargate and specifying the port number (usually 5000) in your web browser.

Q.4: What is the main advantage of using Docker for web server deployment?

Answer:

Docker makes it easier to deploy web servers by bundling applications and their dependencies into containers. This guarantees consistency, across environments, simplifies development and deployment procedures and resolves compatibility problems like the infamous “It works on my system. Not, on yours.”



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads