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.

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.

  • 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”.

  • 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.

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.

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.

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.

  • 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.

  • 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.

  • 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:

  • 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.

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

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

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.

Similar Reads

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....

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....

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...

Output

...

Conclusion

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....

FAQs on Docker Container

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....