Saturday, June 28, 2025

Why & Containerize Your Present Python Apps



Picture by Creator | Ideogram

 

If you happen to’ve been questioning easy methods to make your Python apps extra transportable, constant, and deployment-ready, you are in the best place. Containerization is not only a buzzword. It is a sensible ability that’ll instantly stage up your improvement workflow.

On this information, I am going to stroll you thru containerizing a easy FastAPI software step-by-step. No fluff, simply sensible information you possibly can apply to your individual tasks at present. Able to dive in?

🔗 Hyperlink to the code on GitHub

 

Why Containerize Your Python Purposes?

 
Earlier than we dive into the how, let’s speak concerning the why:

  1. Consistency throughout environments: “It really works on my machine” turns into a factor of the previous. Once you use containers, you’ve got the assure that your app runs the identical means all over the place.
  2. Isolation: Every container has its personal dependencies, avoiding conflicts with different functions or system libraries.
  3. Portability: Ship your software anyplace Docker runs – out of your laptop computer to AWS, Azure, or any cloud supplier.
  4. Scalability: Containers are light-weight and begin shortly, making them excellent for scaling companies up or down as wanted.
  5. DevOps pleasant: Containers match completely into trendy CI/CD pipelines, making steady deployment smoother.

Now that you simply perceive the advantages, let’s containerize an actual Python software! We’ll use Docker, the go-to selection for containerization.

▶️ Earlier than you start: Set up Python and Docker to code alongside.

 

Containerize a Python FastAPI Software

 
We’ll construct and containerize a easy FastAPI app that converts between currencies. This instance walks you thru key ideas you possibly can apply to your individual tasks.

Let’s first create a undertaking listing:

$ mkdir currency-api
$ cd currency-api

 

Subsequent, create and activate a digital atmosphere:

$ python3 -m venv venv
$ supply venv/bin/activate  # On Home windows: venvScriptsactivate

 

Then set up the mandatory packages:

$ pip3 set up fastapi uvicorn

 

Create a major.py file with the next code:

from fastapi import FastAPI, HTTPException, Question
from pydantic import BaseModel
from typing import Literal

app = FastAPI(title="Foreign money Converter")


class ConversionResponse(BaseModel):
    from_currency: str
    to_currency: str
    quantity: float
    transformed: float
    charge: float


mock_rates = {
    ("USD", "EUR"): 0.91,
    ("EUR", "USD"): 1.10,
    ("USD", "JPY"): 145.0,
}


@app.get("/convert", response_model=ConversionResponse)
def convert(
    quantity: float = Question(..., gt=0),
    from_currency: Literal["USD", "EUR"] = "USD",
    to_currency: Literal["USD", "EUR", "JPY"] = "EUR",
):
    if from_currency == to_currency:
        elevate HTTPException(
            status_code=400, element="From and to currencies should differ."
        )

    charge = mock_rates.get((from_currency, to_currency))
    if not charge:
        elevate HTTPException(status_code=400, element="Conversion charge not obtainable.")

    transformed = quantity * charge
    return ConversionResponse(
        from_currency=from_currency,
        to_currency=to_currency,
        quantity=quantity,
        transformed=spherical(transformed, 2),
        charge=charge,
    )

 

This creates an API endpoint /convert that takes an quantity, supply foreign money, and goal foreign money, validates them. It then makes use of mock change charges to transform the quantity and returns the end in a structured JSON format.

 

Step 2: Create a necessities.txt File

Subsequent, create a necessities.txt file:

fastapi==0.115.12
uvicorn==0.34.2

 

This file pins particular variations of our dependencies to make sure our container builds constantly.

 

Step 3: Create a Dockerfile

Now for the principle occasion: creating our Dockerfile. That is the important thing step within the containerization course of.

Right here’s the Dockerfile:

# Use official Python picture
FROM python:3.11-slim

# Set work listing
WORKDIR /app

# Set up dependencies
COPY necessities.txt .
RUN pip set up --no-cache-dir -r necessities.txt

# Copy app code
COPY . .

# Expose port
EXPOSE 8000

# Run the app
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

 
Let’s break down what this Dockerfile does:

  • Base picture: We begin with python:3.11-slim, a light-weight Python picture that is excellent for manufacturing.
  • Setting the working listing: WORKDIR /app creates and units the working listing contained in the container.
  • Dependency set up: We set up all the necessities. This leverages Docker’s layer caching, so altering your app code would not set off a full dependency reinstall.
  • Copying software code: COPY . . copies our code into the container.
  • Port publicity: EXPOSE 8000 tells Docker which port the applying makes use of.
  • Startup command: Lastly, we use Uvicorn to run our FastAPI app with the correct configuration for container environments.

 

Step 4: Create a .dockerignore File

You may add a .dockerignore file to maintain your container lean.

This file is like .gitignore on your tasks. It prevents pointless information from being copied into the container atmosphere.

This retains the container measurement small and avoids potential points with native improvement information.

Right here’s an instance .dockerignore file.

 

Step 5: Construct and Run Your Container

Now let’s construct and run our containerized software:

# Construct the Docker picture
$ docker construct -t currency-api .

# Run the container
$ docker run -p 8000:8000 currency-api

 

These instructions:

  1. Construct a Docker picture named currency-api from the present listing (notice the dot on the finish)
  2. Run a container from this picture, mapping port 8000 in your host to port 8000 within the container

Your FastAPI app is now working in a container! Now you can entry the app at http://localhost:8000.

 

Step 6: Check the Containerized API

Check your API endpoints. Let’s use cURL to ship a conversion request to our API’s /convert endpoint like so:

$ curl "http://localhost:8000/convert?quantity=100&from_currency=USD&to_currency=EUR"

 

Output:

{
	"from_currency": "USD",
	"to_currency": "EUR",
	"quantity": 100.0,
	"transformed": 91.0,
	"charge": 0.91,
}

 

Wrapping Up

 
And there you’ve got it! Your Python FastAPI software is now containerized and prepared for prime time. This method works for just about any Python software, not simply FastAPI. The identical ideas apply whether or not you are containerizing Flask, Django, or every other Python framework.

The precise worth of containerization comes once you begin deploying to completely different environments. Now you possibly can confidently push your containerized app to improvement, staging, or manufacturing environments understanding it would behave constantly all over the place.

What’s subsequent? Take into account exploring Docker Compose for multi-container functions, container orchestration with Kubernetes, or CI/CD pipelines to construct in your new containerization expertise.

Completely satisfied containerizing!
 
 

Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, knowledge science, and content material creation. Her areas of curiosity and experience embody DevOps, knowledge science, and pure language processing. She enjoys studying, writing, coding, and occasional! At the moment, she’s engaged on studying and sharing her information with the developer neighborhood by authoring tutorials, how-to guides, opinion items, and extra. Bala additionally creates partaking useful resource overviews and coding tutorials.



Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

PHP Code Snippets Powered By : XYZScripts.com