AliBigdeli / FastApi-Hamravesh-Docker-Template

sample project to show you how to deploy FastApi Projects into hamravesh service provider

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

FastAPI Hamravesh Template

Sample Project to use hamravesh service provider for FastAPI app

python fastapi docker postgresql git git

Guideline

Goal

This project main goal is to provide a simple way to deploy a fastapi project into hamravesh service provider.

Video Instructions

Development usage

You'll need to have Docker installed. It's available on Windows, macOS and most distros of Linux.

If you're using Windows, it will be expected that you're following along inside of WSL or WSL 2.

That's because we're going to be running shell commands. You can always modify these commands for PowerShell if you want.

Clone the repo

Clone this repo anywhere you want and move into the directory:

git clone https://github.com/AliBigdeli/FastAPI-Hamravesh-Docker-Template.git

Enviroment Varibales

environment variables are included in docker-compose.yml file for debugging mode and you are free to change commands inside:

  backend:
    build: 
      context: .
      dockerfile: dockerfiles/dev/fastapi/Dockerfile
    container_name: backend
    command: sh -c "uvicorn main:app --host 0.0.0.0 --port 8000 --reload"
    volumes:
      - ./core:/usr/src/app
    # env_file:
    # - envs/dev/fastapi/.env
    ports:
      - "8000:8000"
    environment:
      - PGDB_PORT=5432
      - PGDB_PASSWORD=postgres
      - PGDB_USERNAME=postgres
      - PGDB_DBNAME=postgres
      - PGDB_HOSTNAME=postgresdb
      - ENABLE_SENTRY=False
      - SENTRY_DSN=None
      # - MGDB_PORT=27017
      # - MGDB_PASSWORD=mongo
      # - MGDB_USERNAME=mongo
      # - MGDB_DBNAME=mongo
      # - MGDB_HOSTNAME=mongodb


      
    depends_on:
      - postgresdb
      # - mongodb

Build everything

The first time you run this it's going to take 5-10 minutes depending on your internet connection speed and computer's hardware specs. That's because it's going to download a few Docker images and build the Python + requirements dependencies.

docker compose up --build

Now that everything is built and running we can treat it like any other FastAPI app.

Note

If you receive an error about a port being in use? Chances are it's because something on your machine is already running on port 8000. then you have to change the docker-compose.yml file according to your needs.

Check it out in a browser

Visit http://localhost:8000/swagger in your favorite browser.

Testing Usage

running all tests

docker compose run --rm backend sh -c " black -l 79 && flake8 && pytest ." -v core:/usr/src/app

or

docker compose exec backend sh -c sh -c " black -l 79 && flake8 && pytest ." 

Hamravesh deployment

0- Create an account

in order to deploy your project inside hamravesh first you need to create an account. so please go to the following url and create your account.

https://console.hamravesh.com/signup

after that you need to sign in to your console panel. which is going to be like this.

1- Setup database

follow the provided steps to finish this section.

surely you are going to need a postgres database or mongodb for your deployment so all you have to do is to create a database app first. in the app section click on the PostgreSQL/MongoDB database.

then in the next window pick a name for the database service name.

Note: in our case we dont need to access the database through the internet.

after that just choose a plan for it and create the database instance.

now that your database is created you can use it for connecting other apps to it.

the provided database credentials and url are as follows:

PGDB_address: my-site-postgre.bigdeliali3.svc:5432
PGDB_username: postgres
PGDB_password: ddGrZM7u3BsduXm5ph3WzPYlMWSMTXbu
# note: it will be different for using mongodb, but at the end you will end up with: host,port,username,password

Note: if you dont want to use the default database by the name of postgres, you just have to head to the terminal tab and create a another database for your project you can call it anything you want.

psql -U postgres -c "create database <PGDB_name>"

2- Create a repo app

in order to deploy your project you can use repo mode (or منبع گیت) after clicking on the item. you will see a panel like this below:

as you can see you have to provide your github/gitlab/hamgit repo address for deployment. in our case the configuration will be as follow:

repo_address: https://github.com/AliBigdeli/FastAPI-Hamravesh-Docker-Template.git
# if you are just testing without cicd use main or if you want to use cicd script to delpoy create a prod branch and then add it here
branch_name: main
build_context: .
docker_file_address: ./dockerfiles/prod/fastapi/Dockerfile

Note: as we are going to implement ci/cd and other stuffs we avoid auto deployment or even uploading file.

after your done with the inputs just click on (تنظیمات اپ) and go for next step.

3- Setup fastapi app

follow the provided steps to finish this section.

1- General info

in this page you have to provide general information's about the app you are about to create, which in my case are as follows:

app_name: my-site # name of the app which is going to be called inside the portal
service_port: 8000 # which is based on the uvicorn port
execute_command: uvicorn main:app --proxy-headers --host 0.0.0.0 --port 8000

