Tutorials  /  Python

Install Poetry and Flask on Ubuntu 24.04 – Step-by-Step Guide

Ccentron Redaktion · April 2025 ·13 min read ·Python, Tutorial

Poetry is a free and open-source tool designed to manage dependencies and package Python projects efficiently. It provides a streamlined overview of your project’s dependency structure, simplifies dependency installation, and makes it easy to publish your project to PyPI.

This guide will walk you through installing Poetry using Pipx and configuring it to manage a Flask app on Ubuntu 24.04. You’ll also learn how to create a virtual environment and run your Flask project with Poetry and Gunicorn.

Requirements Before You Begin

  • You are working on an Ubuntu 24.04 system.
VM

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Installing Poetry via Pipx on Ubuntu 24.04

Installing Poetry in an isolated environment is recommended to avoid conflicts between Poetry’s internal components and your system’s global Python packages. Use the steps below to set up Pipx and install Poetry:

1. Refresh the APT Repository

Console
$ sudo apt update

2. Install Pipx

Console
$ sudo apt install pipx -y

3. Add Pipx to Your System PATH

Console
$ pipx ensurepath

4. Enable Auto-Completion for Pipx Commands

Console
$ echo 'eval "$(register-python-argcomplete pipx)"' >> ~/.bashrc

5. Apply the Configuration Changes

Console
$ source ~/.bashrc

6. Use Pipx to Install Poetry

Console
$ pipx install poetry

After installation, your terminal should display something like the following:

installed package poetry 2.0.0, installed using Python 3.12.3 These apps are now globally available - poetry done! 

7. Check the Installed Poetry Version

Console
$ poetry --version

The expected output will be similar to:

Poetry (version 2.0.0)

Starting a New Poetry Project for Flask Development

You can either initialize Poetry in an existing Python project or let it create a new one from scratch. Using Poetry to set up a fresh project ensures the proper structure and configuration are created automatically. Below are the steps to begin a new Poetry-managed Flask project.

1. Create a New Project Directory

Console
$ poetry new flask-app

The command above generates a folder named flask-app and includes the following structure:

  • flask_app: Contains an __init__.py file for your Flask application logic, modules, and support code.
  • pyproject.toml: Defines project metadata, Poetry settings, and dependencies.
  • README.md: A basic documentation template for your project.
  • tests: Organizes and stores the project's test files.

Created package flask_app in flask-app

2. Move into the Project Directory

Console
$ cd flask-app

Setting Up a Virtual Environment and Installing Flask

1. Choose the Python Interpreter

Console
$ poetry env use python3

This command tells Poetry to use the system’s default Python 3 interpreter. If you want a specific version, you can run something like poetry env use python3.11, assuming that version is installed.

Creating virtualenv flask-app-vnQ3DaWl-py3.12 in /home/linuxuser/.cache/pypoetry/virtualenvs

Using virtualenv: /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12

2. Get the Activation Command

Console
$ poetry env activate

source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate

3. Activate the Virtual Environment

Console
$ source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate

Once activated, your terminal prompt will look like this:

(flask-app-py3.12) linuxuser@:~/flask-app$

4. Install Flask in the Project

Console
$ poetry add flask

This command performs several actions:

  • Installs Flask and all related packages into the virtual environment.
  • Records the version in your pyproject.toml file.
  • Creates a poetry.lock file to lock versions for reproducibility.

Using version ^3.1.0 for flask

Updating dependencies

Resolving dependencies... (0.2s)

Package operations: 7 installs, 0 updates, 0 removals

- Installing markupsafe (3.0.2)

- Installing blinker (1.9.0)

- Installing click (8.1.8)

- Installing itsdangerous (2.2.0)

- Installing jinja2 (3.1.5)

- Installing werkzeug (3.1.3)

- Installing flask (3.1.0)

Writing lock file

5. Exit the Virtual Environment

Console
$ deactivate

Configuring Firewall Rules for Flask on Ubuntu 24.04

