DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Build Node.js App Docker Image and Push to Docker Private Repo With GitHub Actions
  • [CSF] Enable Continuous Delivery of Your Resume With GitHub Actions
  • Effective Microservices CI/CD With GitHub Actions and Ballerina
  • Deploy MuleSoft App to CloudHub2 Using GitHub Actions CI/CD Pipeline

Trending

  • [DZone Research] Join Us for Our 5th Annual Kubernetes Survey!
  • Message Construction: Enhancing Enterprise Integration Patterns
  • Difference Between High-Level and Low-Level Programming Languages
  • How To Aim for High GC Throughput
  1. DZone
  2. Software Design and Architecture
  3. Containers
  4. GitHub Action Recipes: Building and Pushing Docker Images to a Container Registry

GitHub Action Recipes: Building and Pushing Docker Images to a Container Registry

This GitHub Actions workflow builds a Docker image, tags it, and pushes it to one of three container registries following industry best practices.

Natalie Lunbeck user avatar by
Natalie Lunbeck
·
Sep. 08, 23 · Tutorial
Like (3)
Save
Tweet
Share
5.08K Views

Join the DZone community and get the full member experience.

Join For Free

This GitHub Actions workflow builds a Docker image, tags it, and pushes it to one of three container registries. Here’s a Gist with the boilerplate code.

Building Docker Images and Pushing to a Container Registry

If you haven’t yet integrated GitHub Actions with your private container registry, this tutorial is a good place to start. The resulting workflow will log in to your private registry using the provided credentials, build existing Docker images by path, and push the resulting images to a container registry. We’ll discuss how to do this for GHCR, Docker Hub, and Harbor.

Benefits and Use Cases

Building and pushing Docker images using your CI/CD platform is a best practice. Here’s how it can improve your developer QoL:

  • Shared builds: Streamline the process, configuration, and dependencies across all builds for easy reproducibility.
  • Saves build minutes: Team members can access existing images instead of rebuilding from the source.
  • Version control: Easily duplicate previous builds with image tags, allowing teams to trace and pinpoint bugs.

Building a Docker Image

Using GitHub Actions to automate Docker builds will ensure you keep your build config consistent. This only requires substituting your existing build command(s) into the workflow YAML. In this workflow, the image is named after your GitHub repo using the GITHUB_REPOSITORY environment variable as {{ github.repository }}.

YAML
 
name: Build Docker image
on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Build and tag image
        COMMIT_SHA=$(echo $GITHUB_SHA | cut -c1-7)
        run: docker build -t ${{ github.repository }}:$COMMIT_SHA -f path/to/Dockerfile .


Versioning Your Docker Image Tags

Never rely on latest tags to version your images. We recommend choosing one of these two versioning conventions when tagging your images: using the GitHub commit hash or following the SemVer spec.

Using the GitHub Hash

GitHub Actions sets default environment variables that you can access within your workflow. Among these is GITHUB_SHA, which is the commit hash that triggered the workflow. This is a valuable versioning approach because you can trace each image back to its corresponding commit. In general, this convention uses the hash's first seven digits. Here's how we can access the variable and extract these digits:

YAML
 
- name: Build and tag image
  run: |
    COMMIT_SHA=$(echo $GITHUB_SHA | cut -c1-7)
    docker build -t ${{ github.repository }}:$COMMIT_SHA -f path/to/Dockerfile .


Semantic Versioning

When using version numbers, it is best practice to follow the SemVer spec. This way, you can increment your version numbers following a consistent structure when releasing new updates and patches. Assuming you store your app’s version in a root file version.txt, you can extract the version number from this file and tag the image in two separate actions:

YAML
 
- name: Get version
  run: |
    export VERSION=$(cat version.txt)
    echo "Version: $VERSION"

- name: Build and tag image
  run: docker build -t ${{ github.repository }}:$VERSION -f path/to/Dockerfile .


Pushing a Docker Image to a Container Registry

You can easily build, tag, and push your Docker image to your private container registry of choice within only two or three actions. Here’s a high-level overview of what you’ll be doing:

  1.  Manually set your authentication token or access credential(s) as repository secrets.
  2.  Use the echo command to pipe credentials to standard input for registry authentication. This way, no action is required on the user’s part.
  3. Populate the workflow with your custom build command. Remember to follow your registry’s tagging convention.
  4. Add the push command. You can find the proper syntax in your registry's docs.

