Skip to content

advissor/python3-fastapi-dockerfile

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Dockerizing a FastAPI application

Demo application

This is a simple FastAPI application that allows you to return invoice information.

Create Invoice

  • Endpoint: /invoice

  • Method: POST

  • Description: Creates a new invoice with customer details and line items

  • Request Body:

    {
      "customer_name": "Acme Corp",
      "customer_email": "[email protected]",
      "items": [
        {
          "description": "Consulting Services",
          "quantity": 10,
          "unit_price": 150.00
        }
      ]
    }

Example response:

{"customer_name":"Acme Corp","customer_email":"[email protected]","items":[{"description":"Consulting Services","quantity":"10","unit_price":"150.0"}],"invoice_number":"INV-202412-5caff017","created_at":"2024-12-15T23:29:45.876903","total_amount":"1500.0"}%

Launching the application locally

pip install -r src/requirements.txt

gunicorn --workers 4 \
         --worker-class uvicorn.workers.UvicornWorker \
         --bind 0.0.0.0:8080 \
         --reload \
         src.server:app

Refer to Testing the application for more details

Buiilding the Docker image

docker build -t python-docker:v1.0.0 .

Running the Docker image

docker run --rm -it -e PORT=8080 -p 8080:8080 python-docker:v1.0.0

Testing the Docker image

Open the API Docs page:

    http://0.0.0.0:8080/docs

Testing the application

curl -X POST http://localhost:8080/invoice \
-H "Content-Type: application/json" \
-d '{
    "customer_name": "Acme Corp",
    "customer_email": "[email protected]",
    "items": [
        {
            "description": "Consulting Services",
            "quantity": 10,
            "unit_price": 150.00
        }
    ]
}'

Using a docker-slim (4x size reduction; 201MB -> 50MB)

Docker Slim Documentation

    slim build --target python-docker:v1.0.0  --tag python-docker:v1.0.0-slim
    docker run --rm -it -e PORT=8080 -p 8080:8080 python-docker:v1.0.0-slim

Docker Image Size Comparison

Look for artifacts in the build directory (in log outputs)

About

Example of prod ready fastapi Dockerfile

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published