How to deploy a NodeJs application to GCP cloud run service
In todays guide we will show how to deploy your NodeJs application to a Cloud Run service, and as a bonus, we will show how to set up a trigger to your Github repository as well, so a new deploy will be triggered when a push to the selected branch is made.
In this guide we showed how to deploy a React application, have a look if you are interested.
Dockerfile
Let's create our Dockerfile. In the root of the project, create a file called Dockerfile.
# ==== CONFIGURE ===== # Use a Node 16 base image FROM node:16-alpine # Set the working directory to /app inside the container WORKDIR /app # Copy app files COPY . . # ==== BUILD ===== # Install dependencies (npm ci makes sure the exact versions in the lockfile gets installed) RUN npm ci # ==== RUN ======= # Set the env to "production" ENV NODE_ENV production # Expose the port on which the app will be running EXPOSE 8080 # Start the app CMD [ "node", "index.js" ]
NOTE: that the port we expose should be the same as the one you specify in your Cloud Run service and in your project. For example in your index.js:
const port = parseInt(process.env.PORT) || 8080; app.listen(port, () => { console.log(`Service is listening on port ${port}`); });
Package.json
In our package.json, we will add our start script and main file as well. It is not really a necessity in this particular case, but more of a good practice.
{ "main": "index.js", "scripts": { "start": "node index.js" }, }
Cool, now let's set up our Cloud Run!
Set up Cloud Run service
In Google Cloud Console, create a new Cloud Run service and add a trigger like image below.
And when you click next, specify Dockerfile as build type and the location should be /Dockerfile. Image below will show an example:
And that's it. Now when you push the code to your branch, it will automatically build and deploy to the cloud run service, and you should be able to access the service via the provided url.
Outro
In todays guide, we showed how to deploy our NodeJs application to a Cloud Run service with automatically triggers when we push to Github. I hope you found this guide helpful, and if you have any feedback our questions - just send me an email and I will reply as soon as I can!
Thanks for reading!