Open In App

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.



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

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.




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.

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.

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.

Step 10:

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

Step 12:

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.

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


Article Tags :