Building and Deploying a React Application to Nginx HTML Folder Using GitLab CI With Separate Runners

Deploying a React application involves building it on one server and deploying it to another. GitLab CI provides a robust solution for automating this process, allowing you to leverage different runners for the build and deployment stages. In this article, we will explore how to utilize GitLab CI to build a React application on a build server and deploy the built source to the Nginx HTML folder on a production server using separate runners.

Prerequisites

  • A GitLab repository containing the React application code.
  • A build server with a GitLab CI runner configured.
  • A production server with an Nginx server configured.

Step 1: Configuring the Build Server

Set up a build server with Node.js and the GitLab CI runner installed. Ensure the runner is properly registered with GitLab.

Step 2: Creating the .gitlab-ci.yml File

In the root directory of your GitLab repository, create a file named .gitlab-ci.yml to define the CI/CD pipeline.

Step 3: Defining the Stages and Build Job

Inside .gitlab-ci.yml, define two stages: build and deploy. The build stage will execute on the build runner and handle the React application build process.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
stages:
  - build
  - deploy

build:
  stage: build
  tags:
    - build-runner
  script:
    - npm install
    - npm run build
  artifacts:
    paths:
      - build/

deploy:
  stage: deploy
  tags:
    - production-runner
  script:
    - cp -R build/* /usr/share/nginx/html/
  only:
    - master
  • The build stage is assigned the build-runner tag to ensure it runs on the designated build server. It installs the project dependencies using npm install and builds the React application using npm run build. The resulting build artifacts are saved in the build/ directory.
  • The deploy stage is assigned the production-runner tag to ensure it runs on the designated production server. It uses the cp command to copy the build artifacts from the build/ directory to the Nginx HTML folder (/usr/share/nginx/html/). The deployment only triggers when changes are pushed to the master branch.

Step 4: Registering and Configuring Runners

Ensure that you have registered and configured the build runner on the build server with the build-runner tag, and the production runner on the production server with the production-runner tag.

0%