DEV Community

Cover image for Streamlining CI/CD Pipelines with GitLab CI for Node.js Applications
mark mwendia
mark mwendia

Posted on

Streamlining CI/CD Pipelines with GitLab CI for Node.js Applications

Introduction
In today's software development environment, Continuous Integration (CI) and Continuous Deployment (CD) have become indispensable practices. CI involves the automated testing and integration of code changes into a shared repository, while CD automates the release process to production. This comprehensive guide will walk you through the process of setting up a CI/CD pipeline specifically tailored for a Node.js application using GitLab CI/CD.

Key Components
GitLab CI/CD Overview: GitLab CI/CD is an integrated and robust tool within GitLab that empowers developers to automate the testing and deployment processes.
Pipeline Configuration: A pipeline comprises stages, jobs, and scripts, all meticulously defined in a .gitlab-ci.yml file.

Setting Up Your Project
Create a New Node.js Project:
Begin by creating a new Node.js project by executing the following commands in your terminal:

mkdir my-node-app
cd my-node-app
npm init -y
npm install express jest
Enter fullscreen mode Exit fullscreen mode

Create a Simple Express App:
Develop a basic Express app by creating a server.js file with the following content:

// server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello, CI/CD!');
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

.gitlab-ci.yml Configuration:
Define your CI/CD pipeline in a .gitlab-ci.yml file at the root of your project:

stages:
  - build
  - test
  - deploy

build:
  stage: build
  image: node:14
  script:
    - npm install

test:
  stage: test
  image: node:14
  script:
    - npm test

deploy:
  stage: deploy
  environment: production
  script:
    - echo "Deploying to production server"
    - ssh user@server "cd /path/to/app && git pull && npm install && npm start"
  only:
    - master
Enter fullscreen mode Exit fullscreen mode

Running Your Pipeline:
Once you push your changes to GitLab, the pipeline will be automatically triggered, seamlessly executing each stage as defined in your .gitlab-ci.yml file.

Conclusion:
By implementing CI/CD pipelines with GitLab CI, you can effectively automate testing and deployment, enabling your team to deliver code swiftly and with high efficiency. This not only enhances code quality but also fosters seamless collaboration among team members.

Top comments (0)