Pre-requisites
Make sure your MacOS to be version 10.14 or higher, It's recommended that you upgrade the MacOS to the latest one. Make sure you have at least 4 GB of RAM. If all set, you can directly download the Docker Desktop for Mac here.
Install and Run Docker Desktop
Drag and drop the Docker icon to Applications folder after you double clicked the downloaded Docker.dmg file
To start the Docker, double click the Docker.app file inside Applications folder.
Check the docker menu in the top status bar to check if Docker application is up and running.
Congratulation now you have already successfully installed Docker application inside your MacOS.
Deploy FastAPI inside Docker
First of all install the FastApi and Uvicorn using:
pip install fastapi
pip install uvicorn[standard]
After that, create your FastAPI project directory with this structure:
Inside the app directory create main.py file and insert these line of codes:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Next, run the live server using Uvicorn:
The result will be like this:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
If you open the browser and go to http://127.0.0.1:8000/ it should appear like this:
If you go to http://127.0.0.1:8000/docs/ it will show Swagger UI for your API:
Congratulations! Now you have successfully installed FastAPI inside your machine. Now we proceed to deploy the FastAPI to the Docker app.
Deploy FastAPI to Docker Application
First of all, create Dockerfile inside your project directory and put these line of codes:
FROM python:3.7
RUN pip install fastapi uvicorn
EXPOSE 80
COPY ./app /app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
Your project structure now should be like this:
.
├── app
│ └── main.py
└── Dockerfile
To run the Docker directly you can use these commands:
docker build -t myimage .
docker run -d --name mycontainer -p 80:80 myimage
If you want to run the Docker via Docker Compose you can create docker-compose.yml file inside project root directory and put:
version: "3.8"
services:
fastapi:
build: "."
ports: "8080:80"
After that run:
docker-compose up --build
Congratulations! Now you have succesfully deploy FastAPI inside Docker application. If you want to learn how to develop front end application using React JS you can follow this tutorial.