Push to GitHub Container Registry using GitHub Actions
In this article
Last month, GitHub launched GitHub Container Registry, a rework of the existing Docker support offered within GitHub Packages.
Container Registry allows hosting of Docker images within an organization or personal user account, unlike Packages which only allows hosting at the repository level.
Note: GitHub Container Registry is currently in public beta and subject to change.
This post demonstrates how to set up a GitHub Actions Workflow to push an image to the registry, automatically. Here's what we'll be doing.
- Create a Personal Access Token and add it as a secret
- Create a
Dockerfile
(or use an existing one) - Add
.github/workflows/deploy.yml
workflow file - Trigger the workflow by creating a tag
Personal Access Token#
GitHub Container Registry does not currently support the default GITHUB_TOKEN
(provided to Actions automatically) for authentication. Because of this, it is necessary to create a Personal Access Token with the correct scopes and add it as a repository secret.
The token requires the repo and write:packages scopes. Clicking the button below will fill in the necessary scopes.
Once the token is created, copy it and navigate to your repository Settings > Secrets. Create a secret called GITHUB_REGISTRY_TOKEN
and insert the token as the value.
Create Dockerfile#
The contents of the Dockerfile don't matter for this tutorial, so we'll use this basic one as an example.
FROM alpine
CMD ["echo", "Hello World!"]
Create Workflow#
And now, we're ready to create the workflow file. Workflows are discovered in the .github/workflows
directory, so create a deploy.yml
file in there.
name: Deploy Docker
# Run workflow on tags starting with v (eg. v2, v1.2.0)
on:
push:
tags:
- v*
jobs:
Deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v1
- name: Login to GitHub Container Registry
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_REGISTRY_TOKEN }}
- name: Build and Push Docker Image
uses: docker/build-push-action@v2
with:
push: true # Will only build if this is not here
tags: |
ghcr.io/${{ github.repository }}:${{ github.ref }}
ghcr.io/${{ github.repository }}:latest
Trigger Workflow#
The workflow above uses the docker/login-action
to authenticate with the registry, and the docker/build-push-action
to build the image and push it to the registry. You can trigger it by creating a Git tag that matches the version format (eg. v1.0
).
Once run, you'll see the image appear under the repository owner's profile within the Packages tab. Here is my profile, for example. From here, you can manage versions, link it to a repository, or change the visibility from private to public. Remember, if the image is private, you'll need to authenticate with the GitHub Container Registry wherever you intend to pull the image as well.