For this weekend’s fun project, let’s setup Github Actions and Github Container Registry so we can do CI/CD with our NodeJS project hosted on DigitalOcean. The goal is to have Github Actions create a new Docker image when we push to master, deploy the image to ghcr.io, ssh to the server, download the image and build the container.

Create the app/repo

Let’s create a new public repo on Github named nodejs-playground, add a simple app to this repo:

Package.json file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
  "name": "nodejs",
  "version": "1.0.0",
  "description": "nodejs project",
  "author": "Cuong Tran",
  "license": "MIT",
  "main": "app.js",
  "keywords": ["nodejs", "bootstrap", "express"],
  "dependencies": {
    "express": "^4.16.4"
  }
}

app.js file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const express = require('express');
const app = express();

const port = 8080;
app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

Dockerfile file:

1
2
3
4
5
6
7
8
9
FROM node:20-alpine
RUN mkdir -p /app/node_modules && chown -R node:node /app
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY --chown=node:node . .
EXPOSE 8080
USER node
CMD [ "node", "app.js" ]

Setup Github Actions

Once we have the repo ready, create a Github Actions workflow - we can use Github’s Actions template for Publish Docker Container:

 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
name: Docker

on:
  schedule:
    - cron: '24 18 * * *'
  push:
    branches: ['main']
    # Publish semver tags as releases.
    tags: ['v*.*.*']
  pull_request:
    branches: ['main']

env:
  # Use docker.io for Docker Hub if empty
  REGISTRY: ghcr.io
  # github.repository as <account>/<repo>
  IMAGE_NAME: ${{ github.repository }}
  CONTAINER_NAME: nodejs-playground
  GHCR_SECRET: ${{ secrets.GHCR_SECRET }}

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      # This is used to complete the identity challenge
      # with sigstore/fulcio when running outside of PRs.
      id-token: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      # Install the cosign tool except on PR
      # https://github.com/sigstore/cosign-installer
      - name: Install cosign
        if: github.event_name != 'pull_request'
        uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 #v3.5.0
        with:
          cosign-release: 'v2.2.4'

      # Set up BuildKit Docker container builder to be able to build
      # multi-platform images and export cache
      # https://github.com/docker/setup-buildx-action
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0

      # Login against a Docker registry except on PR
      # https://github.com/docker/login-action
      - name: Log into registry ${{ env.REGISTRY }}
        if: github.event_name != 'pull_request'
        uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      # Extract metadata (tags, labels) for Docker
      # https://github.com/docker/metadata-action
      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

      # Build and push Docker image with Buildx (don't push on PR)
      # https://github.com/docker/build-push-action
      - name: Build and push Docker image
        id: build-and-push
        uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0
        with:
          context: .
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      # Sign the resulting Docker image digest except on PRs.
      # This will only write to the public Rekor transparency log when the Docker
      # repository is public to avoid leaking data.  If you would like to publish
      # transparency data even for private images, pass --force to cosign below.
      # https://github.com/sigstore/cosign
      - name: Sign the published Docker image
        if: ${{ github.event_name != 'pull_request' }}
        env:
          # https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable
          TAGS: ${{ steps.meta.outputs.tags }}
          DIGEST: ${{ steps.build-and-push.outputs.digest }}
        # This step uses the identity token to provision an ephemeral certificate
        # against the sigstore community Fulcio instance.
        run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}

We add a new env variable named CONTAINER_IMAGE to use later for our container’s name CONTAINER_NAME: nodejs-playground.

The first part of the workflow is used to create the image and deploy to ghcr.io. Let’s add the next part to connect to the server and build the container:

 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
deploy:
  runs-on: ubuntu-latest
  needs: build

  steps:
    - name: Deploy to Digital Ocean droplet via SSH action
      uses: appleboy/ssh-action@v1.0.3
      with:
        host: ${{ secrets.DIGITALOCEAN_HOST }}
        username: ${{ secrets.USERNAME }}
        key: ${{ secrets.SSHKEY }}
        passphrase: ${{ secrets.PASSPHRASE }}
        envs: IMAGE_NAME,REGISTRY,GHCR_SECRET
        script: |
          # Login to registry
          echo $GHCR_SECRET | docker login ghcr.io -u ${{ github.actor }} --password-stdin
          docker pull ghcr.io/${{ env.IMAGE_NAME }}:main
          # Check if container exists - if exists stop and remove container
          CONTAINER_EXISTS=$(docker inspect -f '{{.State.Running}}' ${{ env.CONTAINER_NAME }} 2>/dev/null || echo "false")
          if [ "$CONTAINER_EXISTS" = "true" ]; then
            echo "Stopping and removing existing container..."
            docker stop ${{ env.CONTAINER_NAME }}
            docker rm ${{ env.CONTAINER_NAME }}
          else
            echo "Container does not exist, no need to stop and remove."
          fi
          # Run a new container from a new image
          docker run -d --name ${{ env.CONTAINER_NAME }} -p 8080:8080 ghcr.io/${{ env.IMAGE_NAME }}:main          

In order for this part to run, we need to add some Actions secrets. From Repository Settings -> Secrets and variables -> Actions -> New Repository Secrets:

  • DIGITALOCEAN_ACCESS_TOKEN: DigitalOcean dashboard -> API -> Token -> Full Access
  • DIGITALOCEAN_HOST: your droplet’s ipv4
  • PASSPHRASE: SSH Key passphrase
  • SSHKEY: private SSH Key ~/.ssh/id_rsa - can by copied by running cat ~/.ssh/id_rsa - check out https://github.com/appleboy/ssh-action for more details
  • USER: default is root

Once the workflow finishes running - a new image will be published to ghcr.io and available to view from the packages tab https://github.com/[USER_NAME]?tab=packages. We now should be able to use Github Actions to deploy new changes to our server.