---
title: "How to Deploy a Flask Web Server on Cloud Foundry"
description: "Learn how to efficiently deploy a Flash web server on Cloud Foundry without stressing yourself about the process in this tutorial!"
canonical: "https://adamtheautomator.com/flask-web-server/"
---

# How to Deploy a Flask Web Server on Cloud Foundry

> Learn how to efficiently deploy a Flash web server on Cloud Foundry without stressing yourself about the process in this tutorial!

Source: https://adamtheautomator.com/flask-web-server/

---

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 Flask Web Server on Cloud Foundry](https://adamtheautomator.com/wp-content/uploads/2022/03/How-to-Deploy-a-Flask-Web-Server-on-Cloud-Foundry.jpg)

# How to Deploy a Flask Web Server on Cloud Foundry

[![](https://secure.gravatar.com/avatar/d7af82363022947ce49ba2d0ec3b9470f7797b2541539ad2765a998a9c70c65c?s=192&d=mm&r=g)Ekekenta Clara](https://adamtheautomator.com/author/ekekenta-clara/)14 March 20225 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Python](/tag/python/)[Web Development](/tag/web-development/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Setting up a Flask Server](#setting-up-a-flask-server)
*   [Deploying the Flask Web Server](#deploying-the-flask-web-server)
*   [Associating Application to a Custom Role](#associating-application-to-a-custom-role)
*   [Conclusion](#conclusion)

Deploying a Flask web server has seemed overly stressful with lots of gotchas. But with Cloud Foundry, the process of deploying your application is simplified with just one push.

In this article, you’ll learn how to deploy a Flask application on Cloud Foundry. So save yourself the stress of writing infrastructure configurations while focusing on your code for your application.

Sounds interesting? Well, jump right in!

## Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

*   An Ubuntu machine – This tutorial uses [Ubuntu 20.04](https://adamtheautomator.com/install-ubuntu/), but other operating systems will work.

Related:[How to Install Ubuntu 20.04 \[Step-by-Step\]](https://adamtheautomator.com/install-ubuntu/)

*   Python – This tutorial uses Python 3.8.10.

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

*   [Cloud Foundry CLI](https://docs.cloudfoundry.org/cf-cli/install-go-cli.html)– Version 6.53.
    
*   Cloud Foundry SAP [Free Tier Account](https://www.sap.com/registration/trial.908cb719-0e03-421c-a091-daca045f0acc.html).
    

## Setting up a Flask Server

Before deploying a Flask application, you’ll first need to set up a Flash server. You’ll build a small demo app to deploy later in this tutorial.

1\. Run the following commands to create a directory for the project and set up a virtual environment.

```bash
# Create a new directory (FlaskAPI) and change the directory
mkdir FlaskAPI && cd FlaskAPI
# Create Virtual Env
python3 -m venv env
# Activate Virtual Env
. env/bin/activate
```

2\. Next, run the [`pip`](https://realpython.com/what-is-pip/) command below to `install` `flask`. `pip install flask`

```bash
pip install flask
```

3\. Create a file named _app.js_ with your preferred text editor and add the following code snippet below.

The code below creates a Flask wish list app that adds and returns a user’s wish.

```python
from flask import Flask, jsonify, request
import os

# Create an app instance from flask
app = Flask(__name__)

# Get port number from the environment varriable
port = os.getenv("PORT")

# Create an initial empty wish list
wishes = []

# Define a GET route
@app.route("/api/wish", methods=["GET"])
def getAllWish():
    #Retun all the wishes in the list
    return jsonify(wishes)

# Create A POST route
@app.route("/api/wish", methods=["POST"])
def addWish() -> dict:
    # Get the data from request body
    data = request.get_json()
    # Create a new wish object
    wishObj = {
        "id": len(wishes) + 1,
        "item": data["item"],
        "price": data['price']
    }
    # Add the new wish to list
    wishes.append(wishObj)
    # Return the list object
    return jsonify(wishObj)
```

4\. Finally, add the code below at the bottom of the _app.js_ file’s content.

The code below lets you modify your app to listen to the Cloud Foundry default port in production and port 500 in development. When you deploy an app on Cloud Foundry, a port is dynamically allocated for each app instance.

```bash
if __name__ == '__main__':
  # If the app is running locally
	if port is None:
    # Use port 5000
		app.run(host='0.0.0.0', port=5000, debug=True)
	else:
    # Else use cloud foundry default port
		app.run(host='0.0.0.0', port=int(port), debug=False)
```

## Deploying the Flask Web Server

With your Flask application set up, you’re ready to deploy the application. Well, almost. You still need to configure the deployment setup and allocate resources to your application.

1\. Run the [`pip freeze`](https://pip.pypa.io/en/stable/cli/pip_freeze/) command below to get the dependencies to install for your application and write the result in a _requirements.txt_ file. The _requirements.txt_ file is a configuration file handy for installing packages in bulk.

```bash
pip freeze > requirements.txt
```

After running the command, Python creates a _requirements.txt_ file in the project root directory with all dependencies documented like in the screenshot below:

![Creating a text file for a list of app dependencies](https://adamtheautomator.com/wp-content/uploads/2022/03/image-177.png)

Creating a text file for a list of app dependencies

2\. Next, create a _runtime.txt_ file in the ~/_FlaskAPI_ directory, and add your Python version like the one below. But for this demo, Python version 3.8.11 is set.

```bash
python-3.8.11web: FLASK_APP=app.py python3 -m flask run --host=0.0.0.0 --port=$POR
```

3\. Create a _vars.yml_ file in your project root directory, and populate the file with the attributes below.

```yaml
memory: 128MB       # Sets memory limit of the app
disk_quota: 256MB   # Allocates disk space to the app
random-route: true  # Generate route based on the app name
```

4\. Next, create a _manifest.yml_ file in the project root directory (_~/FlaskAPI_), and add the following configurations to the file.

The below configuration allocates resources to your application by referencing variables from the _vars.yml_ file.

> _You can ignore the resource allocation step if Cloud Foundry doesn’t find a manifest.yml file. Cloud Foundry allocates memory for the application depending on the project size._

```yaml
applications:
 - name: test-app   # Sets application name
	 # Reference memory, disk_quota and random-route from vars.yml file
   memory: ((memory))
   disk_quota: ((disk_quota))
   random-route: ((random-route))
```

5\. Create a _Procfile_ in your project root directory (~/_FlaskAPI)_ and add the following line to the _Procfile_.

The _Procfile_ specifies the command line to execute the application at runtime. The command-line starts the program in production and binds the webserver to the –host with the IP address 0.0.0.0.

```bash
web: python app.py
```

6\. Now, open your favorite web browser, and log in to your Cloud Foundry application service. Navigate to your SAP Cloud Platform Cockpit dashboard and note down your **API Endpoint** URL as you’ll need it in the next step.

![Getting your API Endpoint URL](https://adamtheautomator.com/wp-content/uploads/2022/03/image-178.png)

Getting your API Endpoint URL

7\. Run the below [`cf login`](https://docs.cloudfoundry.org/cf-cli/getting-started.html#login) command to log in to your application service, where `https://api.cf.us10.hana.ondemand.com` is the API endpoint you previously noted (step six). Enter your account credentials when prompted.

```bash
cf login https://api.cf.us10.hana.ondemand.com
```

After you log in, you’ll get an output like the one below, which verifies you’ve successfully logged in to your application service.

![Logging in to the Cloud Foundry CLI](https://adamtheautomator.com/wp-content/uploads/2022/03/image-179.png)

Logging in to the Cloud Foundry CLI

8\. Finally, run the [`cf push`](https://docs.cloudfoundry.org/devguide/deploy-apps/deploy-app.html) command below to deploy your application in the current directory (`.`).

```bash
cf push .
```

> _If you stored your configuration details in the vars.yml file, run this command below instead when committing changes throughout the tutorial. cf push –vars-file vars.yml_

If all goes well, you’ll get an output like the one below, which indicates your application is now live on Cloud Foundry.

Once you’ve deployed your application, Cloud Foundry will alert you and give you the route (URL) assigned to the application. Note the route URL as you’ll need it to test your application in the following section.

![Deploying Application to Cloud Foundry](https://adamtheautomator.com/wp-content/uploads/2022/03/image-180.png)

Deploying Application to Cloud Foundry

## Associating Application to a Custom Role

Instead of using the route generated by Cloud Foundry, you can create and associate your application to a custom route.

The routing tier compares each request to a list of all routes associated with apps and attempts to find the best match. Before creating a domain, you’ll need to check all available apps.

1\. Run the below command to list all available `apps`.

```bash
cf apps
```

You’ll see a list of apps displayed on your terminal, like in the screenshot below.

![Displaying Applications](https://adamtheautomator.com/wp-content/uploads/2022/03/image-181.png)

Displaying Applications

2\. Next, run the [`create-domain`](https://cli.cloudfoundry.org/en-US/v6/create-domain.html) command below to create a custom domain (`cf.flaskapp.com`) for Cloud Foundry organization ID (`2de99150trial`).

```bash
cf create-domain 2de99150trial cf.flaskapp.com
```

![Creating a Custom Domain](https://adamtheautomator.com/wp-content/uploads/2022/03/image-182.png)

Creating a Custom Domain

3\. Run the following [`cf create-route`](https://cli.cloudfoundry.org/en-US/v6/create-route.html) command to create a custom route to your domain (`cf.flaskapp.com`) in your app space (`fastapi`) in Cloud Foundry for your app (`test-app`).

```bash
cf create-route fastapi cf.flaskapp.com --hostname test-app
```

Below, you can see that command created a custom route (test-app.cf.flaskapp.com).

![Creating a Custom Route](https://adamtheautomator.com/wp-content/uploads/2022/03/image-183.png)

Creating a Custom Route

4\. Run the below command to map the custom route to your app to accept requests.

```bash
cf map-route test-app cf.flaskapp.com --hostname test-app
```

![Mapping Route to App](https://adamtheautomator.com/wp-content/uploads/2022/03/image-184.png)

Mapping Route to App

5\. Now, run the `cf push` command below to commit the `random-route` option on your `manifest.yml` file and deploy the application again.

```bash
cf push
```

> _Run the command below instead if you stored your configuration details in the vars.yml file. cf push –vars-file vars.yml_

Once the deployment completes, you’ll see your app details displayed on the terminal, like the screenshot below.

![Deploying App to Cloud Foundry](https://adamtheautomator.com/wp-content/uploads/2022/03/image-185.png)

Deploying App to Cloud Foundry

6\. Finally, open a testing tool like [Postman](https://www.postman.com/downloads/) or [Insomnia](https://insomnia.rest/download) and put the route URL you previously noted in the “Deploying your Flask Web Server” (step eight).

To test your application, be sure to prepend _https://_ to the URL (e.g., _https://your-route-url_).

![Testing App using Insomnia](https://adamtheautomator.com/wp-content/uploads/2022/03/image-186.png)

Testing App using Insomnia

## Conclusion

Throughout this tutorial, you’ve learned how to deploy a Flask application on Cloud Foundry by building a demo project. You’ve gone through setting up a Flask Server and ensuring that your application works with testing tools like Postman and Insomnia.

Now, with this newfound knowledge, how do you intend to master the steps you’ve learned in this tutorial? Perhaps build a Flask application with a database? Or deploy your Flask application with Docker?

Related:[How To Deploy a Python Flask API Application on Docker](https://adamtheautomator.com/python-flask-api/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fflask-web-server%2F&text=How%20to%20Deploy%20a%20Flask%20Web%20Server%20on%20Cloud%20Foundry)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fflask-web-server%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fflask-web-server%2F)

## Related Posts

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

### [How to Ace the Modern Coding Interview as a SysAdmin](/ace-modern-coding-interview-sysadmin/)

Master coding interviews for sysadmin and DevOps roles with practical preparation strategies. Learn Python, Bash, and platform-specific techniques that translate your operational experience into interview success.

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

### [How to Install PyTorch on Window](/pytorch/)

Embark on this journey and unleash PyTorch’s potential — your gateway to machine learning and AI exploration, through this ATA Learning tutorial!

![](https://adamtheautomator.com/wp-content/uploads/2023/08/install-python-macos.jpg)

### [Get Started with Programming and Install Python on macOS](/install-python-on-macos/)

Learn how to get started with programming and automation and install Python on macOS 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/)