Note: provided information is just enough to run our program for more details please visit this url https://docs.hamravesh.com/darkube/create/git-repo/settings/general/

2- Environment Variables

in this section you have to provide the environment variables which are going to be used in the project. you can switch to editor and pase our template that is placed in /envs/prod/.env.sample

Note: provided information is just enough to run our program for more details please visit this url https://docs.hamravesh.com/darkube/create/git-repo/settings/envs/

3- Domain Address

pick a name for you app which is going to be accessed through the web and for better security please enable https redirect. keep in mind that you can give a different dns name through a provider like arvan or cloudflare.(we will provide more details for this matter later)

Note: provided information is just enough to run our program for more details please visit this url https://docs.hamravesh.com/darkube/create/git-repo/settings/domain-address/

4- Pick a plan

for launching purposes you have to pick a plan for resources. based on the scale and traffic of your project you have to pick one.

Note: at the moment we are not using disks and we are just using the static files being served by the Whitenoise.

5- wait until its deployed

now all you have to do is to wait util the project is fully deployed.

after its done you can access the website through the url you picked in stage 3 of the setup.

CICD Deployment

For the sake of continuous integration and deployment i have provided two samples for github and gitlab/hamgit for you. but there will be some configurations to be added for building and deploying purposes.

Github CICD

will be provided soon

Gitlab/Hamgit CICD

in order to do ci/cd in the sample project for gitlab/hamgit you have to create a duplicate of the .gitlab-ci.yml.sample but with different name as .gitlab-ci.yml in the root directory.

after that our pipeline will be always listening to the prod branch. if you commit in this branch it will go through the process.

note that you have to declare 5 or more environment variables in your gitlab/hamgit project repo, which you can add it by going to Settings>CI/CD>Variables, and in this section try to add all the needed variables.

these variables should be included:

  • DARKUBE_APP_ID - which can be found in app info page
  • DARKUBE_DEPLOY_TOKEN - which can be found in app info page
  • IMAGE - registry.hamdocker.ir/<USERNAME>/<APPNAME>
  • REGISTERY - registry.hamdocker.ir/<USERNAME>
  • REGISTERY_PASSWORD - registry password
  • REGISTERY_USER - username like 'bigdeliali3'

for having DARKUBE_APP_ID and DARKUB_DEPLOY_TOKEN head to the app page and use the following parameters in the picture.

for having REGISTRY and REGISTRY_USER and REGISTRY_PASSWORD head to the app page and use the following parameters in the picture. REGISTRY will be the url like this: registry.hamdocker.ir/<USERNAME> and for getting the username and passwords just go to the app section and click on docker image. you will see something like this, after that click on registries.

On top of the page you can find the credentials for registry that you need.

after that if everything goes well you can see that the jobs are working.

Sentry Logger

if you need to use sentry logging as a logger for your project all you need to do is to have an account and do modifications in environments cause i have already added the scripts that you need.

0- Create an account

first of all head to the link below and follow instructions to create an account. until you see the dashboard. https://sentry.hamravesh.com/

1- Create Project

Now in order to connect your FastAPI application to the sentry you have to create a project. so click on creating project and then choose FastAPI as your project base, in Setup your default alert settings you can create the alerts you need or you can do it later, and at the end of config just choose a name and select a team and hit Create Project when your done.

Note: for more info you can always check sentry main page in:

2- Implement configs

for ease of use i have already added the scripts plus the requirements that you need for your project as below:

  • requirements.txt
    ...
    sentry-sdk
  • core/main.py
      if settings.ENABLE_SENTRY:
          import sentry_sdk
          sentry_sdk.init(
              dsn=settings.SENTRY_DSN,
    
              # Set traces_sample_rate to 1.0 to capture 100%
              # of transactions for performance monitoring.
              # We recommend adjusting this value in production,
              traces_sample_rate=1.0,
          )
  • envs/prod/fastapi/.env.sample
    SENTRY_ENABLE=True
    SENTRY_DSN=https://xxxx@sentry.hamravesh.com/xxx

as you can see all you have to do is to enable the sentry with putting env in True and replace the dns with the correct url.

3- Throw an Error

for testing purposes i already had put a url inside project to create an error to log it inside the sentry for checking the configuration you can uncomment it again after test.

  • core/main.py
    @app.get("/sentry-debug")
      async def trigger_error():
          division_by_zero = 1 / 0

4- Test logging mechanism

now just head to the url that we have as https://app_name.darkube.app/sentry-debug/ nd create a purposely error. then inside the project page you can see the log of error which happened in your project to get a 500 error.

then head to the dashboard and inside project page you can see an issue

License

MIT.

Bugs

Feel free to let me know if something needs to be fixed. or even any features seems to be needed in this repo.

About

sample project to show you how to deploy FastApi Projects into hamravesh service provider

License:MIT License


Languages

Language:Python 88.9%Language:Dockerfile 11.1%