In last article, we saw that how to push custom image on Docker hub using docker cli, In this article we are going to see how we can automat this using GitHub Actions. Please keep this article link handy as we will be referring it for few key infomration.
First, we need an application source code which we have already dockerized, in this case we will take a simple example, Here is the link of the Git Repo. In this project, we have just two file which have been used. One is 'index.html' and another is 'Dockerfile'. Assumtion is that we already know how to build and run it locally.
Now, We will keep our docker account details : username and access token handy (Explained in same article).
We will go to our github repository, Settings > Secrets > Actions and click on 'New repository secret'.
It will open a new window, where we have to add key and value for our docker account access token (in our case, we name it, DOCKERHUB_TOKEN). We also addeed docker hub user name (DOCKERHUB_USERNAME) as secret.
Now let's add our first GitHub Action at root of our project like below :
In this script we are trigeering the build if any changes are pushed to master branch for all paths. We are using an build agent in this case it is ubunt 22.04
Ther very first step is actions/checkout@v2 action, which take the latest code from the master branch.
Second step is docker/setup-qemu-action which installs QEMU static binaries, which are used to run builders for architectures other than the host.
Third step is docker/setup-buildx-action configures buildx, which is a Docker CLI plugin that provides enhanced build capabilities.
Fourth step is login (docker/login-action@v2) in to docker account, it is using username and token configured in the repository's action secret section. Then next step is building and pushing it to docker hub.
Fifth step, if you will see, we are tagging (docker/build-push-action@v3) the image with 2 tags, one is the latest, so every image will pushed as latest and also as a Variable which is the Github Run Number, which is the number of build (GitHub Action)run for that repo. This way every build will create, it's own tag too and we can pull that particulat image from the dokcer hub.
Now on any code push to master branch it will trigger a build, and we haven't added any filter or condition. On pushing this script to master branch it will trigger a new build. In below screen shot, the yellow dot shows on GitHub repository if any build has been triggered.
The below screenshot is showing that how tags get update in any build.
Below is the screenshot from a successfull run.
After, sucessfull push, we can see that it pushed 2 tag, one is latest and another is 5, which we can see that it was the build number.
This was a pretty straight forward example to create a GitHub Action to build and push image to Dokcer Hub. Hope this was helpful and thanks for reading.
Top comments (0)