Compose sample FastAPI application

Project structure

1
2
3
4
5
6
├── compose.yaml
├── Dockerfile
├── requirements.txt
├── app
   ├── main.py
   ├── __init__.py

compose.yaml

1
2
3
4
5
6
7
8
9
services:
api:
    build: .
    container_name: fastapi-application
    environment:
    PORT: 8000
    ports:
    - '8000:8000'
    restart: "no"

main.py

1
2
3
4
5
6
7
8
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def hello_world():
    return {"message": "OK"}

Deploy with docker compose

1
docker-compose up -d --build

Expected result

Listing containers must show one container running and the port mapping as below.

run: docker ps

After the application starts, navigate to http://localhost:8000 in your web browser and you should see the following json response:

1
2
3
{
"message": "OK"
}

Stop and remove the containers

1
$ docker compose down