This GitHub Actions workflow automates the process of building a Docker image and deploying it to an EC2 instance. It consists of two main jobs: build-docker
and run-on-ec2
.
name: OneHealth CI/CD
on:
push:
branches: ["main"]
pull_request:
branches: ["main"]
jobs:
build-docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.USERNAME }}
password: ${{ secrets.PASSWORD }}
- name: Build the Docker image
run: docker build -t <docker-repository> .
- name: Push the Docker image
run: docker push <docker-repository>
run-on-ec2:
needs: build-docker
runs-on: ubuntu-latest
env:
EC2_SSH_PRIVATE_KEY: ${{ secrets.SSH_SECRET }}
EC2_URL: ${{ secrets.SSH_HOST }}
EC2_USERNAME: ${{ secrets.SSH_USERNAME }}
steps:
- name: Setup SSH for EC2
uses: omarhosny206/[email protected]
with:
EC2_SSH_PRIVATE_KEY: $EC2_SSH_PRIVATE_KEY
EC2_URL: $EC2_URL
- name: run the docker container on EC2
run: |
ssh -o StrictHostKeyChecking=no $EC2_USERNAME@$EC2_URL "
sudo docker pull <docker-repository>
sudo docker stop atom || true
sudo docker rm atom || true
sudo docker run --name atom -d -p 80:5000 <docker-repository>
"
-
The
build-docker
job:- Checks out the code
- Sets up Docker
- Logs into Docker Hub
- Builds the Docker image
- Pushes the image to Docker Hub
-
The
run-on-ec2
job:- Connects to an EC2 instance
- Pulls the newly built image
- Stops and removes any existing container
- Runs the new image in a container
To use this workflow, you need to add the following secrets to your GitHub repository:
DOCKER_USERNAME
: Your Docker Hub usernameDOCKER_PASSWORD
: Your Docker Hub password or access tokenSSH_SECRET
: The private SSH key for your EC2 instanceSSH_HOST
: The public DNS or IP address of your EC2 instanceSSH_USERNAME
: The username to log into your EC2 instance
To add these secrets:
- Go to your GitHub repository
- Click on 'Settings' > 'Secrets and variables' > 'Actions'
- Click 'New repository secret' for each secret you need to add
Remember to replace <docker-repo-name>
with your actual Docker repository name in the workflow file.
Ensure that your EC2 instance has Docker installed and that the user specified by SSH_USERNAME
has the necessary permissions to run Docker commands.