Deploying Create-React-App to Google Cloud Run using Nginx

Google’s Cloud Run is a great way to get sites up and running quickly. It can take a git repo, build, and deploy within minutes. Later, deploying updates is seamless and automatic.

If using create-react-app, to get this up and running, you simply need to get a Dockerfile set up to help build a containerized version of your site.

Here is an example Dockerfile that will create a live build of your React project. This will run use a node environment to runnpm build and copy the built version of the app into the proper location, and then serve the app using nginx.

One piece of this that is important is that you need an nginx config file to serve the site. In this example, there is a file in the repo located in buildconfig/nginx.conf that is used.

Below are the contents of that file.

Google Cloud Run allows you to set a port when deploying an instance, however, that port value isn’t guaranteed, and I’ve noticed it often isn’t followed. There will be a PORTenvironment variable passed into the build, and Google recommends always using this.

In the past, it wasn’t easy to use environment variables in nginx, but this Dockerfile is deploying nginx version 1.19. This allows you to easily create templates that can utilize environment variables. The Docker Hub docs for nginx give some details on this.

In the Dockerfile, the config is copied to /etc/nginx/templates/default/conf.template and this will output the actual config to/etc/nginx/conf.d/default.confwith the port replaced with the value provided by Cloud Run

That should be all there is to it. These steps should work for any Docker deployment given that a PORT is passed in.