Continuous Deployment with GitLab CI/CD from scratch

What Is CI/CD?

CI/CD stands for Continuous Integration and Continuous Deployment (or Delivery).

  • Continuous Integration (CI): Automatically test and build your code whenever changes are made.
  • Continuous Deployment (CD): Automatically release those changes to staging or production once they pass all tests.

GitLab combines both into a single, built-in system that’s easy to use and powerful enough for large teams.

Step 1: Create a GitLab Repository

Start by creating a new project in GitLab.
You can push your local code using:

git remote add origin https://gitlab.com/username/project-name.git
git push -u origin main

Once your project is online, GitLab automatically enables CI/CD features.

Step 2: Add a .gitlab-ci.yml File

This file defines your pipeline stages. Create it in the root of your repository:

stages:
  - build
  - test
  - deploy

build_job:
  stage: build
  script:
    - echo "Building the application..."
    - npm install

test_job:
  stage: test
  script:
    - echo "Running tests..."
    - npm test

deploy_job:
  stage: deploy
  script:
    - echo "Deploying to production..."
    - bash deploy.sh
  only:
    - main

Each stage runs sequentially. If one fails, GitLab stops the pipeline automatically.

Step 3: Add Environment Variables

Go to your GitLab project → Settings > CI/CD > Variables.
Add credentials such as:

  • SSH_KEY – for connecting to your server
  • DEPLOY_HOST – deployment target IP
  • DEPLOY_PATH – where the app should live

These variables keep sensitive data secure and out of your repository.

Step 4: Configure Deployment Script

Your deploy.sh file might look like this:

#!/bin/bash
ssh user@$DEPLOY_HOST "cd $DEPLOY_PATH && git pull && npm install && pm2 restart all"

Make sure it’s executable:

chmod +x deploy.sh

Now, every successful push to the main branch automatically deploys the latest version.

Step 5: Monitor Pipelines

GitLab provides a Pipelines tab where you can see each job’s status in real time.
Failed steps show logs instantly, helping you debug quickly.

You can also view Environments to confirm which version is currently running.

Best Practices

  • Use branch-specific pipelines to separate staging and production.
  • Integrate unit and integration tests before deployment.
  • Set up pipeline caching to speed up builds.
  • Keep scripts modular and reusable.
  • Use GitLab Runners on self-hosted machines for faster performance.

These small steps make pipelines faster, safer, and easier to maintain.

Final Thoughts

GitLab CI/CD makes continuous deployment simple, powerful, and scalable.
With just a .gitlab-ci.yml file, you can automate everything — from testing to live deployment — in minutes.

If you’re exploring other CI/CD setups, check out CI/CD with GitHub, Firebase, and Docker.
To dive deeper into automation best practices, see the GitLab CI/CD documentation.

Leave a Comment

Scroll to Top