Deploy Node JS Project to Google App Engine with Github Actions CI/CD - A Complete Guide
Tags: node, googlecloud, cicd, githubactions
Published: 2024-01-16 18:10:03



This guide provides you a step-by-step process to **deploy your Node JS Project efficiently to Google App Engine**. Each section offers actionable steps, ensuring a smooth deployment journey.
<br />

### In this guide, we'll cover the following sections:

1. [**Pre-requisite**](#pre-requisite) 
2. [**Node Project Config**](#node-project-config) 
3. [**GCP Account & GCP Project Setup**](#gcp-account-and-project-setup) 
4. [**App.yaml & Explanation**](#appyaml-and-explanation) 
5. [**Github Actions CI/CD**](#github-actions-cicd) 
6. [**Testing**](#testing)

Whether you're a seasoned developer seeking a detailed deployment workflow or an enthusiast eager to take your Node project live, this guide will equip you with the necessary knowledge and steps for a successful deployment journey. Let's start with pre-requisites.

<br />

<a name="pre-requisite"></a>

# Section 1: Pre-requisites



Before diving into deploying a Node JS Project to Google App Engine (GAE), it's essential to ensure that you have the necessary tools and knowledge in place. Mininum requirements are

- **Node, YARN & npm Installed:** Make sure Node.js, YARN and npm are installed on your machine. Node 18 is used throughout this guide.
- **Simple Node JS Project:** Familiarize yourself with creating a Node Project project and running it locally.
- **Google Cloud Account:** If you don't have one yet, don't worry; we'll create it in a later step.

<br />
<hr>

<a name="node-project-config"></a>

# Section 2: Node JS Project Config



### Prepare and Run Node JS Project

If you haven't already set up a Node JS project, create your own project or clone the demo project from [Github here](https://github.com/rushi-2001/node-express-app-engine-setup).

- Open your terminal.

- Run the following command to clone Node JS project:

   ```bash
   git clone https://github.com/rushi-2001/node-express-app-engine-setup
   ```
- Install the dependencies:

   ```bash
   yarn
   ```

- Run the app:

   ```bash
   yarn start-dev
   ```
   This will start a development server, allowing you to view your Node server in a browser at http://localhost:8080.


- Prepare a build of your Node app:
   ```bash
   yarn build
   ```
   This command creates a build folder at the root of your project, containing the compiled version of your Node app.
- Exclude build folder from Git: <br>
   Add `build/` to your `.gitignore` file to prevent it from being tracked and pushed to your Git repository.
- Node Scripts Configuration:
   Ensure your `package.json` includes the following scripts:
   ```json
   "scripts": {
    "start": "node build/index.js",
    "start-dev": "nodemon src/index.ts",
    "build": "tsc"
  },
   ```
   Make sure your scripts align with the provided commands for starting & building app.

   > **Important:** When deploying your application to Google App Engine, ensure that the `start` command in your `package.json` points to the correct file for launching your application. <br /> For **JavaScript** project you can use `"start": "node index.js"` and for **TypeScript** project it must be pointing the JS file inside build folder. `"start": "node build/index.js"`


<br/>
<hr>

<a name="gcp-account-and-project-setup"></a>

# Section 3: GCP Account & GCP Project Setup



### Step 1: Create a New Project

1. Go to the [Google Cloud Console](https://console.cloud.google.com/) and sign in.
2. Click on "Select a project" at the top and then click on "New Project."
3. Choose a unique project name and select the desired organization if applicable.
4. Once the project is created, note down the Project ID for future reference.
5. Link this project to appropriate Billing Account.

### Step 2: Enable Required APIs

1. Navigate to the **APIs & Services** section in the Google Cloud Console.
2. Click on **Library** in the left sidebar.
3. Search for **Cloud Storage** and enable the **Cloud Storage API.**
4. Search for **App Engine Admin** and enable the **App Engine Admin API.**

### Step 3: Set Up Cloud Storage

1. Go to the **Cloud Storage** section in the Google Cloud Console.
2. Click on **Create Bucket** to make a new bucket.
3. Choose a unique name and select the desired region.
4. Leave other settings as default and create the bucket.

### Step 4: Install GCP CLI

1. Navigate to the root directory of your Node app in the terminal.
2. Install the Google Cloud SDK following the instructions at [Google Cloud SDK Installation Guide](https://cloud.google.com/sdk/docs/install).
3. Authenticate the Google Cloud SDK by running `gcloud auth login` and following the on-screen instructions.
4. Set the project ID by running `gcloud config set project PROJECT_ID`, replacing PROJECT_ID with your actual Project ID.


<br />

<hr>

<a name="service-account-setup"></a>

# Section 4: Service Account Setup

#### Generate & Download a Service Account

To set up a Service Account for Google App Engine deployment, follow these steps:

1. Go to the [Google Cloud Console](https://console.cloud.google.com/).
2. Navigate to **IAM & Admin** → **Service Accounts**.
3. Click on **Create Service Account**.
4. Provide an appropriate name and description for the service account. For instance, use `github-ci-cd` as it will be utilized for Github CI/CD.
5. Assign the following roles:

     1. App Engine Admin
     2. Cloud Build Service Account
     3. Service Account User
     4. Storage Object Admin

6. Click the three dots and select **Manage keys**.
7. Click on **Add Key → Create New Key**.
7. Choose the **JSON key** type and securely download it. Remember, this key grants access to Google Cloud resources, so keep it safe.

<br />
<hr >

<a name="appyaml-and-explanation"></a>

# Step 5: Create app.yaml and Explanation



#### What is app.yaml?

- The `app.yaml` file configures settings and routing for Google App Engine applications.

#### Placement:

- Keep the `app.yaml` in your project's root directory alongside your source code.

#### Example Configuration:

```yaml
# [START app_yaml]

runtime: nodejs18

service: node-express-api

# [END app_yaml]
```

#### Explanation of Configuration:

- **runtime:** Specifies the runtime environment (e.g., `nodejs18`).
- **service:** Defines the service name, typically a project-specific prefix or subdomain.

This configuration example directs incoming requests to the appropriate static files within the `build` directory, which further handles the different API routing.

#### Deploy your App Locally:

Deploy your Node app by executing the command in root directory of your project:
   ```bash
   gcloud app deploy
   ```
   This command will package and upload your compiled build to Google Cloud. The deployment process may take a few minutes.

   > **Note:** When you are deploying for **first time** of the bucket, comment out line 4, where you specify service name. As first deployment must be of default service. 

After deployment completion, you'll receive a URL where your Node app is hosted. Open the URL to check the deployed Node App.

<br />
<hr >

<a name="github-actions-cicd"></a>

# Step 6: CI/CD using GitHub Actions


### CI/CD and GitHub Actions:

- **CI/CD:** CI (Continuous Integration) and CD (Continuous Deployment) automate the software delivery process. CI involves merging code changes into a shared repository frequently, automatically running tests, and validating changes. CD automates the deployment of validated code changes to production or staging environments.

- **CI/CD in GitHub Actions:** GitHub Actions provide workflows to automate tasks in your repository, including CI/CD processes. These workflows are defined in YAML files and can be triggered by various events like code pushes, pull requests, etc.

### Storing Service Account Key and Project ID in GitHub Secrets:

- Store your Service Account Key and Project ID as secrets in your GitHub repository to securely access them during the CI/CD process.
- You can create Github secrets by **Github Repository → Settings → Secrets & Variables → Actions → Secrets tab → New Repository Secret**
- Secrets:
  1. `GCP_SA_KEY`: Your entire JSON of Service Account Key generated in previous step.
  2. `GCP_PROJECT_ID` Your GCP Project ID.

### Workflow File Name & Placement:

- The workflow file should be named `gcp-deploy.yml`.
- Place this file in the `.github/workflows` directory in your project. Refer the below given repository incase of any confusion.
- Paste the below configuration in recently created yml file.

### Configuration

```yaml
name: Deploy to Goggle App Engine (GAE)

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Setup Node.js and yarn
        uses: actions/setup-node@v2
        with:
          node-version: '18'

      - name: Install dependencies
        run: yarn install --frozen-lockfile

      - name: Build Node Project
        run: yarn build

      - name: Google Cloud Auth
        uses: 'google-github-actions/auth@v2'
        with:
          credentials_json: '${{ secrets.GCP_SA_KEY }}'
          project_id: ${{ secrets.GCP_PROJECT_ID }}

      - name: Set up Cloud SDK
        uses: 'google-github-actions/setup-gcloud@v2'

      - name: Deploy to Google App Engine
        run: |
          gcloud app deploy app.yaml --quiet

```

<br >

This workflow triggers on pushes or pull requests to the `main` branch. It uses **GitHub Actions** to perform various steps such as building the Node app, authenticating with Google Cloud, setting up the Cloud SDK, and deploying the app to Google Cloud Platform.

<br />
<hr >

<a name="testing"></a>
# Step 7: Testing the CI/CD



**Push Your Changes to GitHub (on Main Branch):**

Ensure your latest changes are pushed to the main branch of your GitHub repository.

**Navigate to the 'Actions' Tab in GitHub Repository:**

Visit your GitHub repository and go to the 'Actions' tab.

**Check Workflow Status:**

Verify the status of your Node app deployment workflow using GitHub Actions.

**Open the Deployed App URL:**

Access the provided URL after a successful deployment in your browser to confirm your Node application runs smoothly.

   > **Note:** In GitHub Actions logs, the URL might contain masked text (**** text) representing your GCP project ID. Replace **** with your project ID and open the URL in your browser.

**Access Google Cloud Engine Services:**
Go to Google Cloud, locate and click on App Engine, then navigate to **Services** in the sidebar. Find your recent deployments and click on the service to open your Node App in a new tab.

<br />
<hr >

# GitHub Repository Link

Access the complete code reference for this guide by visiting the [GitHub Repository](https://github.com/rushi-2001/node-express-app-engine-setup).
Feel free to clone the repository and experiment with it on your own!


<br />
<hr >

# Conclusion

🚀 Congratulations on mastering the deployment of your Node JS Project to Google App Engine and GitHub Actions! 🎉

Embrace this automated workflow to streamline your development journey and propel your projects to new heights. You can refer the above given **repository** link as and when required. If you have any queries or need guidance, feel free to chat or **drop a comment.**

Keep coding, exploring, and sharing the joy of efficient deployments! Don't forget to **like and share this guide** to inspire others on their deployment adventures! 👍

**Happy coding! 💻✨**