On most Ubuntu 24.04 systems, the Uncomplicated Firewall (UFW) is enabled by default. To ensure access to your Flask app, you need to open the port it uses—typically port 5000. Use the steps below to allow traffic through port 5000 and reload the firewall settings.

1. Permit Traffic on Port 5000

Console
$ sudo ufw allow 5000/tcp

2. Apply the Updated Firewall Configuration

Console
$ sudo ufw reload

3. Confirm UFW Rule Activation

Console
$ sudo ufw status

The output will typically include:

Status: active

To Action From

-- ------ ----

22/tcp ALLOW Anywhere

5000/tcp ALLOW Anywhere

22/tcp (v6) ALLOW Anywhere (v6)

5000/tcp (v6) ALLOW Anywhere (v6)

Running a Flask Application with Poetry

Poetry does more than just manage dependencies; it can also handle running Python projects within its managed virtual environment. Follow the instructions below to activate the virtual environment and run your Flask app.

1. Retrieve the Virtual Environment Activation Command

Console
$ poetry env activate

The result will look like:

source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate

2. Enable the Virtual Environment

Console
$ source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate

3. Change to the Flask Project Directory

Console
$ cd flask_app

4. Create the app.py File

Console
$ nano app.py

5. Add This Code to the File

Python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "<h1>Greetings</h1>"

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

To save the file, press Ctrl+X, then hit Y and Enter.

This code launches a simple webpage that displays “Greetings” at the root URL.

6. Launch the Flask App with Poetry

Console
$ poetry run python app.py

Your terminal should show an output like the following:

* Serving Flask app 'app'

* Debug mode: off

WARNING: This is a development server. Do not use it in a production deployment.

Use a production WSGI server instead.

* Running on all addresses (0.0.0.0)

* Running on http://127.0.0.1:5000

* Running on http://<SERVER-IP>:5000

Press CTRL+C to quit

To view your Flask web application, open a browser and visit:

http://<SERVER-IP>:5000

To shut down the server, press Ctrl+C in your terminal.

Managing Development and Production Dependencies with Poetry

Poetry supports grouping dependencies, which helps separate development tools from production packages. Here’s how to create a development group and add pytest for testing purposes.

1. Install Pytest in a Dev Dependency Group

Console
$ poetry add pytest --group dev

This command adds a section named [tool.poetry.group.dev.dependencies] in the pyproject.toml file. It includes pytest = "^8.3.4" as part of the dev group.

Dependencies meant for production should not belong to any group. Instead, they should go into the main section [tool.poetry.dependencies]. This ensures they are available during packaging and deployment, without being left out.

2. Create a Unit Test for the Flask App

Navigate to the testing folder within your Flask project:

Console
$ cd ~/flask-app/tests

Create a new folder named unit:

Console
$ mkdir unit

Move into the newly created directory:

Console
$ cd unit

Create an __init__.py file to indicate the folder is a Python package:

Console
$ touch __init__.py

The __init__.py file allows Python to treat the directory as a package, enabling module imports. See the official Python documentation for more details.

Create a test file named test_app.py:

Console
$ nano test_app.py

Insert the following test code:

Python
import pytest
from flask_app.app import app

@pytest.fixture
def client():
    with app.test_client() as client:
        yield client

def test_the_home_route(client):
    response = client.get('/')
    assert response.status_code == 200
    assert b"<h1>Greetings</h1>" in response.data

Save and close the file by pressing Ctrl+X, then Y, and finally Enter.

This unit test checks whether the Flask app’s root endpoint returns the expected HTML content.

3. Run the Unit Test

Console
$ pytest

The output will resemble:

platform linux -- Python 3.12.3, pytest-8.3.4, pluggy-1.5.0

rootdir: /home/linuxuser/flask-app

configfile: pyproject.toml

collected 1 item

test_app.py . [100%]

============================= 1 passed in 0.11s ==============================

Setting Up Gunicorn for Flask in Production

