Learning Notes #67 β Build and Push to a Registry (Docker Hub) with GH-Actions
GitHub Actions is a powerful tool for automating workflows directly in your repository.In this blog, weβll explore how to efficiently set up GitHub Actions to handle Docker workflows with environments, secrets, and protection rules.
Why Use GitHub Actions for Docker?
My Code base is in Github and i want to tryout gh-actions to build and push images to docker hub seamlessly.
Setting Up GitHub Environments
GitHub Environments let you define settings specific to deployment stages. Hereβs how to configure them:
1. Create an Environment
Go to your GitHub repository and navigate to Settings > Environments. Click New environment, name it (e.g., production
), and save.
2. Add Secrets and Variables
Inside the environment settings, click Add secret to store sensitive information like DOCKER_USERNAME
and DOCKER_TOKEN
.
Use Variables for non-sensitive configuration, such as the Docker image name.
3. Optional: Set Protection Rules
Enforce rules like requiring manual approval before deployments. Restrict deployments to specific branches (e.g., main
).
Sample Workflow for Building and Pushing Docker Images
Below is a GitHub Actions workflow for automating the build and push of a Docker image based on a minimal Flask app.
Workflow: .github/workflows/docker-build-push.yml
name: Build and Push Docker Image on: push: branches: - main # Trigger workflow on pushes to the `main` branch jobs: build-and-push: runs-on: ubuntu-latest environment: production # Specify the environment to use steps: # Checkout the repository - name: Checkout code uses: actions/checkout@v3 # Log in to Docker Hub using environment secrets - name: Log in to Docker Hub uses: docker/login-action@v2 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_TOKEN }} # Build the Docker image using an environment variable - name: Build Docker image env: DOCKER_IMAGE_NAME: ${{ vars.DOCKER_IMAGE_NAME }} run: | docker build -t ${{ secrets.DOCKER_USERNAME }}/$DOCKER_IMAGE_NAME:${{ github.run_id }} . # Push the Docker image to Docker Hub - name: Push Docker image env: DOCKER_IMAGE_NAME: ${{ vars.DOCKER_IMAGE_NAME }} run: | docker push ${{ secrets.DOCKER_USERNAME }}/$DOCKER_IMAGE_NAME:${{ github.run_id }}
To Actions on live: https://github.com/syedjaferk/gh_action_docker_build_push_fastapi_app/actions