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.
|
|
- The
buildstage is assigned thebuild-runnertag to ensure it runs on the designated build server. It installs the project dependencies usingnpm installand builds the React application usingnpm run build. The resulting build artifacts are saved in thebuild/directory. - The
deploystage is assigned theproduction-runnertag to ensure it runs on the designated production server. It uses thecpcommand to copy the build artifacts from thebuild/directory to the Nginx HTML folder (/usr/share/nginx/html/). The deployment only triggers when changes are pushed to themasterbranch.
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.