My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Getting started with FastAPI and Docker

frank jam's photo
frank jam
·Nov 12, 2021·

2 min read

Introduction

What is Docker

Docker is a platform for developing, shipping, and running applications. It lets you separate applications from infrastructure, so you can deliver software quickly.

What is FastAPI

FastAPI is a modern, high-performance, web framework for building APIs with Python 3.6 and above based on standard Python type hints.

Setting up the development lab and code creation

Step 1: Installing modules

Uvicorn works as server. FAstAPI is a Web framework for developing RESTful APIs in Python . Virtualenv is a tool for creating isolated Python environments.

pip install fastapi 
pip install uvicorn
pip install virtualenv

Step 2: Environment creation

py -m venv env

Step 3: Virtual environment activation

source env/bin/activate

Step 4: Creating requirements.txt file

pip freeze >  requirements.txt

Step 5: Code development

app.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

Step 6: Docker file creation

Dockerfile


FROM python:3.9

WORKDIR /code

EXPOSE 80:80

COPY ./requirements.txt /code/requirements.txt

RUN  pip install --no-cache-dir --upgrade -r /code/requirements.txt

COPY ./app /code/app

CMD ["python", "app.py"]

Step 7: Building the Docker image

docker build -t myimage .

Step 8: Start the Docker Container

docker run -p 80:80 -t -i myimage

Now in your local browser visit http://127.0.0.1:80