Deploying a Next.js 14 app to Google Cloud Run
Full steps on how to simply deploy a Next.js application on GCR
Are you feeling overwhelmed by the multitude of hosting options while trying to launch your website? Look no further — this guide is here to simplify the process and introduce you to one of the easiest and quickest solutions for getting your website online. Let’s get started!
Table of Contents
— Why Google Cloud Run?
— Why Next.js?
— Creating a new Next.js app
— The Dockerfile
— Saving your code to GitHub
— Setting up your Cloud Run service
— Using a custom domain name
Why Google Cloud Run?
Google Cloud Run is a great solution for rapidly deploying new websites and it comes with many benefits over traditional server based hosting. Some of these benefits are;
- You get two million free requests every month. Yes you read that correctly, I personally have several websites hosted using this solution and have yet to pay a single cent on them.
- Out-of-the-box autoscaling — if you are familiar with Kubernetes, its a similar idea, where the more hits to your site, the more pods get started up so your users will never get a degraded service and your sites will always remain fast!
- Free, preconfigured SSL — Gone are the days of manually having to SSH into a server and configure your SSL certificates. Maybe you used to use tools such as Let’s Encrypt to do this and had to manually configure it to work on your NGINX servers for instance — Well look no further, now you have to do zero configuration and it just works!
- Automated deployments — Simply merging you code into the main branch on git will automatically trigger new builds and your application will be deployed in a matter of minutes! Under the hood, Google Cloud run will use another service called Cloud Build which is a fully managed CI/CD platform which builds and deploys your application!
There are plenty of other great benefits but these are just a few to shout out about! Please check out all of the available features here: https://cloud.google.com/run
Why Next.js?
Next.js is a React Framework with some especially spicy features which are making it one of the fastest growing frameworks for the web to date! Here are some of the things that make it great;
- Server Side Rendering — This is a big one, especially if you want to get your sites listed in search engines or have your links shareable in social media platforms. Due to your pages being rendered on the server side, things like search engines will be able to crawl and index the content of your pages which is very beneficial for SEO purposes.
- File based routing — Typically in React you would have a single file which would contain all of your routing logic and it was always a bit of a nightmare navigating these files. With Next.js, this is done with folders, where the name of the folder is your route — This keeps things really neat and easy to navigate as well as providing some very powerful tools.
- CSS Modules — Locally scopes styles and creates unique classnames for each rule. This honestly keeps your codebase so clean and makes finding things so incredibly easy, its a joke! You can also package this up with tools such as Tailwind CSS to make it even more powerful!
There are plenty of other reasons why you should choose Next.js as your frontend framework and I suggest you give their documentation a good read through so you can get an idea of the things to expect. Whilst this article is specific to Next.JS and Google Cloud Run, the underlying idea can be used with pretty much any framework you like!
Creating a new Next.js app
Lets get started by creating a new Next.js application. This guide will assume you already have a working developer environment set up with Node.js, Git, and a code editor such as VSCode.
Firstly open your editor and its terminal, then CD to a directory you would like to work from, for me I will be working out of my Sites directory on Mac cd ~/Sites
— Once here run the following command which can be found on the Next.js homepage to open up the Next.js installer:
npx create-next-app@latest
This will open a step-by-step configurator for the new application. Simply follow the options and the app will be created, for this demo I called my application “cloud-run-nextjs”
Once the application is created, open the newly created directory in your code editor and your directory structure should look like so:
In terms of setting up the application that should be all! To start your application locally, simply run the following command:
npm run dev
Your application should now be started on port 3000, visiting http://localhost:3000 in your browser should present you with the Next.js landing page
That should be everything to get started with Next.js! You can now start building your site!
The Dockerfile
The Dockerfile is a text document that contains all the commands to assemble an image which will be used to run your site in Cloud Run.
Start off by creating a new file in the root of your project directory called “Dockerfile”. Here is an example Dockerfile which you can use as a great starting point:
FROM node:18-alpine AS base
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package*.json ./
RUN npm ci
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
FROM base AS runner
WORKDIR /app
ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
USER nextjs
EXPOSE 3000
ENV PORT 3000
CMD ["npm", "start"]
That should be everything you need to get started!
Saving your code to GitHub
Head over to GitHub and then create a new repository:
Once you have filled in the form, hit “Create repository” which will then provide you with the commands to push up the code on the next page:
From this page you will want to copy the commands from the “…or push an existing repository from the command line” block. Simply copy the commands and paste them in to your terminal which is open inside your project then hit enter, follow any prompts that may occur, for instance I had to add the GitHub fingerprint to my known hosts by typing “yes”.
Once done, your code should be pushed to GitHub:
Thats everything we need and we can now get started with deploying the application to Cloud Run!
Setting up your Cloud Run service
Head over to your Google Cloud Console (Create a new account if you don’t have one yet). Once you are at your dashboard, head over to Cloud Run by finding it the main navigation menu or searching for it in the search box at the top of the page.
Once there, press the “Create Service” button at the top of the page:
Once you are at the form page for creating a new service, select the radio button entitled “Continuously deploy new revisions from a source repository” then press the “Set up with Cloud Build” button
This will open a new pane where we can connect our GitHub accounts with Google Cloud, follow the steps to do so then select your new repository from the list
Press next to proceed to the Build Configuration settings. Set the branch field to match the name of your main branch on GitHub (if you followed this guide, everything should be set to “main” by default). Then under the “Build Type” options, select “Dockerfile” and set the “Source location” to match the name of your Dockerfile (again, if you followed this guide this should automatically be set to “/Dockerfile” by default)
Press save, then we can get started with the remaining options for our new Cloud Run service. Once back to the main service creation form, the service name should now be filled in with the name of our repo, you can also rename this to anything you like!
Set the region to whatever you like, I suggest choosing a region which is closest to you or your audience. The rest of the options can be left at their defaults except under the “Authentication” settings choose “Allow unauthenticated invocations” to allow the service to be accessed over the open internet.
Once done, open the “Container(s), Volumes, Networking, Security” drawer. The only thing we need to change here for now is the “Container port” option which will be set to “8080” by default so you will need to change this to 3000 — If you remember from setting up the project, this was 3000 when starting the dev environment, as well as at the bottom of the Dockerfile where we expose port 3000 from the container.
After that you press the “Create” button and we’re ready to go! 🚀 🌕
Once the service is created, you should be automatically taken to the revisions tab of your new service, each time you commit to the main branch, you will see a new revision in this list and you can quickly divert traffic to previous revisions if you need to.
Initially, you will see that the “Building and deploying from repository” step is set to “Pending” this is because Cloud Build is building your image and once done your website will be live on the URL provided on this screen. To check the progress on the build, head over to the Cloud Build by finding it in the navigation bar, or search for it in the top menu in Google Cloud.
Once the revision has been built and deployed, you will see a new revision under the revisions tab in your Cloud Run Services and you should be able to access the Next.js application in the URL provided on your Cloud Run service
Using a custom domain name
If you made it this far, the last thing you will probably want to do is hook up your own custom domain name. To do this navigate to the Cloud Run home page in Google Cloud then press “Manage Custom Domains” from the top navigation bar then on the next page press “Add Mapping”.
When the “Add custom domain” pane appears, select your new service to map to, then press select the option “Cloud Run Domain Mappings”
This will open a new modal, select the domain from the list (note: you will need to add a verified domain to your Google account which can be done by selecting “Verify a new domain…” in the dropdown).
For this example I will be setting up the site on a subdomain but you can do this to just the base domain if you choose to:
Press continue and you will be presented with the DNS record which you will need to update on your domain registrars website.
Adding this DNS record will vary between registrars but the process is ultimately the same, this is what mine looks like:
As you can see it matches up with the values supplied from Google Cloud. It can sometimes take a little while for DNS records to take effect, so check back on your site after some time and your site should be live!
Heres the link to this demo in action https://cloud-run-nextjs.callumeddisford.co.uk
Heres the link to the repository used for this demo https://github.com/CallumEddisford/cloud-run-nextjs
I hope you enjoyed this guide and everything went smoothly for you!
Have fun building! 🎉