Github Actions to Build and Push to Docker Hub

From Logic Wiki
Jump to: navigation, search


Create Token in Docker Hub

To create your access token:

  1. Log in to hub.docker.com.
  2. Click on your username in the top right corner and select Account Settings.
  3. Select Security > New Access Token.
  4. Add a description for your token.

Create Secrets in GitHub

  1. Go to repository
  2. Go to Settings
  3. Click Secrets

Create Action in Github

Change

  • IMAGE_NAME variable for subfolders. If there is no subfolder in the project delete defaults, run working directory tree from push section
  • paths must be updated for subfolders
  • name must be changed
name: api_identity_to_dockerhub

on:
  push:
    branches:
      - main
    paths:
      - 'api-identity/**'

env:
  # TODO: Change variable to your image's name.
  IMAGE_NAME: api-identity

jobs:
  push:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ./${{ env.IMAGE_NAME }} 
    steps:
      - uses: actions/checkout@v2
      - name: Build image
        run: docker build . --file Dockerfile --tag image

      - name: Log into registry
        run: echo "${{ secrets.DOCKERHUB_PASSWORD }}" | docker login -u ${{ secrets.DOCKERHUB_USERNAME }} --password-stdin

      - name: Push image
        run: |
          IMAGE_ID=aliiybar/${{ env.IMAGE_NAME }}
          # Strip git ref prefix from version
          VERSION=$(echo "${{ github.ref }}" | sed -e 's,.*/\(.*\),\1,')
          # Strip "v" prefix from tag name
          [[ "${{ github.ref }}" == "refs/tags/"* ]] && VERSION=$(echo $VERSION | sed -e 's/^v//')
          # Use Docker `latest` tag convention
          [ "$VERSION" == "master" ] && VERSION=latest
          echo IMAGE_ID=$IMAGE_ID
          echo VERSION=$VERSION

          docker tag image $IMAGE_ID:$VERSION
          docker push $IMAGE_ID:$VERSION