CI Setup for application
Let’s say we have a Node.js API that retrieves a list of books in a database. We can create a pipeline that pushes our code through three phases: build, test and deploy. A pipeline is a group of steps that are grouped by similar characteristics. With those phases our pipeline is defined by three types:
Project Pipeline
Continuous Integration Pipeline
Deploy Pipeline
The Project Pipeline installs dependencies, runs linters and any scripts that deal with the code. The Continuous Integration Pipeline runs automated tests and builds a distributed version of the code. Finally, the Deploy Pipeline deploys code to a designated cloud provider and environment.
The steps that the three pipelines execute are called jobs. When you group a series of jobs by those characteristics it is called stages. Jobs are the basic building block for pipelines. They can be grouped together in stages and stages can be grouped together into pipelines. Here’s an example hierarchy of jobs, stages, and pipelines:
In this hierarchy, all three components are considered three different pipelines. The main bullets — build, test, and deploy are stages and each bullet under those sections are jobs. Let’s break this out into a GitLab CI/CD yaml
file.
Using GitLab CI/CD
To use GitLab CI/CD, create a file called .gitlab-ci.yml
at the root of the project in your GitLab repository and add the following yaml
:
Now let’s start with our job dedicated to the Build stage. We are going to call this job build-min-code
. In this job we want it to install dependencies and minify the code. We can start this off with using the script
directive. The script
directive is a shell script that gets executed within the Runner. Then we are going to assign this job to the “build” stage. To assign a job to a stage, use the stage
directive.
Now we have a job associated with our Build stage and we are going to do that for our Test stage. Our test job is going to be called run-unit-test
and we are going to use the npm script in our API to run a test npm test
.
Finally, we are going to add a job to handle our Deploy stage: deploy-production
, deploy-staging
. In this instance, we are going to have two different jobs for deployment (staging and production). These jobs will reflect the same layout as our previous jobs but with a small change. Currently, all of our jobs are automatically set to be triggered on any code push or branch. We do not want to have that for when we deploy our code to staging and production. To prevent that from happening we use the only
directive. The only
directive defines the names of branches and tags for which the job will run. The job will look like the following:
In our deploy-staging
job, the Runner will only execute it if there was a change to the develop
branch and for deploy-production
the master
branch. Here is a screenshot below that shows a code push made to the master
branch.
Last updated
Was this helpful?