This tutorial demonstrates how to containerize a FastAPI application using Docker and Docker Compose.
Lab1/
├── app/
│ └── main.py # FastAPI application
├── Dockerfile # Docker configuration
├── docker-compose.yml # Docker Compose configuration
├── requirements.txt # Python dependencies
└── README.md # This file
- Docker installed on your system
- Docker Compose (included with Docker Desktop for Windows/Mac)
The application is a simple FastAPI REST API with the following endpoints:
- GET
/: Returns a welcome message - GET
/items/{item_id}: Returns item details for a given ID - POST
/items/: Creates a new item
cd Lab1
docker build -t fastapi-tutorial .docker run -p 8000:8000 --name fastapi-app fastapi-tutorialStop the container:
docker stop fastapi-appRemove the container:
docker rm fastapi-appList all containers:
docker ps -aList all images:
docker imagescd Lab1
docker compose upTo run in detached mode (background):
docker compose up -ddocker compose downOnce the application is running, you can access:
- API documentation: http://localhost:8000/docs
- API root endpoint: http://localhost:8000/
Example to create an item using curl:
curl -X POST http://localhost:8000/items/ \
-H "Content-Type: application/json" \
-d '{"name": "Test Item", "price": 10.5, "description": "This is a test item"}'Example to get an item:
curl http://localhost:8000/items/1When using Docker Compose, changes to the files in the app directory will automatically be reflected in the container due to the volume mounting configuration.
FROM python:3.9-slim: Uses Python 3.9 slim as the base imageWORKDIR /app: Sets the working directoryCOPY requirements.txt .: Copies the requirements fileRUN pip install...: Installs the dependenciesCOPY ./app /app: Copies the application codeEXPOSE 8000: Documents that the container listens on port 8000CMD ["uvicorn"...]: Specifies the command to run the application
The docker-compose.yml file defines the service configuration:
build: Builds the image from the Dockerfileports: Maps host port 8000 to container port 8000volumes: Mounts localappdirectory to container/apprestart: Automatically restarts the container unless stopped