How to run Flask app inside Docker container

DockerDockerBeginner
Practice Now

Introduction

In this tutorial, we will explore the process of running a Flask application inside a Docker container. We will cover the fundamentals of Docker, build a Flask application, and then containerize the Flask app to take advantage of the benefits that Docker provides.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("`Docker`")) -.-> docker/ContainerOperationsGroup(["`Container Operations`"]) docker(("`Docker`")) -.-> docker/ImageOperationsGroup(["`Image Operations`"]) docker(("`Docker`")) -.-> docker/DockerfileGroup(["`Dockerfile`"]) docker/ContainerOperationsGroup -.-> docker/create("`Create Container`") docker/ContainerOperationsGroup -.-> docker/ps("`List Running Containers`") docker/ContainerOperationsGroup -.-> docker/run("`Run a Container`") docker/ContainerOperationsGroup -.-> docker/start("`Start Container`") docker/ContainerOperationsGroup -.-> docker/stop("`Stop Container`") docker/ImageOperationsGroup -.-> docker/pull("`Pull Image from Repository`") docker/DockerfileGroup -.-> docker/build("`Build Image from Dockerfile`") docker/ContainerOperationsGroup -.-> docker/ls("`List Containers`") subgraph Lab Skills docker/create -.-> lab-415825{{"`How to run Flask app inside Docker container`"}} docker/ps -.-> lab-415825{{"`How to run Flask app inside Docker container`"}} docker/run -.-> lab-415825{{"`How to run Flask app inside Docker container`"}} docker/start -.-> lab-415825{{"`How to run Flask app inside Docker container`"}} docker/stop -.-> lab-415825{{"`How to run Flask app inside Docker container`"}} docker/pull -.-> lab-415825{{"`How to run Flask app inside Docker container`"}} docker/build -.-> lab-415825{{"`How to run Flask app inside Docker container`"}} docker/ls -.-> lab-415825{{"`How to run Flask app inside Docker container`"}} end

Understanding Docker

Docker is a popular open-source platform that allows developers to build, deploy, and run applications in a containerized environment. Containers are lightweight, standalone, and executable software packages that include everything needed to run an application, including the code, runtime, system tools, and libraries.

What is Docker?

Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package.

Docker Architecture

The Docker architecture consists of the following components:

graph TD A[Docker Client] --> B[Docker Daemon] B --> C[Docker Images] B --> D[Docker Containers] B --> E[Docker Registries]
  • Docker Client: The user interface for interacting with the Docker system.
  • Docker Daemon: The background process that manages Docker objects, such as images, containers, networks, and volumes.
  • Docker Images: Blueprints for creating Docker containers.
  • Docker Containers: Runnable instances of Docker images.
  • Docker Registries: Repositories for storing and distributing Docker images.

Benefits of Using Docker

  1. Consistent Environments: Docker ensures that applications run the same way, regardless of the underlying infrastructure.
  2. Scalability: Docker containers can be easily scaled up or down to meet changing demand.
  3. Portability: Docker containers can run on any system that has Docker installed, making it easy to move applications between different environments.
  4. Efficiency: Docker containers are lightweight and use fewer resources than traditional virtual machines.
  5. Isolation: Docker containers provide a high degree of isolation, ensuring that applications run in a secure and consistent environment.

Getting Started with Docker

To get started with Docker, you'll need to install the Docker engine on your system. You can download Docker from the official website (https://www.docker.com/get-started) and follow the installation instructions for your operating system.

Once you have Docker installed, you can start building and running Docker containers. Here's a simple example of running a Docker container with the Ubuntu image:

docker run -it ubuntu

This command will pull the Ubuntu image from the Docker registry, create a new container, and start an interactive shell session within the container.

Building a Flask Application

Flask is a popular Python web framework that is lightweight, flexible, and easy to use. In this section, we'll walk through the process of building a simple Flask application.

Setting up the Development Environment

First, let's set up the development environment. We'll be using Python 3.9 and Flask 2.0.2 for this example.

## Install Python 3.9
sudo apt-get update
sudo apt-get install -y python3.9

## Install Flask
pip3 install flask==2.0.2

Creating a Flask Application

Now, let's create a simple Flask application. Create a new file called app.py and add the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, LabEx!'

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

In this example, we import the Flask class from the flask module, create a new Flask instance, and define a route for the root URL (/) that returns the string "Hello, LabEx!". Finally, we run the application using the app.run() method.

Running the Flask Application

To run the Flask application, execute the following command in your terminal:

python3 app.py

This will start the Flask development server and make your application available at http://localhost:5000/.

Adding Functionality

You can easily add more functionality to your Flask application by defining additional routes and adding business logic. For example, you can create a route that accepts user input, performs some processing, and returns a response.

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, LabEx!'

@app.route('/greet', methods=['POST'])
def greet():
    name = request.form['name']
    return f'Hello, {name}!'

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

In this example, we've added a new route /greet that accepts a POST request with a name parameter. The application then returns a greeting message with the provided name.

Containerizing the Flask App

Now that we have a basic Flask application, let's containerize it using Docker. Containerizing an application allows us to package it, along with its dependencies, into a self-contained unit that can be easily deployed and scaled.

Creating a Dockerfile

To containerize our Flask application, we need to create a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.

Create a new file called Dockerfile and add the following content:

## Use the official Python image as the base image
FROM python:3.9-slim

## Set the working directory to /app
WORKDIR /app

## Copy the requirements file into the container
COPY requirements.txt .

## Install the Python dependencies
RUN pip install --no-cache-dir -r requirements.txt

## Copy the Flask app code into the container
COPY app.py .

## Expose the port that the Flask app will run on
EXPOSE 5000

## Set the command to run the Flask app
CMD ["python", "app.py"]

In this Dockerfile, we:

  1. Use the official Python 3.9 slim image as the base image.
  2. Set the working directory to /app.
  3. Copy the requirements.txt file into the container.
  4. Install the Python dependencies.
  5. Copy the app.py file into the container.
  6. Expose port 5000 for the Flask app.
  7. Set the command to run the Flask app.

Building the Docker Image

Now, let's build the Docker image for our Flask application. In your terminal, run the following command:

docker build -t labex-flask-app .

This command will build a Docker image with the tag labex-flask-app using the Dockerfile in the current directory.

Running the Docker Container

After the image is built, we can run the Flask application in a Docker container:

docker run -p 5000:5000 labex-flask-app

This command will start a new container based on the labex-flask-app image and map port 5000 on the host to port 5000 in the container.

You can now access the Flask application at http://localhost:5000/.

Deploying the Docker Image

Once you have your Flask application containerized, you can deploy the Docker image to a container registry, such as Docker Hub or a private registry, and then deploy the application to a production environment.

Summary

By the end of this tutorial, you will have a solid understanding of how to containerize a Flask application using Docker. You will be able to build a Docker image for your Flask app, run it in a Docker container, and leverage the advantages of Docker for Flask development and deployment.

Other Docker Tutorials you may like