Gitlab CI/CD + PM2

Example

image: node:14.15.0-alpine

cache:
  key: "$CI_PROJECT_ID-$CI_COMMIT_REF_SLUG"
  paths:
    - node_modules/

stages:
  - deploy

before_script:
  - npm set progress=false

deploy_dev:
  stage: deploy
  variables:
    NODE_ENV: "dev"
  script:
    - apk update && apk --no-cache --update add bash openssh-client make build-base git
    # Run ssh-agent (inside the build environment)
    - eval $(ssh-agent -s)
    # Add the SSH key stored in SSH_WEB_PRIVATE_KEY variable to the agent store
    - echo "$SSH_WEB_PRIVATE_KEY" | ssh-add -
    - mkdir -p ~/.ssh
    # For Docker builds disable host key checking. Be aware that by adding that
    # you are suspectible to man-in-the-middle attacks.
    - echo -e "StrictHostKeyChecking no" >> ~/.ssh/config
    # Install pm2
    - npm i pm2 -g
    # Create .env with variables from Gitlab CI
    - echo "$DOTENV" > .env
    # Deploy project
    - pm2 deploy ecosystem.config.js dev
  only:
    - dev
  environment:
    name: dev
    url: https://dev.example.com
  tags:
    - docker
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

SSH key

Private key already added to WEB group in gitlab, just use SSH_WEB_PRIVATE_KEY

Copy public key to server

ssh-copy-id -i ~/.ssh/id_rsa_gitlab.pub user@host
1

.env

Create a custom variableopen in new window with environment-specific variables.

Use environments for dev/staging/production

Add to .gitlab-ci.yml deploy script

script:
  # ...
  - echo "$DOTENV" > .env
  # Deploy project
1
2
3
4