🚀 Complete CI/CD Pipeline Setup in GitLab (Step-by-Step Guide)
In modern software development, Continuous Integration and Continuous Deployment (CI/CD) are essential for faster and reliable releases. GitLab provides a powerful built-in CI/CD system that enables automated build, test, and deployment workflows.
In this guide, we’ll walk through setting up a complete CI/CD pipeline in GitLab.
📌 What is GitLab CI/CD?
GitLab CI/CD is a built-in DevOps tool that automates:
- Code building
- Testing
- Security scanning
- Deployment
It uses a configuration file called:
.gitlab-ci.yml
This file defines stages, jobs, and scripts.
🏗 Step 1: Create a GitLab Repository
- Login to GitLab
- Create a new project
- Push your code to the repository
⚙ Step 2: Create .gitlab-ci.yml File
Add this file to the root of your project:
stages: - build - test - deploy variables: IMAGE_NAME: my-app build_job: stage: build script: - echo "Building the application" - docker build -t $IMAGE_NAME . test_job: stage: test script: - echo "Running tests" - npm install - npm test deploy_job: stage: deploy script: - echo "Deploying application" only: - main
🏃 Step 3: Setup GitLab Runner
GitLab Runner executes pipeline jobs.
Install Runner:
sudo apt install gitlab-runner
Register Runner:
sudo gitlab-runner register
Provide:
- GitLab URL
- Registration token
- Executor type (docker/shell)
🐳 Step 4: Using Docker in Pipeline
To enable Docker builds:
image: docker:latest services: - docker:dind
This allows containerized builds.
🔐 Step 5: Add CI/CD Variables
Go to:
Settings → CI/CD → Variables
Add:
- DOCKER_USERNAME
- DOCKER_PASSWORD
- API_KEYS
- SERVER_IP
Never hardcode secrets in YAML.
🚀 Step 6: Deployment Strategy
You can deploy to:
- VPS server (via SSH)
- Kubernetes cluster
- AWS EC2
- Azure VM
- DigitalOcean
Example SSH Deployment:
deploy_job: stage: deploy script: - ssh user@server "docker pull $IMAGE_NAME && docker restart app"
📊 Pipeline Flow
- Developer pushes code
- GitLab triggers pipeline
- Build stage runs
- Test stage validates
- Deploy stage releases to production
🎯 Best Practices
- Use separate environments (dev, staging, prod)
- Enable branch protection
- Use merge request pipelines
- Enable security scanning
- Cache dependencies for faster builds
- Use Docker for consistency


Comments
No comments yet. Be the first to share your thoughts.
Leave a comment
Comments are moderated before they appear on this post.