dockergithub-actionsgithub-actions-self-hosted-runners

How to self-create a docker image in GitHub Action then use it for steps?


Is it possible to omit using of Docker Hub and any docker image repo/registry to use a docker image in GitHub Actions?

I have a self-hosted runner Linux PC which is able to create my own docker image in any time. Is it possible to make a GitHub Action which in the first step create a docker image then in further steps everything is executed in this self-created docker image?

Of course, in the end of the full GitHub action/workflow self-created docker image should be removed and cleaned up everything.

In most of tutorial and blog site, there is only info about how can publish docker image to any registry via GitHub Action. I can not find any similar solutions. :(

Edit: Summary my goal is the following in a GitHub action of my SW project:


Solution

  • Yes this is certainly possible, you can run arbitrary code within a github action. However, I would advise you to instead publish your docker image on a repository and simply use it via container: docker://<url_of_your_image>

    That being said, if you need to follow the steps you outlined:

    I'll condense your last steps into a build-my-application as they will vary depending on how you build/deploy your app.

    git clone my dockerfile from a 3rd party git url

    Assuming the repo you are accessing is publicly available, or the git user running the action has access. If not you may need to replace the use of curl with a more complex git command.

    name: Build and Run Docker Image
    
    on:
      push:
        branches:
          - main
    
    jobs:
      build-and-run:
        runs-on: ubuntu-latest
        
        steps:
        - name: Download Dockerfile from external repository
          run: |
            curl -LJO https://raw.githubusercontent.com/external/repo/main/path/to/dockerfile
          working-directory: path/to/your/dockerfile/directory
    
        - name: Build Docker image
          run: |
            docker build -t my-docker-image .
         
        - name: Run Docker container
          run: |
            docker run -d --name my-container my-docker-image
        
        - name: Run arbitrary code inside the container
          run: |
            docker exec my-container ./build-my-application
       
    

    Note: If have more needs other than just building the container and running a script, or you need to anchor to a particular version of docker you should specify a container for the job itself to run in i.e. a container to build your container inside.

    e.g.

    jobs:
      build-and-run:
        runs-on: ubuntu-latest
        container:
          image: docker:20.10.9  # Specify the Docker version you need