Automatically Deploy website from Github

Posted in Notes on 01 November 2019

This walk through will allow you to set-up a website to automatically deploy on a remote server whenever updates are pushed to the GitHub repository.

You will need root access to your remote server in order to proceed so it may not work on shared hosting platforms.

Server Side

You will first need to make sure Git is installed on the server. In terminal navigate to your web root folder and use the command git --version. As long as you have a relatively recent version available you should be able to continue.

Create SSH keys for the web user

You will need to know your webserver’s username, it’ll be assigned to any existing files in the web root directory. In this example the web user and group is is www-data, as on a standard Ubuntu LAMP set-up. First, create the directory:

sudo mkdir /var/www/.ssh/

Then set permissions on it for the web user:

sudo chown -R www-data:www-data /var/www/.ssh/

Next generate a deploy key:

sudo -Ha www-data ssh-keygen -t rsa

Follow the instructions, accept the default file name and don’t set a passphrase. As this is an automatic deployment we don’t want it to stop and wait for a password on deploy.

Once complete, print the key to terminal:

sudo cat /var/www/.ssh/id_rsa.pub

Add your Github Repository to the web directoy

Set-up your root directory with the repository you’re going to automatically deploy to as usual. When pushing/pulling you should check that these can be performed by the web user.

Most web servers will not let you log in as the web user however you can use the sudo command to preform them from your root account.

sudo -u www-data git pull

sudo -u www-data git push

If these commands work, the deploy.php script will be able to use them too.

Set-up the Github repository

Add the Public Key

Log into Github and go into User > Settings > SSH and GPL Keys. Click on the New SSH Key button. Enter the website name in the title field and paste the .pub key from terminal into the Key field.

Set-up the deploy hook

Click into the repo you want to deploy and into Settings > Webooks. Click on The Add webhook button.

Enter “https://yourwebsite.com/deploy.php” into the Payload URL input

Select “application/x-www-form-urlencode” from the Content type drop-down

You can choose to trigger the webhook on just the push event, on everything, or you can select which individual events you’d like to deploy on.

Make sure the “Active” option is checked. You can disable the hook by unchecking this if required.

Click Add webhook.

The Deploy Script itself

The final step is to upload the deploy.php script to the root of the web directory on the server to initialise the webhook. The following script has been forked from a script by Jakob Voß.

Once uploaded run a test deployment and if all goes well your changes should appear.