You may prefer to split each item into its own action for better traceability on a workflow failure. 

Pushing to GHCR

Step 1: Setting up GHCR Credentials

In order to access the GitHub API, you’ll want to generate a personal access token. You can do this by going to Settings → Developer → New personal access token (classic) from where you’ll generate a custom token to allow package access. Make sure to select write:packages in the Select scopes section.

New personal access token

Store this token as a repository secret called GHCR_TOKEN.

Step 2: Action Recipe To Push to GHCR

You can add the following actions to your GitHub Actions workflow. This code will log into GHCR, build, and push your Docker image. 

YAML
 
- name: Log in to ghcr.io
  run: echo "${{ secrets.GHCR_TOKEN }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin

- name: Build and tag image
  run: |
    COMMIT_SHA=$(echo $GITHUB_SHA | cut -c1-7)
    docker build -t ghcr.io/${{ github.repository_owner }}/${{ github.repository }}:$COMMIT_SHA -f path/to/Dockerfile .

- name: Push image to GHCR
  run: docker push ghcr.io/${{ github.repository_owner }}/${{ github.repository }}:$COMMIT_SHA


Pushing to Docker Hub

Step 1: Store Your Docker Hub Credentials

Using your Docker Hub login credentials, set the following repository secrets: 

  1. DOCKERHUB_USERNAME
  2. DOCKERHUB_PASSWORD

Note: You'll need to set up a repo on Docker Hub before you can push your image.

Step 2: Action Recipe To Push to Docker Hub

Adding these actions to your workflow will automate logging in to Docker Hub, building and tagging an image, and pushing it.

YAML
 
- name: Log in to Docker Hub
  run: |
    echo ${{ secrets.DOCKERHUB_PASSWORD }} | docker login -u ${{ secrets.DOCKERHUB_USERNAME }} --password-stdin

- name: Build and tag image
  run: |
    COMMIT_SHA=$(echo $GITHUB_SHA | cut -c1-7)
    docker build -t ${{ secrets.DOCKERHUB_USERNAME }}/${{ github.repository }}:$COMMIT_SHA -f path/to/Dockerfile .

- name: Push image to Docker Hub
  run: docker push ${{ secrets.DOCKERHUB_USERNAME }}/${{ github.repository }}:$COMMIT_SHA


Pushing to Harbor

Step 1: Store Your Harbor Access Credentials

Create two new repository secrets to store the following info:

  1. HARBOR_CREDENTIALS: Your Harbor username and password formatted as username:password
  2. HARBOR_REGISTRY_URL: The URL corresponding to your personal Harbor registry

Note: You'll need to create a Harbor project before you can push an image to Harbor.

Step 2: Action Recipe To Push to Harbor

The actions below will authenticate into Harbor, build and tag an image using Harbor-specific conventions, and push the image. 

YAML
 
- name: Log in to Harbor
  run: |
    echo ${{ secrets.HARBOR_CREDENTIALS }} | base64 --decode | docker login -u $(cut -d ':' -f1 <<< "${{ secrets.HARBOR_CREDENTIALS }}") --password-stdin ${{ secrets.HARBOR_REGISTRY_URL }}

- name: Build and tag image
  run: |
    COMMIT_SHA=$(echo $GITHUB_SHA | cut -c1-7)
    docker build -t ${{ secrets.HARBOR_REGISTRY_URL }}/project-name/${{ github.repository }}:$COMMIT_SHA -f path/to/Dockerfile .

- name: Push image to Harbor
  run: docker push ${{ secrets.HARBOR_REGISTRY_URL }}/project-name/${{ github.repository }}:$COMMIT_SHA


Thanks for Reading!

I hope you enjoyed today's featured recipes. I'm looking forward to sharing more easy ways you can automate repetitive tasks and chores with GitHub Actions.

Best practice GitHub Docker (software) push workflow

Published at DZone with permission of Natalie Lunbeck. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Build Node.js App Docker Image and Push to Docker Private Repo With GitHub Actions
  • [CSF] Enable Continuous Delivery of Your Resume With GitHub Actions
  • Effective Microservices CI/CD With GitHub Actions and Ballerina
  • Deploy MuleSoft App to CloudHub2 Using GitHub Actions CI/CD Pipeline

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: