How to Deploy a Web Application to Cloud Run Automatically | by Lynn Kwong | Apr, 2022

Apply CI/CD to your net purposes

Picture by kreatikar in Pixabay

Utilizing some net Python net frameworks like Flask, Django, or FastAPI, you possibly can develop your APIs or net purposes simply in Python. As a Python developer, these frameworks are native and straightforward to get began since you don’t must be taught a complete new front-end language like JavaScript plus its frameworks comparable to React, Angular, Vue, and so on.

This text shouldn’t be about methods to develop APIs or net purposes with a Python framework. Nevertheless, it’s targeted on methods to deploy an internet software to Cloud Run repeatedly. The Flask framework is chosen as a result of it’s easy to make use of and has a big group. The procedures launched on this submit are relevant to all Python frameworks.

Set up Flask domestically

Earlier than deploying our code to the Cloud in a manufacturing setting, we have to develop it domestically and get every thing prepared.

Step one is to put in the framework in your pc. It’s beneficial to put in Flask in a digital setting so it gained’t intrude with system libraries. Apart from, you possibly can set up completely different variations of Flask in numerous digital environments.

We are able to use the Python native venv library to handle your digital environments. Alternatively, you should use conda as a result of you possibly can set up completely different variations of Python with conda conveniently. Apart from, you possibly can activate your digital environments from wherever and don’t want to fret concerning the metadata for the digital setting. Examine here if you wish to be taught a bit extra about conda.

(base)$ conda create --name flask python=3.10
(base)$ conda activate flask
(flask)$ pip set up Flask==2.1.1

Apart from Flask, a number of dependencies required by Flask are put in mechanically. Now we will begin to create a Flask software domestically.

Put together the Flask software domestically

We are going to create a brilliant easy “Hi there World!” Flask software as a result of the main target is the configurations for steady deployment (CD) as can be launched quickly.

Create a folder referred to as my_app, and navigate into it. Then create a file named app.py. You may give it any title you want, however it’s widespread to call it app.py or wsgi.py so some native net servers can discover it simply. Add the next code to app.py:

Since we’re studying the title of the applying from an setting variable, let’s set it first:

$ export APP_NAME='My enjoyable flask App'

Later we are going to see methods to set an setting in Cloud Run.

$ python app.py# OR$ export FLASK_ENV=improvement
$ flask run -p 5000

If port 5000 is used, you’ll find and cease the present software if need:

$ sudo lsof -i -P -n | grep -ie 'b5000b'
$ kill <PID>

Alternatively, you possibly can specify a unique port for app.run or flask run as proven above. When Flask is run, you possibly can see the next data within the console:

In case you go to http://127.0.0.1:5000, you shall the greeting from our software:

Take a look at gunicorn domestically

Since we are going to use gunicorn to serve our Flask software in Cloud Run later, let’s set up it domestically and ensure the applying will be served by gunicorn.

gunicorn will be put in with pip in your digital setting:

$ pip set up gunicorn==20.1.0

Now we will serve the applying with gunicorn:

$ gunicorn --bind :5001 app:app

In case you didn’t cease the Flask software run above, you would wish to specify a unique port right here. The --bind choice takes the type of IP:port. Notice that IP will be omitted however the colon have to be current. If IP is omitted, then gunicorn is sure to 127.0.0.1.

Apart from, the applying is specified within the type of APP_MODULE:APP_INSTANCE_NAME. In our software, each the module and software occasion are named as app, however they are often completely different in your software. Particularly, if you happen to create the applying occasion by way of an software manufacturing unit as demonstrated within the Flask tutorial, you would wish to begin the applying within the type of APP_MODULE:APP_FACTORY_FUNC(), specifically, that you must explicitly name the applying manufacturing unit to create an software occasion.

Create necessities.txt

We now have put in some libraries within the native digital setting. These libraries should be put in in Cloud Run as properly for Flask to work correctly there. To do that, we have to put all of the required libraries in a file referred to as necessities.txt, which is a regular file required by Python to specify library dependencies.

We have to put Flask and gunicorn in necessities.txt:

# requirments.txt
Flask==2.1.1
gunicorn==20.1.0

In case your software requires different libraries, they need to even be added. Apart from, if that you must set up some helper libraries in your native digital environments like mypy and pylint, however don’t need to set up them within the manufacturing requriements.txt, you possibly can create an extra file referred to as requirements-dev.txt and put them there. The title of this file shouldn’t be vital, however requirements-dev.txt is a generally used one.

Create a Dockerfile

