Deploying a Container to GCP Cloud Run

Cloud Run can deploy a container from GCR build using Cloud Build, or directly from Docker Hub.

Building the Container using Cloud Build

To build with gcloud, first create a Dockerfile. Here’s a basic one for a Python Flask app:

FROM python:3.10-slim-bullseye
RUN pip3 install --upgrade pip
RUN pip3 install flask gunicorn
ENV PORT=8000
ENV FLASK_DIR=/opt
ENV FLASK_APP=wsgi:app
ENV NUM_WORKERS=1
ENV NUM_THREADS=8
COPY wsgi.py $FLASK_DIR
ENTRYPOINT gunicorn -b 0.0.0.0:$PORT -w $NUM_WORKERS --threads=$NUM_THREADS --chdir=$FLASK_DIR $FLASK_APP
EXPOSE $PORT

Note that although Cloud Run has a generous free tier, the images will cost some money to store. So it’s in one’s best interest to keep the image sizes as small as possible.

Verify logged in to gcloud and set to correct project:

gcloud projects list
gcloud config set project <PROJECT_ID>

Where <PROJECT_ID> is the Project ID

Then build the container and upload the image to Google Container Registry. Note this step is missing from the quickstart guide

gcloud builds submit --tag gcr.io/<PROJECT_ID>/<IMAGE_NAME>

Deploying the Cloud Run Service from GCR

Now pick a region and deploy the container. In this example ‘python-flask’ is the Cloud Run service name:

gcloud config set run/region us-central1
gcloud run deploy python-flask --image gcr.io/<PROJECT_ID>/<IMAGE_NAME> --allow-unauthenticated --port=8000

Note the default Container port is 8081, even if set to something else in the Dockerfile.

Deploying a Cloud Run Service from Docker Hub

Alternately, you can skip the cloud build steps and simply deploy an image from Docker Hub. For example, the public nginx image:

gcloud config set project <PROJECT_ID>
gcloud config set run/region us-central1
gcloud run deploy nginx --image docker.io/library/nginx --allow-unauthenticated --port=80
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s