GitlabIntermediate

How to Set Up GitLab CI/CD Pipeline for Multiple Environments: A Beginner's Guide

DeveloperHat Team
5 min read

TL;DR

A step-by-step guide to creating and managing GitLab CI/CD pipelines for development, staging, and production environments with best practices and optimization techniques.

Introduction πŸš€

Welcome to our beginner-friendly guide on setting up GitLab CI/CD pipelines! Think of a CI/CD pipeline like a cooking recipe - you follow a series of steps to create something amazing. In this case, we're creating an automated way to deliver your code from development to production.

What You'll Learn πŸ“š

  • Basic concepts of CI/CD pipelines
  • How to create a .gitlab-ci.yml file
  • Setting up multiple environments
  • Best practices and optimization tips
  • Prerequisites πŸ› οΈ

    Before we start, make sure you have:

  • A GitLab account
  • A project repository on GitLab
  • Basic understanding of Git commands
  • Docker installed (optional but recommended)
  • Understanding CI/CD Basics πŸŽ“

    CI/CD stands for Continuous Integration and Continuous Deployment/Delivery. Let's break it down:

  • Continuous Integration (CI) πŸ”„
  • - Automatically building and testing your code

    - Finding and fixing bugs early

    - Keeping your code quality high

  • Continuous Deployment (CD) πŸš€
  • - Automatically deploying your code

    - Managing different environments

    - Ensuring smooth releases

    Creating Your First Pipeline 🎯

    Let's create a simple pipeline. Create a file named .gitlab-ci.yml in your project root:

    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 run test
    
    deploy-staging:
      stage: deploy
      script:
        - echo "Deploying to staging..."
      environment:
        name: staging
      only:
        - develop
    
    deploy-production:
      stage: deploy
      script:
        - echo "Deploying to production..."
      environment:
        name: production
      only:
        - main

    Pipeline Stages Explained πŸ”

    1. Build Stage πŸ—οΈ

    This is where we prepare our application:

  • Install dependencies
  • Compile code
  • Create artifacts
  • 2. Test Stage βœ…

    Here we ensure everything works:

  • Run unit tests
  • Run integration tests
  • Check code quality
  • 3. Deploy Stage πŸš€

    Finally, we deploy our application:

  • Deploy to staging
  • Deploy to production
  • Verify deployment
  • Environment Variables and Secrets πŸ”

    Keep sensitive information secure using GitLab's CI/CD variables:

  • Go to Settings > CI/CD
  • Expand Variables section
  • Add your variables:
  • - API keys

    - Database credentials

    - Environment-specific configs

    Best Practices πŸ’‘

  • Keep It Simple
  • - Start small and expand gradually

    - Use clear, descriptive names

  • Cache Dependencies
  • cache:
      paths:
        - node_modules/

  • Use Pipeline Templates
  • - Create reusable configurations

    - Maintain consistency across projects

  • Monitor Performance
  • - Watch pipeline duration

    - Optimize slow stages

    Troubleshooting Tips πŸ”§

    Common issues and solutions:

  • Pipeline Fails to Start
  • - Check runner availability

    - Verify .gitlab-ci.yml syntax

  • Build Errors
  • - Check dependency versions

    - Verify build scripts

  • Deploy Failures
  • - Check environment variables

    - Verify deployment credentials

    Next Steps 🎯

    Now that you have your basic pipeline:

  • Add more test stages
  • Implement code quality checks
  • Add deployment notifications
  • Set up monitoring
  • Conclusion πŸŽ‰

    Going Further: Multiple Environments Without the Fear

    A first pipeline deploys. A production pipeline promotes β€” the same artifact moves dev β†’ staging β†’ production, so what you tested is byte-for-byte what you ship. The pieces that make that safe in GitLab:

  • Protected environments and branches: production deploys run only from protected branches, by protected roles, with deployment approvals where the risk justifies them.
  • Environment-scoped variables: the same job definition reads different DATABASE_URL / credentials per environment scope β€” never hard-code per-environment values into job scripts.
  • Manual gates where they earn their keep: when: manual on production is not a lack of automation; it is a deliberate human checkpoint. Automate it away only when your rollback is faster than your regret.
  • Review apps for merge requests: an ephemeral environment per MR catches integration issues staging never will, because staging is always somebody else's broken state too.
  • Cache and artifacts discipline: cache dependencies (keyed on the lockfile), pass build outputs as artifacts, and never rebuild at deploy time β€” a rebuild is a new, untested artifact.
  • Implementation Checklist

  • [ ] One artifact built once, promoted through every environment
  • [ ] Production environment protected; deploy job restricted to protected branches
  • [ ] Secrets stored as masked/protected CI variables or an external vault β€” never in .gitlab-ci.yml
  • [ ] Pipeline fails fast: lint and unit tests before any deploy stage can start
  • [ ] Rollback path rehearsed (redeploy previous artifact), not improvised during an incident
  • Trade-offs

    Every gate you add trades deploy speed for blast-radius control. Manual production approvals are right for a payments system and pure friction for a marketing site. Equally, GitLab CI's YAML anchors and extends keep small pipelines tidy but can hide behaviour as pipelines grow β€” when the file passes a few hundred lines, split it with include: and child pipelines before it becomes folklore.

    Congratulations! You've created your first GitLab CI/CD pipeline. Remember:

  • Start simple
  • Test thoroughly
  • Monitor and optimize
  • Keep learning and improving
  • Need help? Check out:

  • GitLab Documentation
  • Community Forums
  • Stack Overflow
  • Happy coding! πŸš€

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week β€” patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.