HomeAbout Us
Deploy FastApi with Docker in Mac Environment
coding
Deploy FastApi with Docker in Mac Environment
Kevin Mustafa
Kevin Mustafa
July 30, 2021
1 min

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:

PROJECT_NAME/app/

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:

uvicorn main:app --reload

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.


Tags

#coding#developer#docker#getting-started#open-source#python#tools#web-development#web-framework#web-servers
Kevin Mustafa

Kevin Mustafa

Indonesia

I am Kevin, nice to meet you.

Expertise

Related Posts

Top 7 Coding Challenges
Top 7 Coding Challenges
August 21, 2021
1 min
© 2021, All Rights Reserved.

Quick Links

About Us