Auto Build & Deploy Nextjs with Azure Pipelines via SSH

Posted on October 31st, 2020

In the previous post, I guided how to deploy nextjs to centos. In this article, I will guide you to automatically build and deploy nextjs to the server using azure pipelines.

In this article, we will not introduce what Azure Pipelines or how to create new pipeline. If you are new, you can refer to here.

Add task SSH

I love to use the classic editor to create a pipeline without YAML.

azure pipelines ssh

1. Add Service connections

Click 1 "manage" to create ssh connection to the server.

2, 3. Add script

Select 2 "Inline Script" and paste the code below:

cd /var/www/html/your-source-code
git checkout .
git pull
npm i
npm run build
pm2 restart yourapp

This means you point to the directory containing the source code, reset the changed files. Then pull back the latest source. Install npm and build source.

Then let pm2 update the build just created.

4. Prevent Fail on STDERR

If this option is selected, the build will fail when the remote commands or script write to STDERR.

Complete yaml file

- task: SSH@0
  displayName: "Run shell inline on remote machine"
  inputs:
    sshEndpoint: "your-ssh-endpoint"
    runOptions: inline
    inline: |
      cd /var/www/html/your-source-code
      git checkout .
      git pull
      npm i
      npm run build
      pm2 restart yourapp
    failOnStdErr: false

5. Auto run pipelines when merge develop

Select Triggers tab.
Check Enable continuous integration. Input Branch specification: develop azure pipelines trigger

Tips: You can add task "Post to Slack" to notify when the build is complete.