How to Deploy a NodeJs App to Ubuntu Virtual Machine with Azure DevOps Pipelines

30 December, 2022

NodeJsJavascriptDevOpsAzure

The pre-configuration steps that are required to ensure your server is ready to accept the NodeJs app files and to ensure Azure DevOps can connect to the server are:

  • Set up an environment in your Azure DevOps project
  • Create an SSH Connection Authorisation in Azure DevOps
  • Create the target folder on the Ubuntu server
  • Install NodeJs on the Ubuntu server
  • Install pm2 globally on the Ubuntu server

The essential steps of this deployment pipeline are:

  • Fetch the app files from the selected git repo (GitHub, Bitbucket etc)
  • Use the pre-built CopyFilesOverSSH task from Azure DevOps
  • Exclude the node_modules and git related files
  • SSH into the Ubuntu server
  • Run the NPM scripts (Test, Build)
  • Start the app using PM2
trigger: - main variables: # Azure Resource Manager connection created during pipeline creation azureSubscription: '${Your Azure Subscription Name}' # Agent VM image name vmImageName: 'ubuntu-latest' environmentName: '${Azure DevOps Environment Name}' pool: vmImage: $(vmImageName) stages: - stage: Build displayName: Build stage jobs: - job: Build displayName: Build steps: - task: CopyFilesOverSSH@0 inputs: sshEndpoint: '${ssh-connection-name}' sourceFolder: '$(System.DefaultWorkingDirectory)' contents: | ** !node_modules/** !.git/** targetFolder: '/home/${Ubuntu-Server-Username}/${nodejs-app-folder}' cleanTargetFolder: true cleanHiddenFilesInTarget: false readyTimeout: '20000' - task: SSH@0 inputs: sshEndpoint: '${ssh-connection-name}' runOptions: 'inline' inline: | cd ${nodejs-app-folder} npm install --silent npm run build pm2 stop ${build-folder-main-js-file} pm2 start ${build-folder-main-js-file} readyTimeout: '20000'

Improvements that could be implemented to this pipeline are to ensure a npm test script is run and that all tests pass before allowing the build task to execute.

If you liked this post, please share it!