1+ name : Build and Push Docker Image
2+
3+ on :
4+ workflow_dispatch :
5+ inputs :
6+ tag_version :
7+ description : ' Docker image tag version (e.g., 3.3.11)'
8+ required : true
9+
10+ env :
11+ DOCKER_IMAGE_NAME : elevate-user # Configure your image name here
12+ DOCKER_REGISTRY : docker.io
13+ DOCKER_NAMESPACE : shikshalokamqa
14+
15+ jobs :
16+ docker-image-build-and-push :
17+ if : github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/docker-image'
18+ runs-on : ubuntu-latest
19+
20+ steps :
21+ - name : Checkout code
22+ uses : actions/checkout@v4
23+
24+ - name : Set up Docker Buildx
25+ uses : docker/setup-buildx-action@v3
26+
27+ - name : Login to Docker Hub
28+ uses : docker/login-action@v3
29+ with :
30+ username : ${{ secrets.DOCKERHUB_USERNAME }}
31+ password : ${{ secrets.DOCKERHUB_TOKEN }}
32+
33+ - name : Get Docker tag version (fail if not provided)
34+ id : get-version
35+ run : |
36+ # Use workflow_dispatch input if provided
37+ if [ ! -z "${{ github.event.inputs.tag_version }}" ]; then
38+ VERSION="${{ github.event.inputs.tag_version }}"
39+ # Or use TAG_VERSION env if set (for push/PR)
40+ elif [ ! -z "${TAG_VERSION}" ]; then
41+ VERSION="${TAG_VERSION}"
42+ else
43+ echo "Error: Docker image version must be provided as workflow_dispatch input or TAG_VERSION env."
44+ exit 1
45+ fi
46+ echo "version=$VERSION" >> $GITHUB_OUTPUT
47+
48+ - name : Check if version exists on Docker Hub
49+ id : check-version
50+ run : |
51+ VERSION=${{ steps.get-version.outputs.version }}
52+ RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" "https://hub.docker.com/v2/namespaces/${{ env.DOCKER_NAMESPACE }}/repositories/${{ env.DOCKER_IMAGE_NAME }}/tags/$VERSION")
53+ if [ "$RESPONSE" -eq 200 ]; then
54+ echo "Error: Tag $VERSION already exists on Docker Hub"
55+ exit 1
56+ else
57+ echo "Tag $VERSION does not exist, proceeding with build"
58+ fi
59+
60+ - name : Extract metadata
61+ id : meta
62+ uses : docker/metadata-action@v5
63+ with :
64+ images : ${{ env.DOCKER_REGISTRY }}/${{ env.DOCKER_NAMESPACE }}/${{ env.DOCKER_IMAGE_NAME }}
65+ tags : |
66+ type=raw,value=${{ steps.get-version.outputs.version }}
67+
68+ - name : Build and push Docker image
69+ id : build
70+ uses : docker/build-push-action@v5
71+ with :
72+ context : .
73+ file : ./Dockerfile
74+ push : true
75+ tags : ${{ steps.meta.outputs.tags }}
76+ labels : ${{ steps.meta.outputs.labels }}
77+ platforms : linux/amd64,linux/arm64
78+ cache-from : type=gha
79+ cache-to : type=gha,mode=max
80+
81+ - name : Image digest
82+ run : echo "Image pushed with digest ${{ steps.build.outputs.digest }}"
83+
84+ - name : Print pushed tags
85+ run : |
86+ echo "Pushed tags:"
87+ echo "${{ steps.meta.outputs.tags }}" | tr ',' '\n'
0 commit comments