---
title: "How To Deploy a Python Flask API Application on Docker"
description: "Quickly need to deploy a Python API application? Learn how to deploy a Python Flask API application via Docker in this step-by-step tutorial!"
canonical: "https://adamtheautomator.com/python-flask-api/"
---

# How To Deploy a Python Flask API Application on Docker

> Quickly need to deploy a Python API application? Learn how to deploy a Python Flask API application via Docker in this step-by-step tutorial!

Source: https://adamtheautomator.com/python-flask-api/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![How To Deploy a Python Flask API Application on Docker](https://adamtheautomator.com/wp-content/uploads/2022/01/How-To-Deploy-a-Python-Flask-API-Application-on-Docker.jpg)

# How To Deploy a Python Flask API Application on Docker

[![](https://secure.gravatar.com/avatar/2beb65fca997135120ed98dc6a2e57dcdf1a7d7d2f5ff687b5d91dc7ccd7a6b5?s=192&d=mm&r=g)Sagar](https://adamtheautomator.com/author/shanky-mendiratta/)3 January 20225 min. read

Categories: [DevOps](/category/devops/)

Tags:[Docker](/tag/docker/)[Docker-Compose](/tag/docker-compose/)[Linux](/tag/linux/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Creating a Python Flask API Application (GET and POST API)](#creating-a-python-flask-api-application-get-and-post-api)
*   [Creating a Dockerfile to Deploy the Python Flask API Application](#creating-a-dockerfile-to-deploy-the-python-flask-api-application)
*   [Building a Docker Image for Python Flask API Application](#building-a-docker-image-for-python-flask-api-application)
*   [Running the Python Flask Application in Docker Container](#running-the-python-flask-application-in-docker-container)
*   [Conclusion](#conclusion)

If you’re new to Docker and containers, learning to deploy a [Python Flask](https://flask.palletsprojects.com/en/2.0.x/) API application on Docker is a great way to start. Docker lets you containerize applications with light-weighted technology and security for quick application deployment.

In this tutorial, you’ll learn to become your own master in setting up and deploying Python Flask API applications on Docker containers.

Get ready and start deploying!

Hands-on API tutorials are easier when the Python, Docker, and web fundamentals are fresh. If you want structured practice while you build, [compare Educative’s interactive developer courses](https://educative.pxf.io/c/1454808/1657818/19245) before you buy.

## **Prerequisites**

If you’d like to follow along step-by-step, you will need the following installed:

*   Ubuntu machine with Docker installed. This tutorial uses [Ubuntu 18.04.5 LTS](https://releases.ubuntu.com/18.04/) with Docker v19.03.8.

Related:[How to Install and Use Docker on Ubuntu (In the Real World)](https://adamtheautomator.com/docker-ubuntu/)

*   Python v3.9 or later installed on Ubuntu machine. This tutorial will be using Python v3.9.2 on a Ubuntu Machine.

Related:[How Do You Install Python 3.6?](https://adamtheautomator.com/install-python-36/)

*   [Elinks](https://yum-info.contradodigital.com/view-package/base/elinks/) package installed on the Ubuntu machine used to test the API in this tutorial.

## Creating a Python Flask API Application (GET and POST API)

Kick-off this tutorial by creating a Python Flask application. Flask is a lightweight [WSGI](https://wsgi.readthedocs.io/en/latest/) micro web application framework written in Python. Flask provides handy tools and features in creating web applications in Python.

Before creating a Python Flask application, you’ll install a Python Flask and Python virtual environment where Flask will run an application.

1\. Log in to your Ubuntu machine using your favorite SSH client.

2\. Next, run the following commands to create a directory named _~/docker\_python\_flask\_demo_ and switch to that. This directory will hold all the files required by Python and Docker to run an application.

```yaml
mkdir ~/docker_python_flask_demo
cd ~/docker_python_flask_demo
```

3\. Run the `pip` command below to `install` a Python virtual environment (`virtualenv`) needed by Flask to execute the applications. A Python virtual environment offers its own Python binary and per-application installed packages to avoid conflicts with other applications.

```bash
pip install virtualenv
```

![Installing the environment needed by Flask to execute the applications](https://adamtheautomator.com/wp-content/uploads/2022/01/image.png)

Installing the environment needed by Flask to execute the applications

4\. Execute the [`virtualenv`](https://docs.python.org/3/library/venv.html) command below to [create and activate a virtual environment](https://docs.python.org/3/library/venv.html) using the `venv` module.

```bash
virtualenv venv
```

![Creating the virtual environment for Python](https://adamtheautomator.com/wp-content/uploads/2022/01/image-1.png)

Creating the virtual environment for Python

5\. Now, run the below command to install the Python `flask` package with the `pip` package manager.

```bash
pip install flask
```

6\. Run the following command to activate packages in your virtual environment before you can start installing or using them. This modifies the `VIRTUAL_ENV` environment variable to point to your virtual environment and prepends the virtual environment Python binary to the path so you run the correct binary.

```bash
source venv/bin/activate
```

7\. Create one more file, named **requirements.txt**, and define the dependency of the Flask application, as shown below.

```markup
Flask==2.0.2
```

8\. Create a text file _~/docker\_python\_flask\_demo/app.py_ and populate the file with the below Python code.

The below Python code imports the Python `flask` class and creates a class instance named `app`. The `app` class instance contains two `login()` functions executed when users send requests on `/login` page.

The `success()` function then executes, displaying the welcome “name-of-the-user” message on the browser.

```python

from flask import Flask , redirect , url_for , request # Importing the class flask
# app is the object or instance of Flask
app = Flask(__name__)
# app.route informs Flask about the URL to be used by function
@app.route('/success/<name>')
# Creating a function named success
def success(name):
    return 'welcome %s' % name

@app.route('/login', methods = ['GET','POST'])
# Creating a function named login 
def login():
    if request.method == 'POST':
       user = request.form['adamlistek']
       return redirect(url_for('success', name = user)) 
    else:
       return "INVALID"
# Programs executes from here in a development server (locally on your system) 
# with debugging enabled. 
  
if __name__ == '__main__':
   app.run(debug = True)
```

9\. Create one more file named _~/docker\_python\_flask\_demo/form.html_ and copy/paste the below code.

Running the HTML code below creates a form with two inputs; one is text to provide your name, and the other is a submit button.

As soon as you provide a username and hit the submit button, a post request is sent, and Flask executes another function and opens a new web page on [http://localhost:5000/success/](http://localhost:5000/success/)<username>.

```markup
<html>
  <body>
    <form action="http://localhost:5000/login" method="post">
      <p>Please Enter your name</p>
      <p><input type="text" name="adamlistek" /></p>
      <p><input type="submit" value="Submit" /></p>
    </form>
  </body>
</html>
```

10\. Finally, run the `Python` command below to verify the application (`app.py`) works locally on your system.

```python
Python app.py
```

As you can see below, the application is running successfully on the Ubuntu machine but not on Docker. You’ll launch the same application on Docker in the following sections.

![Running the Python application on the ubuntu machine.](https://adamtheautomator.com/wp-content/uploads/2022/01/image-2.png)

Running the Python application on the ubuntu machine.

## Creating a Dockerfile to Deploy the Python Flask API Application

You’ve just created and verified the Python Flask application works locally on your machine. But before deploying the application on Docker, you’ll first create a [Dockerfile](https://docs.docker.com/engine/reference/builder/) to define all sets of instructions to build the [Docker image](https://docs.docker.com/engine/reference/commandline/images/).

Create a file named Dockerfile in the _~/docker\_python\_flask\_demo_ directory, and copy/paste the content below to the Dockerfile.

Docker will use this Dockerfile to run all the instructions or commands necessary to build a new Docker image on top of the base image (`ubuntu:18.04`).

```yaml
# Sets the base image for subsequent instructions
FROM ubuntu:18.04
# Sets the working directory in the container  
WORKDIR /app
RUN apt-get update -y
RUN apt-get install -y python-pip python-dev
# Copies the files to the working directory
COPY form.html /app/form.html
# Copies the dependency files to the working directory
COPY requirements.txt /app/requirements.txt
# Install dependencies
RUN pip install -r requirements.txt
# Copies everything to the working directory
COPY . /app
# Command to run on container start    
CMD [ "python" , "./app.py" ]
```

Now, run the [`tree`](https://en.wikipedia.org/wiki/Tree_\(command\)) command below to verify all of the required files to run the Python Flask application are contained in the working directory (_~/docker\_python\_flask\_demo_).

```bash
tree  
```

![Verifying all Required Files to Run the Flask Application Exist](https://adamtheautomator.com/wp-content/uploads/2022/01/image-3.png)

Verifying all Required Files to Run the Flask Application Exist

## Building a Docker Image for Python Flask API Application

You now have the required files to deploy a Python Flask application, but those files won’t do anything unless you build an image. You’ll run the `docker build` command to build a Docker image based on the instructions you set in the Dockerfile.

Related:[Creating a Docker Image for Python Data Science Libraries](https://adamtheautomator.com/python-data-science-libraries/)

Run the `docker build` command below to build a Docker image in the working directory (`.`). This command tags (`-t`) the image as `flask-image` version 1 (`:v1`).

```bash
sudo docker build -t flask-image:v1 .
```

![Building the Docker Image](https://adamtheautomator.com/wp-content/uploads/2022/01/image-4.png)

Building the Docker Image

Now, run the `docker` command below to list all available images.

```bash
sudo docker images
```

Below, you can see various attributes returned, such as **REPOSITORY**. Notice the **REPOSITORY** name is **flask-image** and is tagged with a version (**v1**), as shown below.

![Verifying the New Docker Image (flask-image)](https://adamtheautomator.com/wp-content/uploads/2022/01/image-5.png)

Verifying the New Docker Image (flask-image)

## Running the Python Flask Application in Docker Container

After creating a Docker image, you can now run the Python flash application in a Docker container. A Docker container packages up code and its dependencies to run applications quickly.

1\. Execute the `docker run` command below to perform the following:

*   Start the container in **[detached mode](https://www.freecodecamp.org/news/docker-detached-mode-explained/)** (`-d`), so it runs as a background process and returns the console output upon creation.
*   Maps the Docker host port (`-p 5000:5000`) with the container’s port.
*   Launches the Docker container (`flask-image:v1`)

```bash
sudo docker run -d -p 5000:5000 flask-image:v1
```

2\. Next, run the `docker` command below to list all containers in the Docker engine. Verify if Docker successfully created the container.

```bash
sudo docker ps -a
```

![Verifying the Docker container in the Docker engine](https://adamtheautomator.com/wp-content/uploads/2022/01/image-6.png)

Verifying the Docker container in the Docker engine

3\. Finally, run the command below to open your web browser in the Ubuntu machine using elinks.

```markup
elinks form.html
```

The command opens the web browser on the terminal and prompts for a name, as shown below.

Enter your name and hit the Submit button.

![Accessing the login web page with the form to enter your name](https://adamtheautomator.com/wp-content/uploads/2022/01/image-7.png)

Accessing the login web page with the form to enter your name

4\. As you can see below, after hitting the **Submit** button, the login function redirects to the success function in the Flask application.

![Displaying the welcome message in the web browser](https://adamtheautomator.com/wp-content/uploads/2022/01/image-8.png)

Displaying the welcome message in the web browser

## Conclusion

This tutorial aimed to help you through the process of setting up a Python Flask API Docker container using Docker images. You’ve also touched on how to launch Python Flask containers using Dockerfiles, which allows you to edit and build customized containers of your choice.

So what other applications do you have in mind to deploy on Docker container? Perhaps a Docker MongoDB container?

Related:[How to Deploy and Manage a Docker MongoDB Container](https://adamtheautomator.com/docker-mongodb/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fpython-flask-api%2F&text=How%20To%20Deploy%20a%20Python%20Flask%20API%20Application%20on%20Docker)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fpython-flask-api%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fpython-flask-api%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2026/02/featured_image-13.webp)

### [Azure Container Apps: Instant Preview Environments per PR](/build-ephemeral-preview-environments-every-pr/)

Build isolated preview environments for every pull request using Azure Container Apps revision labels and Azure DevOps pipelines with scale-to-zero economics.

![](https://adamtheautomator.com/wp-content/uploads/2025/11/55418e927e511ae263219c072e27d637c2a967a5036de7020b329582db775c26.png)

### [Automating Docker Container Health Checks with Python and Local Notifications](/docker-health-checks-python/)

Docker's built-in health checks are passive—they tell Docker when a container fails, but do they tell you? In this tutorial, we'll build a lightweight Python monitoring system that runs entirely on your infrastructure with zero external dependencies. You'll learn to detect container failures in real-time, send instant alerts, and maintain a complete audit log of every state change.

![](https://adamtheautomator.com/wp-content/uploads/2023/11/automating-tasks.jpg)

### [Automating Tasks Using Bash Scripts and Cron Jobs with AWS](/automating-tasks/)

Discover how to combine bash scripts with cron jobs and leverage the power of AWS for automating tasks in this ATA Learning tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
