GitLab CI/CD: Deploy Code to Staging in Minutes

GitLab CI/CD Deployment for Beginners is your step-by-step guide to pushing code to a remote staging server using secure SSH automation. Whether you’re new to GitLab or DevOps, this tutorial will help you automate your deployment pipeline quickly and safely.


βœ… Why You Should Deploy to Remote Server with GitLab CI/CD

Deploy to remote server with GitLab CI/CD and simplify your staging or production workflow. In this guide, you’ll learn how to set up a secure, automated CI/CD pipeline to deliver your code efficiently. Whether you’re new to DevOps or just starting with GitLab, this tutorial will walk you through the essential steps β€” from SSH setup to deployment execution.

πŸ“ Note: Every project and server environment can have its own unique requirements and configurations. This tutorial provides a general deployment process, not a one-size-fits-all setup. Adjust scripts and paths based on your infrastructure.

Before setting up automated deployments, it’s important to understand how to commit and push your changes properly. Learn more in our guide: Basic Git Commands for GitLab Developers.


βœ… GitLab CI/CD Deploy Code Requirements for Remote Server

Requirement Description
πŸ§‘β€πŸ’» GitLab Project GitLab CI/CD must be enabled in your project.
πŸš€ Remote Staging Server – Public IP or DNS
– SSH access
– Git and build tools installed
πŸ” Deploy User Non-root user with write access to deployment folder (e.g. /home/deploy/app).
πŸ€– GitLab Runner Shared or self-hosted GitLab Runner connected to your project.

πŸ› οΈ Step 1: Generate an SSH Key for GitLab CI/CD Remote Deployment

ssh-keygen -t rsa -b 4096 -C "gitlab-staging-deploy"
  • Accept the default file path
  • Leave passphrase empty

This creates:

  • ~/.ssh/id_rsa β€” your private key
  • ~/.ssh/id_rsa.pub β€” your public key

πŸ” Step 2: Add the Public Key to Your Remote Staging Server

ssh-copy-id -i ~/.ssh/id_rsa.pub deploy@staging.yourdomain.com

Or manually add the contents of id_rsa.pub to ~/.ssh/authorized_keys.


πŸ” Step 3: Add the SSH Private Key to GitLab CI/CD Variables

  1. Go to GitLab β†’ Settings β†’ CI/CD β†’ Variables
  2. Add new variable:
    • Key: STAGING_SSH_KEY
    • Value: Paste the contents of id_rsa (private key)
    • Type: File
    • Protected: βœ… (recommended)

✍️ Step 4: Configure .gitlab-ci.yml to Deploy Code via GitLab CI/CD

stages:
  - build
  - deploy

variables:
  STAGING_USER: "deploy"
  STAGING_HOST: "staging.yourdomain.com"
  STAGING_PATH: "/home/${STAGING_USER}/app"

before_script:
  - 'which ssh-agent || (apt-get update -y && apt-get install openssh-client -y)'
  - eval $(ssh-agent -s)
  - echo "$STAGING_SSH_KEY" | tr -d '\r' | ssh-add -
  - mkdir -p ~/.ssh
  - ssh-keyscan -H $STAGING_HOST >> ~/.ssh/known_hosts

build_app:
  stage: build
  script:
    - echo "Running build..."
    - mkdir -p dist
    - echo "Sample Build Output" > dist/index.html
  artifacts:
    paths:
      - dist/

deploy_staging:
  stage: deploy
  only:
    - development
  script:
    - ssh $STAGING_USER@$STAGING_HOST "mkdir -p $STAGING_PATH"
    - rsync -avz --delete dist/ $STAGING_USER@$STAGING_HOST:$STAGING_PATH
    - ssh $STAGING_USER@$STAGING_HOST "sudo systemctl reload nginx"
  environment:
    name: staging
    url: http://staging.yourdomain.com
  when: manual

βš™οΈ Step 5: Prepare Your Remote Server for Deployment

sudo apt update
sudo apt install git rsync nginx -y
sudo adduser deploy
sudo mkdir -p /home/deploy/app
sudo chown -R deploy:deploy /home/deploy/app

This ensures your deployment user has full access to the target directory.


πŸ” Step 6: Give Nginx Access to Deployed Files

1. Allow the Deploy User to Reload Nginx

sudo visudo

Add this line:

deploy ALL=NOPASSWD: /bin/systemctl reload nginx

2. Set Directory Permissions for Nginx Read Access

chmod o+x /home/deploy
chmod -R o+r /home/deploy/app

Optional: Create a symlink if Nginx is pointing to /var/www/html:

ln -s /home/deploy/app /var/www/html/app

πŸ”„ Optional: Use Git Pull Instead of Rsync

If your server has the repo cloned, you can update code with:

script:
  - ssh $STAGING_USER@$STAGING_HOST "cd $STAGING_PATH && git pull origin development && ./build.sh"

πŸ“Š Monitor Your Remote Deployments in GitLab

  • Go to GitLab β†’ Operations > Environments
  • Track deployment logs, history, and URLs
  • Trigger manual deployments if when: manual is used

βœ… Best Practices for GitLab CI/CD Remote Server Deployment

Practice Details
πŸ” Use SSH Keys Never use passwords. Store private keys as protected CI/CD variables.
🧾 Use Artifacts Only deploy what you build. Avoid syncing entire repos.
🚫 Avoid Root Access Always deploy as a non-root user for better security.
🧠 Track Your Deployments Use GitLab environments to monitor and manage releases.
πŸ•ΉοΈ Use when: manual Control when deploys happen β€” ideal for QA teams.

🧠 Final Thoughts on GitLab CI/CD Deploy Code Process

Now you know how to deploy to remote server with GitLab CI/CD using a clean, beginner-friendly pipeline. By following this guide, you’ve learned how to GitLab CI/CD deploy code efficiently and securely using SSH and automation. With secure SSH keys, build artifacts, and deployment automation, your DevOps workflow becomes faster, safer, and more consistent.


πŸ“š References

lordfrancs3

lordfrancs3

Lordfrancis3 is a member of PinoyLinux since its establishment in 2011. With a wealth of experience spanning numerous years, he possesses a profound understanding of managing and deploying intricate infrastructure. His contributions have undoubtedly played a pivotal role in shaping the community's growth and success. His expertise and dedication reflect in every aspect of the journey, as PinoyLinux continues to champion the ideals of Linux and open-source technology. LordFrancis3's extensive experience remains an invaluable asset, and his commitment inspires fellow members to reach new heights. His enduring dedication to PinoyLinux's evolution is truly commendable.

Articles: 35

Leave a Reply

Your email address will not be published. Required fields are marked *