Introduction
Manually deploying your website every time you make a change is inefficient and prone to errors. GitHub Actions provides a powerful way to automate the deployment process, ensuring that every commit to your repository triggers an update to your website on DigitalOcean. In this guide, we’ll walk through setting up GitHub Actions to automate the deployment of a static site or web application on DigitalOcean.
Prerequisites
Before we begin, ensure you have the following:
- A DigitalOcean account
- A Droplet with SSH access (or a Kubernetes cluster if you’re using DigitalOcean Kubernetes)
- A GitHub repository with your website’s code
- A domain name (optional but recommended)
Step 1: Setting Up SSH Access
To allow GitHub Actions to deploy your site to DigitalOcean, you need to set up SSH access between GitHub and your Droplet:
- Generate an SSH key on your local machine:
ssh-keygen -t rsa -b 4096 -C "your-email@example.com"
- Copy the contents of the public key (
~/.ssh/id_rsa.pub
) and add it to your DigitalOcean Droplet’s~/.ssh/authorized_keys
file:echo "your-public-key" >> ~/.ssh/authorized_keys
- Add the private key (
id_rsa
) as a GitHub Secret:- Go to your GitHub repository.
- Navigate to Settings > Secrets and variables > Actions.
- Click New repository secret.
- Name it
SSH_PRIVATE_KEY
and paste the private key contents.
Step 2: Writing a GitHub Actions Workflow
Create a GitHub Actions workflow file inside .github/workflows/deploy.yml
in your repository:
name: Deploy to DigitalOcean
on:
push:
branches:
- main # Change this if you use a different branch
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Set up SSH
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H your-server-ip >> ~/.ssh/known_hosts
- name: Deploy to Server
run: |
ssh user@your-server-ip "cd /var/www/html && git pull origin main && systemctl restart nginx"
Replace your-server-ip
and user
with the appropriate values for your DigitalOcean Droplet.
Step 3: Push Your Code and Test Deployment
Once everything is set up:
- Commit and push your code to GitHub:
git add . git commit -m "Set up GitHub Actions for deployment" git push origin main
- GitHub Actions will trigger the deployment automatically.
- Check the Actions tab in your repository to monitor the workflow.
- Visit your website to confirm the deployment.
Conclusion
With GitHub Actions, you can automate the deployment of your website to DigitalOcean efficiently, reducing manual effort and ensuring a smooth workflow. This setup can be extended further by integrating Docker, Kubernetes, or CI/CD tools for a more advanced pipeline.
Do you use GitHub Actions for your deployment?