How to deploy code using GitHub to your server

You can save time and avoid mistakes when you automatically deploy code from GitHub to your own server. Automation in deployment gives you faster feedback and helps your team work together better. When you use tools like GitHub Actions, webhooks, and deployment scripts, you reduce human error and keep your process reliable. Even if you only know the basics of GitHub and server management, you can set up this workflow and see improvements right away.
Key Takeaways
- Automate your code deployment to save time and reduce errors. Use tools like GitHub Actions and webhooks for a smoother process.
- Set up essential tools and accounts, including a GitHub repository, cloud server, and deployment scripts. This foundation is crucial for successful automation.
- Keep your server secure by using SSH keys for passwordless access. This ensures only trusted systems can connect to your server.
- Test your deployment process on a staging server before going live. This helps catch issues early and protects your production environment.
- Utilize GitHub secrets to store sensitive information safely. This keeps your passwords and keys hidden from your workflow files.
Prerequisites for Automatic Deployment
Tools and Accounts Needed
Before you set up automatic deployment, you need to gather some essential tools and accounts. These will help you connect your code from GitHub to your server and make the process smooth.
- Online Remote Repository: You need a GitHub account with a repository that holds your project code.
- Local Git Repository: Set up a local git repository on your computer to manage your code changes.
- Cloud Server: Choose a cloud server provider like Amazon EC2 or Rackspace. This is where your site or app will run.
- Deployment Script: Write a deployment script, such as
deploy.php, to handle pulling the latest code from GitHub. - Git Installation on Server: Make sure git is installed and updated on your server.
- SSH Key Setup: Generate an SSH key on your server. This allows secure, passwordless communication with GitHub.
- Add SSH Key to GitHub: Add your server’s SSH public key to your GitHub account so your server can access the repository.
- Set Up Post-Receive Hook: Configure a post-receive hook in GitHub to trigger your deployment script.
Tip: Keep your SSH keys safe. Never share your private key with anyone.
Preparing Your Server
You must prepare your server to receive code updates from GitHub. This setup ensures that automatic deployment works every time you push new code.
- Clone your GitHub repository into a directory on your server. You can create separate directories for production and staging environments.
- Write bash scripts for deployment. Give these scripts execution permissions so they can fetch the latest code and run it.
- Subscribe to GitHub’s Webhook API. This lets your server listen for events and start the deployment process automatically.
Here is a simple command to clone your repository:
git clone git@github.com:yourusername/your-repo.git
When you finish these steps, your server will be ready for automatic deployment. You will save time and reduce errors every time you deploy new code.
Automatically Deploy Code with GitHub Actions
You can automatically deploy code to your server by using github actions. This tool helps you run scripts and move your code every time you push changes. You do not need to log in to your server or run commands by hand. The process becomes smooth and repeatable.
Creating a Workflow File
To automatically deploy code, you must create a workflow file in your repository. This file tells github actions what to do when you push new code. Place the file in the .github/workflows/ folder and name it something like main.yml.
Here is an example of a workflow file that triggers on every tag push and runs a deployment job:
name: Deploy on Tag on: push: tags: - '*' jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout Repository uses: actions/checkout@v3 - name: Deploy to Test Server env: REMOTE_PATH: [your remote path location] if: startsWith(github.ref, 'refs/tags/') && contains(github.ref, 'rc') run: | mkdir -p ~/.ssh echo "${{ secrets.TEST_SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa cd ~/.ssh chmod 600 id_rsa ssh -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa ${{ secrets.TEST_SSH_USERNAME }}@${{ secrets.TEST_SERVER }} 'echo "${{secrets.REPO_DEPLOY_KEY}}" > ~/.ssh/gh_key && chmod 600 ~/.ssh/gh_key && eval `ssh-agent -s` && ssh-add ~/.ssh/gh_key && cd ${{ env.REMOTE_PATH }} && git fetch --tags && git checkout ${{ github.ref }} && /usr/bin/docker compose run --rm backend php yii migrate --interactive=0 && /usr/bin/docker compose run --rm backend php yii cache/flush-all && rm -f ~/.ssh/gh_key'
This workflow checks out your code, connects to your server, and runs commands to update your project. You can change the steps to fit your needs.
When you create your workflow file, you might run into some common mistakes:
- The workflow does not trigger. Make sure the file is in
.github/workflows/main.yml. - YAML syntax errors. Use two spaces for each indentation level.
- Command not found. Check that all tools are installed on the github runner.
You can avoid these problems by double-checking your file location and syntax.
Setting Up Environments and Secrets
You must keep your server safe when you automatically deploy code. Never put passwords or private keys in your workflow file. Instead, use github secrets to store sensitive information.
Go to your repository settings and find the “Secrets” section. Add your SSH private key, server username, and any other secret values. In your workflow file, you can use these secrets with ${{ secrets.YOUR_SECRET_NAME }}. This keeps your data safe and hidden.
You can also set up different environments for testing and production. This lets you automatically deploy code to a test server first. If everything works, you can deploy to your live server. Using github actions, you can control where and when your code goes live.
By following these steps, you will automatically deploy code every time you push changes. You will save time, reduce errors, and make your deployment process strong and secure.
Automatic Deployment Using Webhooks
Webhooks give you a powerful way to automate your deployment process. When you set up a webhook, your server listens for events from GitHub and responds by updating your code automatically. This method works well if you want to control the deployment process from your own server.
Writing a Webhook Listener Script
To start, you need a script that listens for incoming webhook requests. You can use PHP, Node.js, or another language that can handle HTTP POST requests. The script will receive notifications from GitHub when you push changes to your repository.
Here is a typical setup process for a webhook listener:
- Clone your Git repositories into separate directories for production and staging.
- Create bash scripts for each environment. Give these scripts execution permissions so they can run automatically.
- Write code to handle webhook events. Many developers use the
github-webhook-handlerpackage in Node.js, but you can also use PHP or Python. - Set up the webhook URL in your GitHub repository settings. Choose which events will trigger the webhook, such as push or pull request events.
- Test and verify your setup. Use a process manager like PM2 to monitor your script and check logs for errors.
Below is a simple example of a PHP webhook listener script:
<?php
$secret = 'your_webhook_secret';
$payload = file_get_contents('php://input');
$signature = 'sha1=' . hash_hmac('sha1', $payload, $secret);
if (hash_equals($signature, $_SERVER['HTTP_X_HUB_SIGNATURE'])) {
// Run your deployment script
shell_exec('/path/to/deploy.sh');
http_response_code(200);
echo "Deployment triggered.";
} else {
http_response_code(403);
echo "Invalid signature.";
}
?>
Tip: Always test your webhook listener with sample payloads from GitHub. This helps you catch errors before they affect your live site.
Configuring GitHub Webhooks
After you create your listener script, you need to configure the webhook in your GitHub repository. This step connects your repository to your server and tells GitHub where to send notifications.
Follow these steps to configure your webhook:
- Write code to handle webhook events and make sure your server has a public URL that GitHub can reach.
- Use a package like
github-webhook-handlerif you want to simplify event handling. - Run your server so it listens for incoming webhook requests.
- Go to your repository settings on GitHub. Add a new webhook and enter the URL of your listener script.
- Select the events that should trigger the webhook, such as push events or pull requests.
Security is very important when you use webhooks. You want to make sure only GitHub can trigger deployments on your server. Here are some key security considerations:
| Security Consideration | Description |
|---|---|
| Use of a secret for verification | Add a secret to your webhook. This helps confirm that requests come from GitHub. |
| Webhook URLs accessibility | Keep your webhook URL private. Do not share it to prevent unauthorized access. |
| Use of HTTPS | Set up HTTPS to encrypt communication between GitHub and your server. |
Note: If you use a secret, update your listener script to check the signature of incoming requests. This adds an extra layer of protection.
When you finish these steps, your server will automatically deploy new code every time you push changes to your repository. This setup saves you time and reduces the risk of manual errors.
Secure Server Access and SSH Keys
Setting up secure access is a key part of any automated deployment. You want to make sure only trusted users and systems can connect to your server. Using SSH keys helps you achieve passwordless and secure connections.
Generating SSH Keys
You can generate SSH keys to allow your deployment process to connect safely to your server. Follow these steps to set up SSH keys for your deployment user:
- Generate a new SSH key pair on your local machine:
ssh-keygen -t ed25519 -f ~/.ssh/blog_deployer - Create a dedicated user on your server for deployment:
useradd blog-deployer - Lock the password for this user to prevent password logins:
passwd -l blog-deployer - Make a
.sshdirectory for the new user:mkdir -p /home/blog-deployer/.ssh - Add the public key to the
authorized_keysfile:nano /home/blog-deployer/.ssh/authorized_keys - Change ownership of the home directory:
chown -R blog-deployer:blog-deployer /home/blog-deployer
This process ensures that only your deployment system can connect and deploy project to server.
Setting Permissions
You must set the right permissions to keep your deployment secure. If you do not, attackers might gain access or steal data. Here are some best practices:
- Restrict SSH login for the deployment user. You can use a command like:
restrict,pty,no-agent-forwarding,no-port-forwarding,no-X11-forwarding,command="/usr/local/bin/rrsync -wo /var/www/blog" - Limit what the deployment user can do. Only allow actions needed for deployment.
- Store secrets and keys in a secure vault. Encrypt them at rest and in transit.
- Regularly audit and monitor access to your server.
- Rotate SSH keys and secrets often.
Tip: Always check permissions on your SSH keys and deployment scripts. Misconfigured permissions can lead to unauthorized access, data leaks, or attacks.
By following these steps, you protect your deployment pipeline and keep your server safe.
Test and Deploy Your Site
Running a Test Deployment
You should always test before you deploy your site to production. A test deployment helps you catch problems early and ensures your process works as expected. Follow these steps to run a test deployment from GitHub to your private server:
- Prepare your server. Use a clean Linux system, such as Ubuntu 22.04 or newer. Make sure it has at least 4GB RAM and 2 CPU cores. Check that your server can access the Internet.
- Clone your deployment repository from GitHub. Use the correct SSH key or HTTPS method for secure access.
- Choose your installation method. For a fast install, run:
./scripts/install-fast.shFor a custom install, prepare your configuration file and use the Helm install command.
- Trigger your deployment. Push a change to your repository or manually activate your workflow or webhook.
- Watch the logs on your server. Confirm that the deployment script runs and updates your files.
Tip: Always test on a staging server before you deploy your site to production. This keeps your live site safe.
Troubleshooting Common Issues
You may face some common problems during deployment. The table below lists frequent issues, their causes, and how to prevent them:
| Issue | Error Message | Cause | Preventive Measure |
|---|---|---|---|
| Duplicate key found in mapping | duplicate key found in mapping | YAML parser update | Use unique and descriptive naming in templates |
| Secret not found | Secret not found or variable is empty | Syntax error | Show correct context syntax in templates |
| Matrix strategy error | Matrix not expanded, tests skipped | Invalid matrix configuration | Include a working matrix example in templates |
| Context syntax error | Variable not interpolated, value is empty | Forgot to wrap with ${{ }} | Show all context patterns in templates |
| Template too complex | Contributor ignores template, issue incomplete | Contains 20+ fields | Keep skill templates concise (max 5-8 fields) |
| Missing required fields | Issue incomplete, missing key information | Markdown template lacks validation | Use YAML template with required: true |
| Workflow duplication | Wasted CI time, high maintenance overhead | Separate workflows for CI/CodeQL/dependency review | Provide integration options in templates |
If you see errors, check your YAML files for mistakes. Make sure all secrets and variables are set. Review your deployment logs for clues. Fixing small issues early will make your deployment process smooth and reliable.
You should test your deployment pipeline often and keep your deployment script secure. Try advanced tools like AWS Code Deploy, Heroku, Zeit Now, Netlify, Travis CI, CircleCI, AWS ECS, Docker Swarm, and Kubernetes. You can also use Bitrise and Firebase for mobile projects. Add notification systems to your github integration for better monitoring. These tools help you manage your git workflow and keep your cloud server updated. Automated checks, monitoring tools, and dashboards give you more control and safety.
