1
GitLab CI/CD Pipeline
GitLab CI/CD Pipeline
GitLab CI/CD is a built-in continuous integration and continuous deployment platform that automates the build, test, and deployment of your code.
What is GitLab CI/CD?
GitLab CI/CD uses a YAML file called .gitlab-ci.yml to define pipeline configurations. Every commit triggers a pipeline that can build, test, and deploy your code.
Basic Pipeline Structure
yaml
# .gitlab-ci.yml
stages:
- build
- test
- deploy
build-job:
stage: build
script:
- echo "Building the application..."
- npm install
- npm run build
test-job:
stage: test
script:
- echo "Running tests..."
- npm test
deploy-job:
stage: deploy
script:
- echo "Deploying to production..."
only:
- main
Pipeline Stages
Stages define the order of execution:
yaml
stages:
- lint
- build
- test
- security
- deploy
Jobs and Scripts
Each job runs specific commands:
yaml
lint-job:
stage: lint
script:
- npm run lint
- npm run format:check
build-job:
stage: build
script:
- docker build -t myapp:$CI_COMMIT_SHA .
- docker push myapp:$CI_COMMIT_SHA
Using Variables
yaml
variables:
DOCKER_IMAGE: "myapp:latest"
DEPLOY_ENV: "production"
deploy-job:
stage: deploy
script:
- echo "Deploying $DOCKER_IMAGE to $DEPLOY_ENV"
environment:
name: production
url: https://myapp.example.com
Caching Dependencies
yaml
build-job:
stage: build
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
- .cache/
script:
- npm install
- npm run build
Artifacts
yaml
build-job:
stage: build
script:
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 week
Manual Deployments
yaml
deploy-production:
stage: deploy
script:
- ./deploy.sh production
when: manual
only:
- main
Best Practices
- Keep pipelines fast with caching
- Use merge request pipelines
- Protect sensitive data with CI/CD variables
- Use tags for runner selection
- Implement rollback strategies
- Monitor pipeline performance