Table of Contents
Manual builds, inconsistent testing, and risky release nights slow engineering teams down. GitLab CI/CD removes that friction by running your build, test, and deployment steps automatically every time code changes.
This guide walks you through setting up GitLab CI/CD in seven steps, then goes further: a complete working pipeline, performance tuning, security practices, troubleshooting, and the governance decisions engineering managers and CTOs face as pipelines scale. It is written for developers, DevOps engineers, and technical leaders who want a delivery system they can trust, not just a first green pipeline.
What is CI/CD?
GitLab CI/CD is a continuous integration and continuous delivery platform that automates software building, testing, and deployment through pipelines defined in a .gitlab-ci.yml file. GitLab Runners execute the pipeline jobs, helping teams deliver software consistently with less manual intervention.
CI/CD combines three practices:
- Continuous Integration (CI): every commit to a shared repository is automatically built and tested, so integration problems surface within minutes.
- Continuous Delivery (CD): every change that passes validation is automatically prepared for release. A person still approves the production deployment.
- Continuous Deployment: every change that passes validation is released to production automatically, with no manual gate.
In short, CI/CD helps automate the entire software development lifecycle, allowing organizations to release faster with fewer defects. Because GitLab combines source control, merge requests, and pipelines in one platform, a pipeline can be tied directly to the code change that triggered it.
How does GitLab CI/CD work?
GitLab CI/CD triggers a pipeline when a configured event occurs, such as a push or a merge request. The flow looks like this:
- A developer commits code.
- GitLab detects the event and reads
.gitlab-ci.yml. - GitLab creates a pipeline and organizes jobs into stages.
- Runners pick up and execute the jobs.
- Tests and validation decide whether the pipeline continues.
- Automatic or approved deployment moves the application into its target environment.
Key components of GitLab CI/CD
| Component | Purpose |
|---|---|
| Pipeline | Coordinates the automated workflow |
| Stages | Group jobs into ordered execution phases |
| Jobs | Execute individual tasks |
| GitLab Runner | Application that executes jobs |
.gitlab-ci.yml | Defines the pipeline configuration |
| Artifacts | Store and pass job outputs |
| Cache | Reuse dependencies between runs |
| Environments | Represent deployment targets such as staging and production |
Benefits of Using CI/CD
The value of CI/CD is operational and measurable in your own delivery data, so the benefits below are framed around outcomes rather than generic claims.
- Faster release cycles: automated tests and parallel jobs shorten the feedback loop between commit and result.
- Fewer manual deployment errors: a repeatable, scripted workflow removes configuration drift between environments.
- Better software quality: linting, automated tests, and quality gates run on every change.
- Improved collaboration: merge request pipelines show reviewers whether a change is safe before they approve it.
- Greater visibility and release control: pipeline status, job logs, deployment history, and approval rules give leaders a clear audit trail.
- Scalability: the same pipeline model works for a single service or a portfolio of hundreds of projects.
| Business challenge | GitLab CI/CD capability | Expected outcome |
|---|---|---|
| Slow releases | Automated pipelines | Shorter release cycles |
| Repeated manual work | Reusable jobs and templates | Less operational effort |
| Inconsistent testing | Automated test jobs | More consistent validation |
| Deployment errors | Controlled deployment jobs | More predictable releases |
| Limited release visibility | Pipeline and job monitoring | Better operational oversight |
What do you need before you start?
- A GitLab account and a project repository
- Application source code with a build process that already works locally
- Build and test commands (for example,
npm ciandnpm test) - Access to a GitLab Runner
- A deployment target, if you are implementing CD
- The permissions and credentials needed to deploy
Choosing the right GitLab Runner
A GitLab Runner is an application that receives jobs from GitLab, runs their scripts in a configured environment, and reports results back. Runner scope and runner executor are separate decisions.
| Runner scope | Best suited for | Consideration |
|---|---|---|
| Instance (shared) | Many projects across an instance | Shared infrastructure and access policies |
| Group | Related projects owned by one team | Centralized team-level management |
| Project | One project with specific needs | Most granular configuration and isolation |
The executor determines how a job runs: Docker is the common default because each job gets a clean, reproducible container; Shell runs directly on the host and suits simple or legacy setups; Kubernetes runs each job as a pod and suits teams that need elastic scaling on a cluster. See the official Runner documentation for the full list.
How to Set Up GitLab CI/CD in 7 Simple Steps
The examples use a small Node.js web application, but the structure applies to any stack.
1. Create a GitLab Project
- Sign in and select the + menu, then New project/repository.
- Choose Create blank project, Create from template, or import an existing repository.
- Name the project (for example,
my-ci-project) and set visibility to private or public. - Clone it locally and push your application code.
- Confirm your default branch (usually
main). - Verify that your build and test commands run successfully on your machine. A pipeline automates a process that already works; it cannot fix one that does not.
2. Create a .gitlab-ci.yml File
The .gitlab-ci.yml file in the root of your repository defines your stages, jobs, and rules. Start with a minimal version:
stages:
- build
- test
- deploy
build-job:
stage: build
script:
- echo "Building application"
test-job:
stage: test
script:
- echo "Running tests"
deploy-job:
stage: deploy
script:
- echo "Deploying application"stagessets the execution order. Jobs in the same stage can run in parallel.- Each top-level key that is not a reserved keyword (such as build-job) defines a job.
stageassigns the job to a stage.scriptlists the shell commands the runner executes.
Commit and push the file:
git add .gitlab-ci.yml
git commit -m "Add .gitlab-ci.yml"
git push origin mainBefore pushing, open Build > Pipeline editor to validate the syntax. A pipeline now starts on every push.
3. Configure Runners for the Pipeline
- Go to Settings > CI/CD > Runners in your project.
- Check whether instance (GitLab-hosted) runners are enabled. For many public-cloud projects, these are sufficient.
- If you need control over hardware, network access, or data location, register a self-managed runner by following the GitLab Runner documentation.
- Use runner tags to route jobs. A job with
tags: [docker]only runs on runners carrying that tag. - Keep runners that hold sensitive access (such as production deployment) separate from general-purpose runners.
A minimal Docker-based runner configuration in config. toml looks like this:
concurrent = 4
[[runners]]
name = "docker-runner"
url = "https://gitlab.com"
executor = "docker"
[runners.docker]
image = "alpine:latest"
privileged = falseconcurrent caps how many jobs this runner process executes at once. Keep privileged = false unless a job genuinely needs it, since privileged containers weaken isolation.
4. Add Build and Test Jobs to Your Pipeline
Replace the placeholder scripts with real work. Beyond compiling, add unit tests, linting, and test reports:
build-job:
stage: build
image: node:20-alpine
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 week
unit-test:
stage: test
image: node:20-alpine
script:
- npm ci
- npm test
lint:
stage: test
image: node:20-alpine
script:
- npm ci
- npm run lintunit-test and lint share a stage, so they run in parallel. If any job in the test stage fails, later stages do not run, so a failing test blocks deployment by default. Add integration tests as another job in the test stage, and publish test reports with artifacts:reports:junit so results appear in merge requests.
5. Implement Continuous Deployment (CD)
Most teams promote through development, staging, and production environments. Declare each with the environment keyword, so GitLab tracks deployment history, and require approval for production:
deploy-staging:
stage: deploy
script:
- ./deploy.sh staging
environment:
name: staging
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
deploy-production:
stage: deploy
script:
- ./deploy.sh production
environment:
name: production
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
needs: ["deploy-staging"]when: manual makes the production job wait for a person to start it. Combine this with protected environments (Settings > CI/CD > Protected environments) so only approved roles can deploy, and with protected branches so only trusted code reaches the pipeline. Plan rollback before you need it: keep previous artifacts or image tags available and make redeploying a known-good version a one-click or one-command action.
If you want full continuous deployment, remove the manual gate, but only once your automated tests are trustworthy.
6. Set Up Environment Variables
Never hardcode API keys, passwords, or SSH credentials in .gitlab-ci.yml. Define them as CI/CD variables:
- Open Settings > CI/CD > Variables and select Add variable.
- Enter the key (for example,
DEPLOY_TOKEN) and value. - Enable Mask variable so the value is hidden in job logs.
- Enable Protect variable so it is only available on protected branches and tags.
- Scope the variable to a specific environment (such as
production) where possible.
Reference variables by name, and avoid printing them:
deploy-production:
stage: deploy
script:
- ./deploy.sh production # the script reads $DEPLOY_TOKEN from the environmentA common mistake is echoing a secret to confirm it is set. That risks exposing it in logs, so check that it exists without printing its value.
Masking is not a complete security control. Anyone who can change the pipeline code can write a job that sends a variable elsewhere, so pipeline code must be reviewed and trusted. For production, prefer short-lived credentials (for example, GitLab ID tokens with OpenID Connect to your cloud provider) or an external secrets manager, and grant each credential only the access it needs.
7. Monitor and Optimize Your Pipeline
Commit your pipeline, then confirm it works end to end:
- Push the change and open Build > Pipelines.
- Inspect each stage and job. Open any failed job to read its full log.
- Retry failed jobs after fixing the cause.
- Verify that artifacts were generated and are downloadable.
- Confirm the staging deployment succeeded and the application is healthy.
- Start the manual production job and validate application health afterward.
Working-pipeline checklist:
- ☐ Pipelines start automatically on push and merge request
- ☐ A failing test stops the pipeline before deployment
- ☐ Secrets are masked, protected, and never printed
- ☐ Production requires approval and protected access
- ☐ Artifacts and logs are available for troubleshooting
- ☐ You know how to roll back
Example of a Complete GitLab CI/CD Pipeline
The pipeline below ties the steps together for a Node.js web app: dependency caching, build artifacts, a Docker image pushed to the GitLab container registry, automatic staging deployment, and manual production deployment.
stages:
- build
- test
- package
- staging
- production
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH
default:
image: node:20-alpine
cache:
key:
files:
- package-lock.json
paths:
- .npm/
variables:
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
build:
stage: build
script:
- npm ci --cache .npm --prefer-offline
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 week
unit-test:
stage: test
needs: ["build"]
script:
- npm ci --cache .npm --prefer-offline
- npm test
lint:
stage: test
needs: []
script:
- npm ci --cache .npm --prefer-offline
- npm run lint
package-image:
stage: package
image: docker:27
services:
- docker:27-dind
needs: ["build", "unit-test", "lint"]
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
before_script:
- echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
script:
- docker build -t "$IMAGE_TAG" .
- docker push "$IMAGE_TAG"
deploy-staging:
stage: staging
needs: ["package-image"]
script:
- ./deploy.sh staging "$IMAGE_TAG"
environment:
name: staging
url: https://staging.example.com
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
deploy-production:
stage: production
needs: ["deploy-staging"]
script:
- ./deploy.sh production "$IMAGE_TAG"
environment:
name: production
url: https://www.example.com
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manualAssumptions: the app has build, test, and lint npm scripts and a Dockerfile; a runner that supports Docker-in-Docker (privileged mode) handles the package-image job; deploy.sh is your own script that deploys an image tag to the named target. Treat this as a template to adapt and test, not a production-ready drop-in.
How the example pipeline executes
On a merge request, only build, unit-test, and lint run, which gives reviewers fast feedback. After merge to the default branch, the pipeline also builds a Docker image tagged with the commit SHA, deploys it to staging automatically, and then waits for a person to start the production job. Because the same tagged image moves from staging to production, what you tested is exactly what you ship, which makes releases traceable.
How to adapt the pipeline for different applications
| Application | Typical pipeline jobs |
|---|---|
| Node.js | Install, lint, test, build, deploy |
| Python | Install dependencies, test, package, deploy |
| Java | Compile, unit test, package, integration test, deploy |
| Dockerized microservices | Build image, scan, publish, deploy |
| Infrastructure as Code | Validate, plan, review, apply |
How to Optimize GitLab CI/CD Pipeline Performance
Improve performance by running independent jobs in parallel, using needs to remove unnecessary stage waits, caching dependencies, and skipping work that is not needed. Measure duration before and after each change to confirm it helped.
- Run independent jobs in parallel. Stage-based execution waits for the entire previous stage. With needs, a job starts as soon as the specific jobs it depends on finish. In the example above,
lintusesneeds: []and starts immediately. - Use caching and artifacts correctly. They solve different problems:
| Feature | Cache | Artifacts |
|---|---|---|
| Main purpose | Reuse dependencies and files | Preserve job outputs |
| Typical use | Package dependencies | Build packages, test reports |
| Reuse | Across eligible jobs and pipelines | Between jobs and for later download |
| Role | Performance optimization | Passing specific outputs reliably |
Treat the cache as best-effort. A job must still work if the cache is missing. See the GitLab caching documentation.
- Use conditional execution.
rules,workflow: rules, andchangesto avoid running pipelines or jobs that a change does not affect, which saves runner time and cost. For example, rebuild a service only when its folder changes:
build-api:
stage: build
script:
- ./build.sh api
rules:
- changes:
- services/api/**/*- Use parallel and matrix jobs.
Parallel: matrixruns one job across several versions or configurations, such as multiple Node.js versions. - Reduce runner bottlenecks. Watch queue time, runner
concurrentlimits, and resource sizing. Long pending times usually mean too few runners or mismatched tags. - Reuse pipeline components. Use
include, templates, and versioned CI/CD components so teams share one maintained definition instead of copying YAML between projects.
GitLab CI/CD Security Best Practices
Security belongs inside the pipeline, not after it. A pipeline can reach your source code, registries, and production systems, so it is an attractive target.
- Protect variables and secrets: mask and protect variables, scope them to environments, and use an external secrets manager for high-value credentials.
- Use least-privilege credentials: give each job only the access it needs, and prefer short-lived tokens over long-lived keys.
- Separate trusted and untrusted jobs: pipelines from forks or unreviewed merge requests should never receive production credentials. If they do, a malicious change could read and exfiltrate them.
- Protect production runners and environments: run production deployments on dedicated, access-controlled runners, with protected branches, protected environments, and approval rules.
- Scan dependencies and container images: add dependency, container, and secret-detection scanning as pipeline jobs so issues are caught before release.
- Keep audit logs and deployment records: retain pipeline history and deployment records so you can answer who deployed what, and when.
For product-specific detail, follow GitLab’s CI/CD hardening recommendations and Runner security guidance.
Common GitLab CI/CD Errors and How to Fix Them
| Problem | Likely cause | Fix |
|---|---|---|
| Pipeline does not start | Invalid workflow or rules | Validate the configuration in the pipeline editor |
| Job stays pending | No eligible runner | Check runner availability and tags |
| YAML error | Indentation or syntax mistake | Run CI Lint |
| Dependency install fails | Network, registry, or version issue | Check registry access and pinned versions |
| Artifacts missing | Wrong path or expired | Verify artifacts: paths and expire_in |
| Deployment fails | Credentials or environment permissions | Check protected variables and deploy access |
| Pipeline is slow | Sequential jobs, repeated downloads | Review needs, caching, and parallelism |
How to debug a failed GitLab job
- Open the failed pipeline and identify the first failing job.
- Read the log from the bottom up for the actual error.
- Check variables, runner tags, image versions, and permissions.
- Reproduce the command locally or in the same container image.
- Fix the cause, retry the job, and add a test or check so it does not recur.
GitLab CI/CD vs GitHub Actions vs Jenkins
Each tool is a reasonable choice in the right context. None is universally better.
| Factor | GitLab CI/CD | GitHub Actions | Jenkins |
|---|---|---|---|
| Primary ecosystem | GitLab | GitHub | Independent automation server |
| Configuration | YAML | YAML | Jenkinsfile (Groovy) |
| Execution | GitLab Runners | GitHub-hosted or self-hosted runners | Jenkins agents |
| Source control | Native GitLab | Native GitHub | Multiple providers |
| Extensibility | CI/CD components, integrations | Actions marketplace | Large plugin ecosystem |
| Infrastructure | Hosted or self-managed | Hosted or self-hosted | Self-managed |
- Choose GitLab CI/CD when you want source control and delivery in one platform.
- Choose GitHub Actions when your workflow is centered on GitHub.
- Choose Jenkins when you need deep customization or already run a mature Jenkins environment.
For a closer look at the platforms themselves, see our GitHub and GitLab comparison.
GitLab CI/CD Best Practices for Enterprise Teams
- Standardize pipeline templates across projects.
- Separate development, staging, and production access.
- Enforce automated quality gates.
- Use protected branches and merge request approvals.
- Isolate production credentials.
- Track pipeline failures and deployment frequency.
- Define artifact retention and recovery policies.
- Document who owns and maintains each pipeline.
As teams grow, use parent-child and multi-project pipelines for monorepos and microservices, and centralize shared logic in versioned components. GitLab’s AI-driven DevSecOps innovations are also worth tracking as your platform matures.
How to measure CI/CD effectiveness
DORA research groups software delivery performance into throughput and instability. Track these five metrics:
- Deployment frequency: how often you deploy to production.
- Lead time for changes: how long a commit takes to reach production.
- Failed deployment recovery time: how quickly you recover from a deployment that fails. This is the current term and replaces the older MTTR wording.
- Change failure rate: the share of deployments that cause a failure needing remediation.
- Deployment rework rate: how often you ship unplanned deployments to fix a problem caused by an earlier one.
The first two measure throughput; the rest measure instability. Review them together, since optimizing speed alone can hide quality problems. See the DORA metrics guide for definitions.
When Should You Consider Professional DevOps and CI/CD Implementation?
Many teams build their first pipeline internally. Outside help tends to pay off when the problem is larger than a single pipeline:
- Modernizing legacy applications
- Complex multi-environment or multi-region deployment
- Migrating from manual releases
- Standardizing CI/CD across many teams
- Cloud-native and Kubernetes-based delivery
- Security and compliance requirements
- Persistent reliability or performance problems in existing pipelines
HyScaler helps organizations design and operate delivery pipelines through its DevOps engineering services, software development services, and IT services and solutions. If your development team is evaluating CI/CD standardization, a short conversation with an engineer is often the fastest way to scope it.
Conclusion
GitLab CI/CD automates the path from commit to production. A well-structured pipeline improves consistency, testing, and deployment control, and the seven steps above give you a working foundation: project, .gitlab-ci.yml, runners, build and test jobs, deployment, variables, and monitoring.
As you scale, security, runner management, and performance matter more, and measuring delivery with DORA metrics keeps improvement grounded in data. Design pipelines around your applications, infrastructure, and operational needs, and expand over time into practices such as automatic rollback and canary deployments.
GitLab’s documentation changes often, so validate YAML, runner settings, and tier-specific features against the current docs before using them in production. If you want help building a secure, scalable pipeline, explore HyScaler’s DevOps and IT services.
FAQs
Is GitLab CI/CD free?
Yes. GitLab includes CI/CD in its free tier on both GitLab.com and self-managed installations. Hosted runner usage is limited by compute-minute quotas, and some advanced features require paid tiers. Check GitLab’s current pricing page before planning, since limits and tiers change.
What is the difference between GitLab CI and GitLab CD?
CI automatically builds and tests every code change so problems are found early. CD automatically prepares validated changes for release and can deploy them to environments. In GitLab, both run in the same pipeline, defined in one .gitlab-ci.yml file.
Can I use GitLab CI/CD with other version control systems?
GitLab CI/CD runs for projects hosted in GitLab. If your code lives elsewhere, you can connect an external repository so GitLab builds it, or mirror the repository into GitLab. Native integration works best with GitLab-hosted repositories.
Can I use Docker with GitLab CI/CD?
Yes. Jobs can run inside Docker images for consistent environments, and pipelines can build and push container images to a registry. Docker builds usually need a suitably configured runner, so plan for container security and isolation.
Can GitLab CI/CD deploy to AWS or Kubernetes?
Yes. Pipelines can deploy to AWS, Kubernetes, virtual machines, and other targets using scripts, CLIs, or integrations. Use short-lived credentials such as OIDC-based tokens instead of storing long-lived cloud keys as variables.
What is the difference between GitLab Runner and GitLab CI/CD?
GitLab CI/CD is the overall automation system that defines and orchestrates pipelines. A GitLab Runner is the separate application that actually executes the jobs. GitLab assigns jobs, and runners run them and return results.
How do I secure a GitLab CI/CD pipeline?
Store secrets in masked, protected variables or an external secrets manager, use least-privilege and short-lived credentials, and keep production access off untrusted jobs. Protect branches, environments, and runners, scan dependencies and images, and retain audit logs.