GitLab CI

Run Docker instance

GitLab CI use Docker container to run jobs. To deploy on your server, you have to create a SSH key for GitLab CI.

You can create a local Docker alpine:latest to test CI.

docker pull alpine:latest

Run with interactive mode

docker run -it alpine:latest sh

Init SSH

command -v ssh-agent >/dev/null || ( apk add --update openssh )
eval $(ssh-agent -s)

Create SSH key

ssh-keygen -t ed25519

Now you can add the public key to your server ~/.ssh/authorized_keys file.

cat ~/.ssh/

And private key to GitLab CI/CD Variables.

cat ~/.ssh/id_ed25519

Test CI

Set variables:
SSH_PRIVATE_KEY=`cat ~/.ssh/id_ed25519`

Setup SSH

echo -e "${SSH_PRIVATE_KEY}" | tr -d '\r' | ssh-add - > /dev/null
mkdir -p ~/.ssh
chmod 700 ~/.ssh
ssh-keyscan >> ~/.ssh/known_hosts
chmod 644 ~/.ssh/known_hosts

Test SSH

ssh -${SSH_USER}@${SSH_IP}

If it works, you can exit.


GitLab CI/CD Variables

You can find variables in Settings > CI/CD > Variables.

You have two ways to set variables:
  • Project variables are available only for this project.
  • Group variables are available for all projects in this group.


GitLab CI/CD Pipeline

Now you can create a .gitlab-ci.yml file at the root of your project.

# A pipeline is composed of independent jobs that run scripts, grouped into stages.
# Stages run in sequential order, but jobs within stages run in parallel.
# For more information, see:

  - deploy

  NODE_VERSION: 18.17.0

  stage: deploy
  image: alpine:latest
    - 'command -v ssh-agent >/dev/null || ( apk add --update openssh )'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan $SSH_IP >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
    - ssh $SSH_USER@$SSH_IP "
      . ~/.zshrc &&
      cd ~/www/$CI_PROJECT_NAME &&
      git pull &&
      ~/.nvm/versions/node/v$NODE_VERSION/bin/pnpm i &&
      ~/.nvm/versions/node/v$NODE_VERSION/bin/pnpm generate &&
      notifier '$CI_PROJECT_TITLE deployed'"
    - main
  • $CI_PROJECT_NAME and $CI_PROJECT_TITLE are predefined variables from GitLab CI.
  • $NODE_VERSION is a custom variable for this project only, defined in variables: section.
  • $SSH_PRIVATE_KEY, $SSH_IP and $SSH_USER are custom variables, defined in Settings > CI/CD > Variables.
  • . ~/.zshrc allow to load zsh config file.
  • ~/.nvm/versions/node/v$NODE_VERSION/bin/pnpm is the path to pnpm binary.
  • notifier is a custom script with go to send notification to Discord, you can find it here notifier

Now you can install your own runner on your server with this guide.