Try Python Project with Cloud Run

2019-10-12

Cloud Run is the GCP service that can operate with Container and Serverless. You can deploy Docker Image to a fully managed environment of GCP like Fargate in AWS.


Although Cloud Run is still a beta release at the time of writing this article, it seems that it’s enough to operate this service as Production. Cloud Run, compare still poorly with AWS Fargate, is a great useful container service.

Create a sample project with Flask

The following is a sample Rest API project structure with Python Flask.

  -Dockerfile
  -docker-compose.yml
  -src
    -requirements.txt
    -run.py

Dockerfile as the following.

FROM python:3.7

RUN apt-get update && 
    apt-get -y install python-dev

RUN mkdir /app
WORKDIR /app
ADD src /app/

# pip install
ADD src/requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt

ENV PORT 8080
EXPOSE 8080
CMD ["python", "run.py"]

requirements.txt as the following.

flask

docker-compose.yml as the following.

version: '3'
services:
  web:
    build: .
    working_dir: /app
    volumes:
      - ./src:/app
    ports:
      - 8080:8080
    stdin_open: true
    tty: true

Create run.py as the following.

from flask import Flask, jsonify, request
import json
import os
app = Flask(__name__)

@app.route("/", methods=['GET'])
def hello():
    result = {
        "title": "test"
    }
    return jsonify(result)

if __name__ == "__main__":
    app.run(host='0.0.0.0',port=8080,debug=True)

Setting 8080 port for listen is the important point. Default listen port in Cloud Run is 8080, so it should set 8080 unless there are some particular reason.

Try to run on the localhost.

docker-compose build
docker-compose up -d

It responses a json with accessing to “http://localhost:8080".

Deploy to Cloud Run

It should Enable Cloud Run API and Container Repository on GCP console. And it must install cloud SDK on the host machine for using “gcloud command".

Push to Container Repository

Execute the following command in a directory that exist the Dockerfile to build a docker image and push to Container Repository.

gcloud builds submit --tag gcr.io/[project-ID]/[repository-name]

Publish or Update Cloud Run

It deploy the project to Cloud Run with the following.

gcloud beta run deploy [Run service name] --image gcr.io/[project-ID]/[repository-name] --region asia-northeast1 --platform managed --allow-unauthenticated

The option is the following. you can interactive mode without the option.

–region asia-northeast1 Tokyo Region
–platform managed fully managed
–allow-unauthenticated Without Authentication

It can publish to fully managed environment with only this. The case of updating the project is same.