Tuesday, May 13, 2025

Setting Up a Linux Machine with Docker for GitHub Actions


This guide will help you set up a Linux machine with Docker, add it as a self-hosted runner in GitHub Actions, and configure it to spin up and delete containers for each job.

Step 1: Install Docker on Linux

  1. Update your package index:
    sudo apt-get update
  2. Install Docker dependencies:
    sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
  3. Add Docker’s official GPG key:
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
  4. Add Docker’s repository:
    sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
  5. Install Docker:
    sudo apt-get update
    sudo apt-get install docker-ce
  6. Verify Docker installation:
    sudo systemctl status docker

Step 2: Add the Linux Machine as a Self-Hosted Runner in GitHub Actions

  1. Create a new runner:
    • Go to your GitHub repository.
    • Navigate to Settings > Actions > Runners.
    • Click Add runner and follow the instructions to download and configure the runner application.
  2. Download the runner application:
    mkdir actions-runner && cd actions-runner
    curl -o actions-runner-linux-x64-2.283.3.tar.gz -L https://github.com/actions/runner/releases/download/v2.283.3/actions-runner-linux-x64-2.283.3.tar.gz
    tar xzf ./actions-runner-linux-x64-2.283.3.tar.gz
  3. Configure the runner:
    ./config.sh --url https://github.com/your-repo --token YOUR_TOKEN
  4. Install the runner as a service:            
    sudo ./svc.sh install
    sudo ./svc.sh start
           
  5.    

Step 3: Configure GitHub Actions to Use Docker Containers


#.github/workflows/docker-runner.yml
name: Docker Runner

on: [push]

jobs:
  build:
    runs-on: self-hosted
    container:
      image: ubuntu:latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Run a script
        run: echo "Hello, Docker!"

## cleanup job on separate file
       
jobs:
  build:
    runs-on: self-hosted
    container:
      image: ubuntu:latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Run a script
        run: echo "Hello, Docker!"
      - name: Cleanup
        run: docker system prune -f

This setup ensures that Docker containers are spun up for each job and cleaned up after the job completes.

No comments:

Post a Comment