Deploying Web App using GitLab CI

September 18, 2017

Whenever we want to deploy a codebase to a server, we need to do lots of process like unit testing, linting, building, uploading it to the server, etc.

It is tedious, right? Why not automate it.

Just push those changes and let GitLab CI handle those tasks for you.

Step 1: Generating SSH Keys

In order to push the code from GitLab repo to our server, we need to authenticate GitLab CI.

To generate SSH key pair, open up your terminal and execute the following command.

<code class="sh">ssh-keygen -t rsa -b 4096 -C

And then enter the full path where you need to store the SSH key pairs.

Then SSH to your server

And then append the public key ( in ~/.ssh/authorized_keys

Step 2: Setting up your CI environment variables

Just like your machine, you can also add environmental variables in your GitLab CI.

And you can access those variables in your CI.

Its under Settings > Variables tab.

SERVER_IP -> Your server IP address
AUTO_DEPLOY_PRIVATE_KEY -> Private Key which we just created (deploy-ci)
APP_ROOT -> Path to where need to deploy the app

Instead of hardcoding those things in GitLab CI config I like to keep it as environmental variables.

So that,

  • You don’t need to edit your CI config often.
  • And you can just copy paste it your other projects and just change the env variables :)

gitlab environmental variables

Step 3: GitLab CI

Create a .gitlab-ci.yml file at the root of your repo. And when you push the code to your repo. GitLab would check and execute your tasks.

Basically, GitLab CI is a docker container which allows us to execute any Linux command you want to.

Just like I mentioned before we can do a lot of things like building, testing your code, etc.

For the sake of simplicity, I’m just deploying the code in my repo to my server.

Here’s GitLab config, You can just copy/paste it :)

image: node:latest
  - deploy
  stage: deploy
    - apt-get update -y
    # install ssh-agent
    - 'which ssh-agent || (apt-get install openssh-client -y )'
    - 'which rsync || (apt-get install rsync -y )'
    # run ssh-agent
    - eval $(ssh-agent -s)
    # add ssh key stored in AUTO_DEPLOY_PRIVATE_KEY variable to the agent store
    - ssh-add <(echo "$AUTO_DEPLOY_PRIVATE_KEY")
    # disable host key checking (NOTE: makes you susceptible to man-in-the-middle attacks)
    - mkdir -p ~/.ssh
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
    - rsync -r -v -e ssh . $SSH_USER_NAME@$SERVER_IP:$APP_ROOT --delete-before --exclude '.git'
    - echo "Deployed!"
    - master

If you’ve customised it, just make sure to lint it

👋 I'm Ashik Nesin • Principal Software Engineer @Chargebee 👨‍💻• I write about web development & behinds the scenes of startup/side projects that I'm building

© 2022 Nesin Technologies LLP