Deploy FastAPI on Heroku using Docker Container

Akshay Khatale
2 min readMar 21, 2021

Hello Developer’s, Some time ago I wanted to deploy API using FastAPI on heroku, I looked everywhere tried everything to deploy it on heroku stack but it did not worked. So I tried to deploy using Docker and in this tutorial I will show how I did it.

Why FastAPI ?

As you all know python does not support concurrency. Flask and Django are the framework which are very slow and are not support async, on the other hand FastAPI built on Starlette which is asynchronous webserver wich can be as fast as node.js or golang, And you also get a nice intuitive docs of your endpoint created using Swagger.

Prerequsites

  1. A Heroku Account
  2. Heroku CLI

3. Python Basic Knoledge

4.Docker Basic Knoledge

Step 1: Create App

Open your heroku account and click on “new” then “Create New App” then name your app and click “Create App”.

Step 1
Step 1

Step 2: Create Docker And Python Files

First we will be creating Python file for our simple app in app folder ‘main.py’.

from fastapi import FastAPIapp = FastAPI()@app.get("/")def read_root():return {"Hello": "World"}

Then we will create shell script(start.sh) with heroku $PORT envirnment variable to start uvicorn server wich is ASGI we will be using to serve our app.

#/bin/shuvicorn app.main:app --host 0.0.0.0 --port $PORT

Then we will create Dockerfile with python 3.7 alpine as base.

FROM python:3.7-alpineRUN pip install fastapi uvicornCOPY ./start.sh /start.shRUN chmod +x /start.shCOPY ./app /appCMD ["./start.sh"]

And at last we will create docker-compose file in root wich will tell heroku the what type of Dyno it is and other config

version: "3.9"services:web:build: .volumes:- ./app:/app

Now our directory stucture should look like this.

root
|-app
| |-main.py
|-start.sh
|-Dockerfile
|-docker-compose.yml

Step 3: Deploy to Heroku using Heroku CLI

First we have to login to the Heroku CLI using command below, then you will be automatically authenticated in Browser.

$ heroku login

Then we have to login to heroku container registry using command:

$ heroku container:login

Then we will push the container to the heroku using command :

$ heroku container:push web --app akshayone#replace akshayone with your app name

And in the end its time to relese the contianer for this we will run:

$ heroku container:release web --app akshayone

Done, your app is deployed on heroku.

Clone from github repository Github Heroku Docker

--

--