Recently, I often use Fast API, and I wanted to build it quickly with Docker and throw it away. As a memo, I would like to leave a way to build it lightweight.
--Environment where Docker and Docker Compose can be used
version
$ docker --version
Docker version 19.03.8, build afacb8b7f0
--The file structure looks like this
file organization
.
├── Dockerfile
├── docker-compose.yml
├── main.py
└── requirements.txt
You can clone from here https://github.com/sattosan/sample-fastapi-alpine
Dockerfile Made based on alpine
Dockerfile
FROM python:3.8-alpine
WORKDIR /app
ADD requirements.txt .
#Install the required packages inside the container
RUN apk add --no-cache build-base mariadb-connector-c-dev
# requirements.Install the Python packages listed in txt
RUN pip install --no-cache-dir --trusted-host pypi.python.org -r requirements.txt
ADD main.py .
#Wait for FastAPI on port 8000
CMD ["uvicorn", "main:app", "--reload", "--host", "0.0.0.0", "--port", "8000"]
Docker Compose
docker-compose.yml
version: "3.0"
services:
# FastAPI
api:
container_name: "api"
build: .
restart: always
tty: true
ports:
- 8000:8000
requirements.txt
uvicorn
fastapi
I have prepared the sample code in the FastAPI documentation (https://fastapi.tiangolo.com/).
main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
$ docker-compose up -d --build
--Alpine-based Image size
docker images | grep api
latest bff0158b61ca 29 minutes ago 275MB
--Image size of the head family
It is the result of building with reference to Honke
$ docker images | grep api
latest 878110f2207f 11 seconds ago 1.02GB
You can see that it was reduced by 3.6 times compared to the original family
APIs generated by FastAPI are automatically documented by Swagger
You can see the documentation by accessing domain / docs
http://localhost:8000/docs
If you hit it with curl, it will come back like this
result
$ curl localhost:8000
{"Hello":"World"}
This time, I tried to build a lightweight development environment based on alpine.
It is 3.6 times lighter than the original house, so I think it is a sufficient environment for disposable items. Recently, the Fast API has begun to be used in various projects including Netflix, so If you haven't used it yet, please try it!
--Netflix OSS: https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072
--Honke: https://fastapi.tiangolo.com/