Skip to content

Cache Docker images #4

@abrichr

Description

@abrichr

e.g. docker-build-ec2.yml.j2:

name: Docker Build on EC2 and Publish to GHCR

on:
  push:
    branches:
      - {{ branch_name }}

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

      - name: SSH and Execute Build on EC2
        uses: appleboy/ssh-action@master
        with:
          command_timeout: "60m"
          host: {{ host }}
          username: {{ username }}
          {% raw %}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          {% endraw %}
          script: |
            # Define the image tag
            IMAGE_NAME="ghcr.io/{{ github_owner }}/{{ project_name }}:latest"

            # Check if the image exists on GHCR
            IMAGE_EXISTS=$(curl -s -o /dev/null -w "%{http_code}" https://ghcr.io/v2/{{ github_owner }}/{{ project_name }}/manifests/latest)
            if [ "$IMAGE_EXISTS" -eq 200 ]; then
                echo "Image $IMAGE_NAME already exists in GHCR. Pulling it."

                # Log in to GHCR using secrets passed as environment variables
                echo "${{ secrets.GHCR_PAT }}" | sudo docker login ghcr.io -u "${{ secrets.GHCR_USERNAME }}" --password-stdin

                # Pull the existing image from GHCR
                sudo docker pull $IMAGE_NAME
            else
                echo "Image $IMAGE_NAME does not exist. Proceeding with build and push."

                # Clean up any existing clone
                rm -rf {{ github_repo }} || true
                git clone https://github.com/{{ github_path }}
                cd {{ github_repo }}
                git checkout {{ branch_name }}
                git pull

                # Stop and remove any existing containers
                sudo docker stop {{ project_name }}-container || true
                sudo docker rm {{ project_name }}-container || true

                # Build the Docker image
                sudo nvidia-docker build -t $IMAGE_NAME .

                # Log in to GHCR using secrets passed as environment variables
                echo "${{ secrets.GHCR_PAT }}" | sudo docker login ghcr.io -u "${{ secrets.GHCR_USERNAME }}" --password-stdin

                # Push the Docker image to GHCR
                sudo docker push $IMAGE_NAME
            fi

            # Run the Docker container
            sudo docker stop {{ project_name }}-container || true
            sudo docker rm {{ project_name }}-container || true
            sudo docker run -d -p 7861:7861 --gpus all --name {{ project_name }}-container $IMAGE_NAME

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions