Hosting Flask servers on Firebase from scratch

Python devs 🐍! Rejoice 🎉! Firebase Hosting 🔥 supports dynamic server backends with Cloud Run 🏃‍♂️! Alright. That’s enough emojis. Time to dive into the details.

Wait; isn’t Firebase Hosting just for static web pages?

Any server backend with Cloud Run

Note: You don’t need to install Docker

Step 0 — Project structure

flask-fire (root dir)
├── server
| ├── src
| └── app.py
| └── templates
| └── index.html
| ├── Dockerfile
├── static
| └── style.css
├── firebase.json
├── .firebaserc

Step 1 — Setup a simple Flask server

Step 2 — Creating a Dockerfile

  1. This sets the base image of the container. Your code will run on a version of Python 3.7.
  2. Install the needed dependencies to run the server: Flask and gunicorn.
  3. Copy the server’s source files into a folder within the container named app. Then set the working directory to that app folder.
  4. Set an environment variable for the port for 8080. Note: Cloud Run expects the port to be 8080.
  5. Run gunicorn bound to the 8080 port.

Step 3 — Create a Firebase project and enable billing

Cloud Run has a free tier

Cloud Run’s free tier at the time of this writing.
Cloud Run’s free tier at the time of this writing

Step 4 — Build the container with Cloud Build

gcloud init
gcloud builds submit --tag gcr.io/<project-id>/flask-fire

Step 5 — Deploy the container to Cloud Run

gcloud beta run deploy --image gcr.io/<project-id>/flask-fire

Step 6 — Set up Firebase Hosting

npm init -y # creates a package.json
npm install -D firebase-tools
./node_modules/.bin/firebase init hosting
Select a default Firebase project for this directory: (Use arrow keys)
> your-project-id
Select a default Firebase project for this directory: <project-id>
What do you want to use as your public directory? static
Configure as a single-page app (rewrite all urls to /index.html)? N

Make sure no index.html exists!

rm static/index.html # Mac/Linux
del static/index.html # Windows

Add a style.css in the static directory

Step 7 — Hook up Cloud Run to Firebase Hosting

./node_modules/.bin/firebase serve

Step 8— Static and Dynamic

Cache-Control: public,max-age=300,s-maxage=600
  1. Create the template given the context.
  2. Create a response with the template.
  3. Attach a Cache-Control header to control store the content for a 10 minute period in the local CDN edge server. This time period is referred to as a Time To Live or TTL.

Step 9 — Deploy to Firebase Hosting

gcloud builds submit --tag gcr.io/<project-id>/flask-fire
gcloud beta run deploy --image gcr.io/<project-id>/flask-fire
firebase deploy

Finished!

Send us your Flask apps!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David East

David East

3.5K Followers

Developer Advocate at Google. Working on the Firebases.