├── .gitignore ├── LICENSE ├── README.md └── src ├── .dockerignore ├── Dockerfile ├── main.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints 2 | .vscode 3 | src/service_account_credentials.json 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | pip-wheel-metadata/ 28 | share/python-wheels/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | MANIFEST 33 | 34 | # PyInstaller 35 | # Usually these files are written by a python script from a template 36 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 37 | *.manifest 38 | *.spec 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .nox/ 48 | .coverage 49 | .coverage.* 50 | .cache 51 | nosetests.xml 52 | coverage.xml 53 | *.cover 54 | *.py,cover 55 | .hypothesis/ 56 | .pytest_cache/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 99 | __pypackages__/ 100 | 101 | # Celery stuff 102 | celerybeat-schedule 103 | celerybeat.pid 104 | 105 | # SageMath parsed files 106 | *.sage.py 107 | 108 | # Environments 109 | .env 110 | .venv 111 | env/ 112 | venv/ 113 | ENV/ 114 | env.bak/ 115 | venv.bak/ 116 | 117 | # Spyder project settings 118 | .spyderproject 119 | .spyproject 120 | 121 | # Rope project settings 122 | .ropeproject 123 | 124 | # mkdocs documentation 125 | /site 126 | 127 | # mypy 128 | .mypy_cache/ 129 | .dmypy.json 130 | dmypy.json 131 | 132 | # Pyre type checker 133 | .pyre/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Sebastian Kraus 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deploying a FastAPI app on Google Cloud Run 2 | This is a very simple hello-world-walkthrough with FastAPI and Cloud Run. 3 | 4 | 5 | ## Initial Setup 6 | To play through this tutorial, I recommend creating a new project. You can do this in the console or [with the Cloud SDK](https://cloud.google.com/sdk/gcloud/reference/projects/create) (recommended). You can find your billing account id [here](https://console.cloud.google.com/billing) 7 | 8 | 9 | Create your new project. 10 | ```bash 11 | export PROJECT_ID= 12 | export BILLING_ACCOUNT_ID= 13 | export APP=myapp 14 | export PORT=1234 15 | export REGION="europe-west3" 16 | export TAG="gcr.io/$PROJECT_ID/$APP" 17 | 18 | gcloud projects create $PROJECT_ID --name="My FastAPI App" 19 | 20 | # Set Default Project (all later commands will use it) 21 | gcloud config set project $PROJECT_ID 22 | 23 | # Add Billing Account (no free lunch^^) 24 | gcloud beta billing projects link $PROJECT_ID --billing-account=$BILLING_ACCOUNT_ID 25 | ``` 26 | 27 | Enable the services you need. 28 | ```bash 29 | gcloud services enable cloudbuild.googleapis.com \ 30 | containerregistry.googleapis.com \ 31 | run.googleapis.com 32 | ``` 33 | 34 | ## Simple Hello World App 35 | 36 | Let's keep it bloody simple and focus on the general process. This is a our hello world app `src/main.py`. 37 | ```python 38 | from fastapi import FastAPI 39 | 40 | app = FastAPI() 41 | 42 | 43 | @app.get("/") 44 | async def root(): 45 | return {"message": "Hello World"} 46 | ``` 47 | 48 | If you want to test it locally, run: 49 | ```bash 50 | pip install -r src/requirements.txt 51 | cd src 52 | uvicorn main:app --reload 53 | ``` 54 | 55 | You can check the output in your browser by opening http://127.0.0.1:1234 or "curling" the app in another terminal tab via: 56 | ```bash 57 | curl http://127.0.0.1:$PORT 58 | ``` 59 | As a response you'll see `{"message":"Hello World"}`. 60 | 61 | ## App into Docker 62 | 63 | You need to put your app into an image before deploying it. Here you see an example docker file. Note that you should use a PORT as environment variable. If you don't you'll get an error like `Cloud Run error: The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable.` 64 | 65 | ```docker 66 | FROM python:3.9-slim@sha256:980b778550c0d938574f1b556362b27601ea5c620130a572feb63ac1df03eda5 67 | 68 | ENV PYTHONUNBUFFERED True 69 | 70 | ENV APP_HOME /app 71 | WORKDIR $APP_HOME 72 | COPY . ./ 73 | 74 | ENV PORT 1234 75 | 76 | RUN pip install --no-cache-dir -r requirements.txt 77 | 78 | # As an example here we're running the web service with one worker on uvicorn. 79 | CMD exec uvicorn main:app --host 0.0.0.0 --port ${PORT} --workers 1 80 | ``` 81 | 82 | To try your app locally with docker simply run inside `src`: 83 | ```bash 84 | docker build -t $TAG . 85 | docker run -dp $PORT:$PORT -e PORT=$PORT $TAG 86 | ``` 87 | 88 | Again you can check it in your browser our curl it: 89 | ```bash 90 | curl http://127.0.0.1:$PORT 91 | ``` 92 | 93 | ## Deployment 94 | If everything worked out so far, we're ready to deploy our app. First we create a Google Cloud Build. Maybe it's similar to pushing a docker image to a docker registry. 95 | 96 | ```bash 97 | gcloud builds submit --tag $TAG 98 | ``` 99 | 100 | After this is done, well it's finally time to deploy your cloud run app :). 101 | ```bash 102 | gcloud run deploy $APP --image $TAG --platform managed --region $REGION --allow-unauthenticated 103 | ``` 104 | 105 | ## Test it 106 | Note, this may take some minutes. The URL of your app will show up in the terminal. But you can also check your app via: 107 | ```bash 108 | # See all info about the app 109 | gcloud run services describe $APP --region $REGION 110 | ``` 111 | 112 | Note, even though we've chosen a random port like `1234`, the deployed service will use `8080` by default. This is why we need `--port ${PORT}` in the last line of our Dockerfile. 113 | 114 | Let's send a request to our app. 115 | ```bash 116 | # get url 117 | URL=$(gcloud run services describe $APP --region $REGION --format 'value(status.url)') 118 | 119 | curl $URL 120 | ``` 121 | Perfect! Again, we receive `{"message":"Hello World"}`. 122 | 123 | ## Clean up 124 | If you don't need the app anymore remove it. (You may also delete the whole project instead.) 125 | ```bash 126 | gcloud run services delete $APP --region $REGION 127 | 128 | # Check if it disAPPeared (optional) 129 | gcloud run services list 130 | ``` -------------------------------------------------------------------------------- /src/.dockerignore: -------------------------------------------------------------------------------- 1 | __pycache__ -------------------------------------------------------------------------------- /src/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.9-slim@sha256:980b778550c0d938574f1b556362b27601ea5c620130a572feb63ac1df03eda5 2 | 3 | ENV PYTHONUNBUFFERED True 4 | 5 | ENV APP_HOME /app 6 | WORKDIR $APP_HOME 7 | COPY . ./ 8 | 9 | ENV PORT 1234 10 | 11 | RUN pip install --no-cache-dir -r requirements.txt 12 | 13 | # As an example here we're running the web service with one worker on uvicorn. 14 | CMD exec uvicorn main:app --host 0.0.0.0 --port ${PORT} --workers 1 -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | 3 | app = FastAPI() 4 | 5 | 6 | @app.get("/") 7 | async def root(): 8 | return {"message": "Hello World"} 9 | -------------------------------------------------------------------------------- /src/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi==0.75.0 2 | uvicorn==0.17.6 --------------------------------------------------------------------------------