A minimal example showing how to run a FastAPI application inside a Docker container. This project demonstrates containerizing a simple API with a Dockerfile and running it using uvicorn.
fastapi-docker-demo/
├── app
│ └── main.py
├── Dockerfile
└── requirements.txt
The API exposes two endpoints:
| Method | Endpoint | Description |
|---|---|---|
| GET | / |
Returns a simple message and current timestamp |
| POST | /items |
Accepts an item payload and returns it with a processing timestamp |
The API uses a Pydantic model to validate request data.
class Item(BaseModel):
name: str
price: float
is_available: bool = TrueExample request body:
{
"name": "Laptop",
"price": 1200.50,
"is_available": true
}- Docker installed
- Internet connection to pull the Python base image
Dependencies defined in requirements.txt:
fastapi
uvicorn[standard]
From the project root directory:
docker build -t fastapi-docker-demo .docker run -p 8000:8000 fastapi-docker-demoThe API will now be available at:
http://localhost:8000
curl http://localhost:8000Example response:
{
"message": "FastAPI running inside Docker 🚀",
"timestamp": "2026-03-12T10:00:00"
}curl -X POST http://localhost:8000/items \
-H "Content-Type: application/json" \
-d '{"name":"Phone","price":699.99}'Example response:
{
"received_item": {
"name": "Phone",
"price": 699.99,
"is_available": true
},
"processed_at": "2026-03-12T10:02:00"
}FastAPI automatically generates API documentation.
| Interface | URL |
|---|---|
| Swagger UI | http://localhost:8000/docs |
| ReDoc | http://localhost:8000/redoc |
Key steps in the Dockerfile:
- Use a lightweight Python base image.
- Set a working directory inside the container.
- Install dependencies from
requirements.txt. - Copy the application source code.
- Expose port
8000. - Start the API server with
uvicorn.
For local development:
pip install -r requirements.txt
uvicorn app.main:app --reloadThen open:
http://localhost:8000/docs
This project is for demonstration and learning purposes.