Google Cloud Run allows you to easily deploy a docker container to the cloud. I currently use it to host all my side projects that require a server.

Requirements

You’ll need a Dockerfile

For a Next.js application using yarn, you can use something like the following (you can replace yarn with npm or pnpm or whatever package manager you’re using)

FROM node:18-slim
WORKDIR /usr/src/app
COPY package*.json ./
RUN yarn install

COPY . .
COPY .env.production .

RUN yarn build

ENV NODE_ENV production

EXPOSE 3000

CMD ["yarn", "start"]

Make sure to add .gcloudignore and .dockerignore files

Without these, Google Cloud Run will automatically ignore .env files (I wasted hours on this trying to figure out why my Next.js environment variables weren’t defined on Google Cloud Run)

gcloud CLI

Install gcloud for your terminal if you haven’t already: https://cloud.google.com/sdk/docs/install

You can set the default region to say “us-east4” by running the following command: gcloud config set run/region us-east4

Manual Deployment

Note: I do not recommend manually deploying unless you never plan to update your code. CI/CD is far superior since code updates will then automatically trigger deploys.

That being said if you did want to manually deploy, you could run the following command. Replace “<service-name>” with the name of your service.

gcloud run deploy <service-name> --source .

We won’t be manually deploying in this tutorial because we’ll set up Continuous Deployment with GitHub Actions to do that automatically upon code changes pushed up to GitHub.

Deploying with CI/CD and GitHub Actions

Follow this tutorial in Google Cloud’s documentation: Creating a CI/CD environment for serverless containers on Cloud Run with GitHub Actions

I am not a Google Cloud representative, so Google’s documentation should be your source of truth. I’m just writing this to try to be helpful :)