Cloud Run works intently with Cloud Build which builds Docker photos out of your GitHub repositories mechanically. Cloud Run makes use of the Docker photos constructed by Cloud Construct to spin up your purposes. Subsequently, to make use of Cloud Run, you must also have the Cloud Construct API enabled.

The Dockerfile supplied by the official documentation of Cloud Run is an effective instance and may work as it’s most often:

This Dockerfile has good documentation and is easy to know. Particularly, the PORT digital setting can be handed in by Cloud Run mechanically, as we are going to see quickly after we arrange Cloud Run.

Apart from, it’s additionally useful to specify a .dockerignore file to exclude some metadata or short-term recordsdata out of your Docker picture. It could make your picture smaller and look cleaner. A pattern .dockerignore file can comprise the next contents:

Deploy to Cloud Run

You possibly can deploy your Flask software domestically with the next command:

$ gcloud run deploy

Simply comply with the directions to deploy your software step-by-step.

Nevertheless, if you wish to have extra management over the deployment process, it’s higher to make use of the GCP console. And if you wish to arrange a steady deployment (CD) pipeline, it will likely be way more easy to do it within the console.

So let’s head over to the Cloud Run web page in GCP Console. Yow will discover Cloud Run on the left navigation bar, or simply seek for it within the high search field. Then click on “CREATE SERVICE” to create a brand new Cloud Run service:

On the web page opened, since we need to arrange a steady deployment pipeline, click on the second choice to “Repeatedly deploy new revisions from a supply repository”:

Then click on “SET UP WITH CLOUD BUILD” to decide on a GitHub repository for Cloud Run. This repository will comprise the supply code and the configurations to construct and deploy your software.

If you wish to comply with, you possibly can fork this repository to your GitHub account and proceed to the next steps. Alternatively, you possibly can add the Dockerfile file as demonstrated above to your individual repository.

If it’s the primary time you deploy a Cloud Run service from a GitHub repository, you would wish to put in the “Google Cloud Construct” software in your GitHub repository:

Once you click on “INSTALL GOOGLE CLOUD BUILD”, a brand new window can be opened and you can be prompted to put in “Google Cloud Construct” in all of your GitHub repositories or a selected repository. Choose the one your need and click on “Set up” to put in it:

You’ll be requested to authenticate your GitHub account. After that, it is possible for you to to see your GitHub repository in Cloud Construct. Choose it and settle for the settlement for utilizing your GitHub repository in your GCP challenge:

Click on “Subsequent” to specify the “Construct Configuration”. You would wish to decide on the department towards which Cloud Construct will run. Apart from, that you must specify a Construct Sort. We are going to use a Dockerfile to construct our software. Each choices will be left as default most often.

Click on “SAVE” to save lots of the configurations for Cloud Construct.

Then that you must specify some primary configurations for Cloud Run. Once more, the default configurations could be sufficient most often:

The choices are fairly self-explanatory and have useful suggestions as properly. Because of this the Console is beneficial for deployment, particularly for newbies. You possibly can have extra understanding and extra management over what you might be doing, slightly than deal with it as a black field.

Particularly, The “CPU allocation and pricing” choice can improve the payments dramatically. In case you select the default non-obligatory “CPU is just allotted throughout request processing”, then usually you don’t need to pay for it if you happen to don’t have a whole lot of site visitors. Nevertheless, In case you select “CPU is at all times allotted”, you would wish to pay fairly some bucks each month. Please do verify Google Cloud Pricing Calculator for extra particulars.

As chances are you’ll bear in mind, we learn an setting variable APP_NAME in our Flask software. Let’s set a worth for it and see if the worth will be learn by Cloud Run. To do that, increase “Container, Variables & Secrets and techniques, Connections, Safety” and click on the “VARIABLES & SECRETS” tab. Add an setting APP_NAME with a worth you want, say “My First Cloud Run Service”.

Then click on “CREATE” to create your service. It’ll take lower than one minute for Cloud Construct to construct your Docker container earlier than it may be utilized in your Cloud Run service.

When the deployment is finished, you’ll land on a web page just like the one beneath. You possibly can verify the metrics, logs, revisions, and so on on this web page. If one thing is mistaken together with your service, the logs are at all times the primary place to verify.

Now if you happen to click on on the URL on this web page, you must be capable to open the easy web site constructed by Flask:

Congratulations! Your CI/CD pipeline in your Flask net software has been inbuilt Cloud Run. Now if you happen to make some adjustments on the primary department and push the code to GitHub, a brand new Docker picture can be mechanically constructed and a brand new revision of Cloud Run can be deployed mechanically for you.

More Posts