How To Use Github Actions To Auto Deploy Your Next.js App (Ubuntu)

Publish Date - 21st April 2023

Last Updated - 21st April 2023

Sometimes, SSH'ing into your server after every update for redeployment is annoying.

Github has an amazing Continuous Integration (CI) and Continuous Deployment tool set via Github Actions.

What Is A Github Action

A Github action is a script that executes in response to another event. For example, an action can run when you commit to a specific repository.

Conveniently, there is a marketplace that have pre-build modules we can add to our script. More on this later.

Preparing The Workflow

Create a new directory in your project root called .github/workflows

mkdir .github && mkdir .github/workflows

Inside the workflows folder, create a file called Deploy.yml. You can name this folder anything you want. Just make sure it's has a .yml.

Finding The Right Github Action Plugin

Before we write the details of the Deploy.yml file, we need to find the pre build modules we intend to use.

To deploy your application on your Ubuntu server, we need to allow gitbub to login and execute commands.

There is a module for this called SSH Remote Commands.

Allowing for SSH

The final step before writing the script is to allow for SSH.

Navigate to the repo on Click on settings and on the left, click on secrets and Variables, then actions.

In this section you want to add the following two repository secret:

  • First Secret
    • Name: USER
    • Secret: <The Username For Your Ubuntu Server>
  • Second Secret
    • Name: KEY
    • Secret: <Copy Private SSH Key>

It's important to follow the ssh instructions from Appleboy's documentation here. Otherwise, your action will fail.

Writing The Script

Here is the script for the deploy action.

Inside the Deploy.yml file:

name: Deploy

  push:  # <-- Activate script on push
    branches: [ 'Branch Name' ] # Add name of branch here

    name: Deploy
    runs-on: ubuntu-latest
    - name: deploying to ubuntu server
      uses: appleboy/ssh-action@v0.1.10 # Here is the appleboy module
        host: <ADD YOUR HOST IP>
        username: ${{ secrets.USER }} # Accesses USER secret automatically

        key: ${{ secrets.KEY }} # Accesses KEY secret automatically
        port: 22
        script: |    # <-- The steps to deploy
          cd kev-blog
          git pull
          npm run build
          pm2 reload 1

All this script is doing is:

  • When a commit is pushed to the specified branch...
  • Login to server at ~/
  • Find the kev-blog folder which is where this blog is
  • Pull the changes from Github
  • Rebuild the Next.js package
  • Reload PM2 which serves the Next.js app

Observing The Deployment

Inside your repo, you can go to the Actions tab to observe this happening live. And success and failure messages.

That's it for now.