Gunicorn is a production-ready WSGI server for Python web apps. It efficiently handles multiple client requests, making it ideal for running Flask in a live environment. Below are steps to install and use Gunicorn with your Flask project.

1. Move to the Flask Application Directory

Console
$ cd ~/flask-app/flask_app

2. Add Gunicorn as a Root Dependency

Console
$ poetry add gunicorn

3. Create the wsgi.py File

Console
$ nano wsgi.py

Paste the following Python code:

Python
from app import app

if __name__ == '__main__':
    app.run()

Save and exit using Ctrl+X, then press Y and Enter.

4. Launch Flask App Using Gunicorn

Console
$ gunicorn --bind 0.0.0.0:5000 wsgi:app

Check your web browser at:

http://<SERVER-IP>:5000

To stop the running server, use Ctrl+C in the terminal.

Managing and Recreating Poetry Virtual Environments

Poetry creates virtual environments that use up storage space, but they can be deleted and recreated as needed. Below are the steps to remove the current virtual environment and regenerate it.

1. Exit the Current Virtual Environment

Console
$ deactivate

2. List All Virtual Environments for the Project

Console
$ poetry env list

The currently active environment will be marked with (Activated).

flask-app-vnQ3DaWl-py3.12 (Activated)

3. Remove the Virtual Environment

Console
$ poetry env remove flask-app-vnQ3DaWl-py3.12

Deleted virtualenv: /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12

4. Recreate the Virtual Environment

Console
$ poetry env use python3

5. Retrieve the Activation Command

Console
$ poetry env activate

source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate

6. Activate the Virtual Environment

Console
$ source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate

7. Install Dependencies from pyproject.toml

Console
$ poetry install

As long as the pyproject.toml file is intact, Poetry can restore the environment and its dependencies at any time.

Changing the Location of the Poetry Virtual Environment

By default, Poetry saves virtual environments in ~/.cache/pypoetry/virtualenvs. To better organize your project, you can place the environment directly inside the project folder.

1. Exit the Current Environment

Console
$ deactivate

2. List Current Virtual Environments

Console
$ poetry env list

flask-app-vnQ3DaWl-py3.12 (Activated)

3. Delete the Virtual Environment

Console
$ poetry env remove flask-app-vnQ3DaWl-py3.12

4. Change the Environment Location Setting

Console
$ poetry config virtualenvs.in-project true

This command overrides the default Poetry setting, placing the virtual environment inside your project’s root folder.

5. Confirm the Configuration

Console
$ poetry config virtualenvs.in-project

true

6. Generate a New Virtual Environment

Console
$ poetry env use python3

Creating virtualenv flask-app in /home/linuxuser/flask-app/.venv

Using virtualenv: /home/linuxuser/flask-app/.venv

7. Retrieve the Activation Command

Console
$ poetry env activate

source /home/linuxuser/flask-app/.venv/bin/activate

8. Activate the Environment

Console
$ source /home/linuxuser/flask-app/.venv/bin/activate

9. Display Environment Information

Console
$ poetry env info

Virtualenv

Python: 3.12.3

Implementation: CPython

Path: /home/linuxuser/flask-app/.venv

Executable: /home/linuxuser/flask-app/.venv/bin/python

Valid: True

Base Platform: linux

OS: posix

Python: 3.12.3

Path: /usr

Executable: /usr/bin/python3.12

10. Reinstall All Project Dependencies

Console
$ poetry install

11. Start Flask Using Gunicorn in the New Environment

Console
$ gunicorn --bind 0.0.0.0:5000 wsgi:app

Check the application by navigating to:

http://<SERVER-IP>:5000

Conclusion

In this guide, you learned how to install and use Poetry on Ubuntu 24.04 for managing dependencies in a Flask project. You created a Poetry project, set up virtual environments, ran tests, and configured a production-ready server using Gunicorn. Additionally, you explored how to control the location and management of your virtual environments, ensuring an efficient development workflow.

For more detailed information, visit the official Poetry documentation.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren