Deploying a website is usually a hard and unsafe task, something that might scare you each time you must face against it.

In this blog entry, I will show you that if you use the right tools, the deploy operation can be just a common task in your website development strategy.

The only required element you need here is an hosting with a SSH connection. It's quite difficult to find someone who gifts this kind of feature, so you must be prepared to pay a fee.

There are a lot of providers out there which offer this feature. Personally, I'm using Dreamhost since eight years and the service they offer, really rocks.

If you decide to go with Dreamhost, you could consider to use the DBDH60 promo code, to get a 60% discount on the hosting price for the first year.

Ok, now you have a hosting with SSH connection, you can go further with this tutorial.

To deploy our Grav powered website we will leverage Git, the most popular VCS application out there today, to the next level. The VCS acronym means Version Control System, which definition taken from Wikipedia is

In computer software engineering, revision control is any kind of practice that tracks and provides control over changes to source code.

Despite the deploying stuff, you should always use a VCS application to manage your code to track the changes you made and you should apply this best practice also when you develop alone.

If you already know how git works, you can safety skip the next paragraphs.

Git basics

Basically, Git is a distributed VCS application, this means a server is not required to track the changes. You only need to initialize a project and you can immediately start to track everything you made on your application.

While Git has a lot of features you will learn using it mostly when you will start to collaborate on existing projects, you will require few commands to track your changes, I will show next.

After you installed Git, just enter the root folder of your application and run the following command:

git init

This initializes your first Git project. Next you must add a file called .gitignore where are listed the folders or the files Git must ignore. It is very important to add and configure this file when you want to track a Grav website because there are some folders you must exclude from the tracking.

Grav already comes with a preset .gitignore file

Now you must add your files to Git just running this command:

git add .

which means "add all files to Git", then you must confirm the changes, committing them to Git:

git commit -m "add here a comment to describe the changes you made"

Now your changes are tracked by Git. Every time you made some other changes, you just repeat the add/commit process.

Git can run as a server to keep your changes in the cloud and let other developers join and collaborate to your project. Though you can create your own server, the best option here is to use an existing free web service, like Github, the most known and used Git remote service.

Github is perfect when you want to share your project with other developers, but, if you want to manage private projects, as a personal website or a customer website, you must pay a fee.

Let's assume you work alone or with a small team made of maximum 5 persons you can safety use Bitbucket, which is a web service that works exactly as Github, but gives you the chance to work for free with private repositories on your own or with 5 collaborators.

Now, you must choose one of those providers, then open a free account with the one you choose. Let's suppose Bitbucket is the winner for you.

SSH key generation

The very first thing to do is to set up the SSH connection required to transfer the code to Bitbucket. To Create the SSH key for your local computer, just run the following command:

ssh-keygen

and follow the instructions. When you are done you must add the generated public key to Bitbucket. Just click on the User profile on Bitbucket web site, click on Settings link, then click on the Deployment keys link. At last, click the Add button and paste the contents of the id_rsa.pub key, generated into your computer.

Now you need a repository where your project will live. From the Repositories menu, click the Create repository link to open the form to create a new repository. Here the repository name is the only required information. Provide a name then click the I have an existing project link and follow their instructions.

At the end, your project should be transferred to Bitbucket. Each time you want to transfer all the changes you made from your local computer to Bitbucket, you simply run the push command:

git push origin master

Perfect, now your project is hosted at Bitbucket and anyone you give the access will be able to download your project.

And here comes the trick to easily deploy your web site. In fact, now you are able to get the repository code in your web server just running this command:

git pull origin master

When you run that command, you are sure that everything you committed to the remote repository is quickly ported to your web server, but, before that, you must repeat again the SSH key generation process for your remote server.

Automate the deploying process

To add a service to automatically deploy the website, you require a service able to run the pull command for you. This task is quite easy to do, just add a new /deploy/deploy.php file in your project, then paste the following code inside it:

<?php

// Only POST data is allowed
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "This service is not available";
    die;
}

// SET YOUR TIMEZONE
date_default_timezone_set('Europe/Rome');

ignore_user_abort(true);
set_time_limit(0);

$repo          = '~/[REPOSITORY PATH]';
$branch        = 'master';
$output        = array();

// update github Repo
$output[] = date('Y-m-d, H:i:s', time()) . "\n";
$output[] = "GitHub Pull\n============================\n" . shell_exec('cd '.$repo.' && git pull origin '.$branch);

// redirect output to logs
file_put_contents(rtrim(getcwd(), '/').'/___github-log.txt', implode("\n", $output) . "\n----------------------------\n", FILE_APPEND);

// Cleans cache, images and assets folders
rrmdir(__DIR__ . '/../cache', true);
rrmdir(__DIR__ . '/../images', true);
rrmdir(__DIR__ . '/../assets', true);

function rrmdir($dir, $keep) {
    if (!is_dir($dir)) {
        return;
    }

    $objects = scandir($dir);
    foreach ($objects as $object) {
        if ($object == "." || $object == "..") {
            continue;
        }

        $file = $dir . "/" . $object;
        if (filetype($file) == "dir") {
            rrmdir($file, false);
            continue;
        }

        unlink($file);
    }

    if ($keep) {
        return;
    }

    reset($objects);
    rmdir($dir);
}

Next arrange the $repo variable with your remote path and set your timezone.

Do not forget to add/commit/push this file to the remote server.

At last configure a new hook at Bitbucket. From the Webhooks page, always in the Settings panel, give a name to the hook, than provide the url that points the deploy file. For example, for this website the url is http://diblas.net/deploy/deploy.php.

Now, every time you push from your local computer to your remote report, automatically the site is updated with the changes you pushed.

Go beyond

This approach is very simple but also very effective even if it has some disadvantages you must consider.

  1. When you push to remote repository, changes are immediately reflected to the remote server and this behavior is not always a good thing, just because you might prefer to commit more than once before pulling the changes on the remote server.
  2. As long as you transfer pages this approach works fine, but when you start to change plugins, themes or assets, something might go wrong and break your production site. A stage environment, where you can test the web site on the remote server before go live, could help to be sure that everything works fine.
  3. If something goes wrong, you cannot go back to previous working website.

Luckily an awesome application can help you to cover all those aspects. Here is where Rocketeer comes into play.

Click here to read the article about this terrific application.

Next Post Previous Post

Related Posts