Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • AWS EC2
  • AWS S3
  • AWS VPC
  • AWS Load Balancing
  • AWS Autoscaling
  • AWS EKS
  • AWS ECS
  • AWS Fargate
  • Microsoft Azure Tutorial
  • Google Cloud Platform Tutorial
  • Docker tutorials
  • Kubernetes Tutorials
  • GIT Tutorials
  • Docker cheat sheet
  • Kubernetes cheat sheet
  • Ansible Interview Questions
  • Docker Interview Questions
  • AWS Interview Questions
Open In App
Next Article:
How to Provide the Static IP to a Docker Container?
Next article icon

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

Last Updated : 28 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.


Next Article
How to Provide the Static IP to a Docker Container?

V

vinay1484
Improve
Article Tags :
  • Geeks Premier League
  • Amazon Web Services
  • Amazon
  • AWS
  • Geeks Premier League 2023
Practice Tags :
  • Amazon

Similar Reads

  • How to Use AWS CLI in Docker Container ?
    The AWS Command Line Interface (CLI) is a powerful tool that allows users to interact with AWS services directly from the terminal. Integrating AWS CLI within a Docker container can significantly streamline workflows, especially for development and deployment processes that rely on cloud infrastruct
    4 min read
  • How To Deploy Flask APP On AWS EC2 Instance?
    In this article, we will study how we can deploy our existing Flask application in AWS EC2. We will also see how to use the public IP of the EC2 instance to access the flask application. For this article, you should know about setting up EC2 in AWS. So, let's begin with the deployment. Primary Termi
    5 min read
  • Serverless Computing With AWS Lambda And Docker: Running Custom Containers
    AWS Lambda is a serverless computing service that runs the code without any management of servers by the user. On the other hand, Docker is a tool that helps to encapsulate applications with its dependency into docker containers. AWS Lambda and Docker are some of the most important services used by
    5 min read
  • How to Provide the Static IP to a Docker Container?
    Docker is an open-source project that makes it easier to create, deploy and run applications. It provides a lightweight environment to run your applications.It is a tool that makes an isolated environment inside your computer. Think of Docker as your private room in your house. Living with your fami
    2 min read
  • How To Configure Flask API To Your Domain Name On AWS EC2?
    In this article, We are going to create a Flask API on an EC2 Instant and we will learn how to configure it with a domain name using Gunicorn and nginx(NGINX). Flask is a web microframework, it’s a Python module that lets you develop web applications easily. A domain name is a string of text that ma
    8 min read
  • How to Use AWS Elastic Beanstalk For Scalable Web Application Deployment?
    AWS Elastic Beanstalk is an easy-to-use service for deploying and scaling web applications and services developed with Java, .NET, PHP, Node.js, Python, Ruby, Go, and Docker on familiar servers such as Apache, Nginx, Passenger, and IIS. Benefits of AWS Elastic BeanstalkOffers Quicker Deployment: It
    5 min read
  • How To Deploy A Container To Azure Container Instances ?
    In layman's terms, how will it feel when a developer develops an app and a member of the testing team tries to test the application on his/her OS? They will have to install the packages, and libraries required to run the app. Well, in this case, the container makes it easy and faster to rapidly depl
    8 min read
  • How to Launch a WordPress Website using Amazon EC2 Server ?
    What is Amazon web service (AWS)? It is a secure cloud services platform. It offers services like compute power, database storage, content delivery, and other functionality to help businesses scale and grow. What is Amazon EC2? Amazon Elastic Compute Cloud (EC2) is an Cloud Based Services IaaS (Infr
    3 min read
  • Deploy Flask App on AWS EC2 Windows
    Do you want to host a Windows-based Python Flask application on Amazon Web Services (AWS) Elastic Compute Cloud (EC2)? Flask is a frequently utilized framework for building web apps, APIs, and prototypes because of its ease of use and versatility. AWS EC2 provides virtual machines that are scalable,
    5 min read
  • How to Deploy Web Apps in S3?
    Amazon S3 is an Object storage service owned by AWS which offers high availability, security, scalability, and performance. Customers across all industries and sizes can use Amazon S3 to back up and restore, archive, create enterprise applications, connect IoT devices, and create big data analytics
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences