Building and Pushing Docker images using Github Actions

We needed to build a Docker image via Github Actions and push to the Package repository to create a public, shareable image.

Add the following in a .github/workflows folder with a .yml extension. You'll also need to add the following secrets to the respoitory:

  • DOCKER_USERNAME - the username whose token you will be using
  • DOCKER_TOKEN -an access token with write:packages permission

Once you have pushed the package, you will need to go to the Packages tab on either the organisation and associate it with the repository. Once that is done, the package appears on the right-hand side of the repository list.

Action YAML Example

This code was copied (and adapted) from the official Github Docs website.

I've added (but left commented out) and example of how to pass in a build argument too.

name: Create and publish a Docker image

    branches: ['main']

  IMAGE_TAG: latest

    runs-on: ubuntu-latest

      contents: read
      packages: write

	  # Hack to add an env variable built up of env variables
      - name: Set docker image env var
        run: |
          echo "IMAGE_NAME=$/$:$" >> $GITHUB_ENV

      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v2
          username: $
          password: $

      - name: Build and push Docker image
        uses: docker/build-push-action@v4
          context: .
           #build-args: |
          push: true
          tags: $

View this post on Github

You might also enjoy…

Mike Street

Written by Mike Street

Mike is a CTO and Lead Developer from Brighton, UK. He spends his time writing, cycling and coding. You can find Mike on Mastodon.