Easy Deployment of PHP Applications with Deployer with php

View: 574    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Php&mySql   Fields: Other

19 point/3 review File has been tested

Deployer is packaged as a PHAR file that we can download to our local machine. We can also move it to the user’s bin directory to make it global. Check the documentation for more details.

Introduction

Deployer is packaged as a PHAR file that we can download to our local machine. We can also move it to the user’s bin directory to make it global. Check the documentation for more details.

mv deployer.phar /usr/local/bin/dep
chmod +x /usr/local/bin/dep

Defining Servers

After cloning the demo repository, we need to create a new file called deploy.php where we’ll define our deployment steps.

The first step is to define our deployment servers. We can authenticate normally using a username and a password.

// deploy.php

server('digitalocean', '104.131.27.106')
    ->user($_ENV['staging_server_user'])
    ->password($_ENV['staging_server_password']);

We can also define the type of this server (stagingproduction, etc), which allows us to run tasks (more on tasks later) on a specific server stage.

// deploy.php

set('default_stage', 'staging');

server('digitalocean', '104.131.27.106')
    ->user($_ENV['staging_server_user'])
    ->password($_ENV['staging_server_password'])
    ->stage('staging')
    ->env('deploy_path', '/var/www');

We need to add the default_stage attribute when using the stage method. Otherwise, we’ll get the You need to specify at least one server or stage. error.

SSH Authentication

It’s a common practice to use SSH authentication on the production servers. If you’re not familiar with using SSH keys for authentication, check out this guide for a detailed walkthrough.

// deploy.php

set('default_stage', 'staging');

server('digitalocean', '104.131.27.106')
    ->identityFile()
    ->user($_ENV['staging_server_user'])
    ->password($_ENV['staging_server_password'])
    ->stage('staging');

By default, the identityFile method uses the current user id_rsa identity file. We can change that if this is not the case.

// deploy.php

// ...
    ->identityFile('path/to/id_rsa', 'path/to/id_rsa.pub', 'pass phrase')
// ...

Install SSH2 Extension

Deployer also supports using the PHP SSH2 extension. After installing the extension and enabling it, we need to require the herzult/php-ssh package which provides an OOP wrapper for the PHP extension, and sets the ssh_type config option to ext-ssh2.

// deploy.php

set('ssh_type', 'ext-ssh2');
// ...

The only problem here is that Deployer doesn’t have the php-ssh package shipped with the PHAR archive. We’ll need to clone the Deployer repository, require the package, and finally use the buildscript to generate a new PHAR archive.

Using Configuration Files

We can also define our servers using a YAML configuration file, and pass the file to the serverListmethod. You can read more about servers in the documentation.

// servers.yml

digitalocean:
  host: 104.131.27.106
  user: root
  identity_file: ~
  stage: staging
  deploy_path: /var/www/

We can now load the file inside our deploy.php file.

serverList('servers.yml');

Defining Tasks

Tasks are commands that can be run through the dep command.

dep deploy:staging

The deploy:staging argument should be a task inside our deploy.php file. We can upload files, run commands on the server, etc.

// deploy.php

task('deploy:staging', function() {
    writeln('<info>Deploying...</info>');
    $appFiles = [
        'app',
        'bootstrap',
        'public',
        'composer.json',
        'composer.lock',
        'artisan',
        '.env',
    ];
    $deployPath = env('deploy_path');

    foreach ($appFiles as $file)
    {
        upload($file, "{$deployPath}/{$file}");
    }

    cd($deployPath);
    run("composer update --no-dev --prefer-dist --optimize-autoloader");

    run("chown -R www-data:www-data app/storage");
    set('writable_dirs', ['app/storage']);

    writeln('<info>Deployment is done.</info>');
});

The file looks overwhelming at first, but there’s nothing special here. First, we print a message using thewriteln method to notify the user that the deployment process has started. Next, we define the application folders that need to be uploaded.

The upload method will send our local application files to the server inside the for loop. Check the documentation for the list of available functions.
We cd to the server directory and update our Composer dependencies using the run method, which lets us run any shell command on the server.

The next and final step is to make the necessary directories writable by the server user, in this case www-data for Apache. The writable_dirs parameter tells the deployer about our writable directories. We can achieve the same thing using a shell command, too.

dep deploy:staging

task("deploy:staging", function () {
    // ... 
})->desc('Deploy application to staging.');

The desc method will add a help message to our task (command).

Our current file has one big task to handle the whole deployment process. We’ll split it into small reusable tasks and run them successively in the deploy:staging task.

task('deploy:started', function() {
    writeln('<info>Deploying...</info>');
});

task('deploy:done', function() {
    writeln('<info>Deployment is done.</info>');
});

The above tasks are just to notify the user of the deployment state. Deployer provides after and beforemethods (hooks) to run tasks when other tasks are fired.

before('deploy:staging', 'deploy:started');
after('deploy:staging', 'deploy:done');
task('deploy:upload', function() {
    $appFiles = [
        'app',
        'bootstrap',
        'public',
        'composer.json',
        'composer.lock',
        'artisan',
        '.env',
    ];
    $deployPath = env('deploy_path');

    foreach ($appFiles as $file)
    {
        upload($file, "{$deployPath}/{$file}");
    }
});

task('deploy:writable_dirs', function() {
    $deployPath = env('deploy_path');
    cd($deployPath);

    run("chown -R www-data:www-data app/storage");
    set('writable_dirs', ['app/storage']);
});

task('deploy:composer', function() {
    $deployPath = env('deploy_path');
    cd($deployPath);

    run("composer update --no-dev --prefer-dist --optimize-autoloader");
});

The only part that’s left is to run all the tasks in the deploy:staging task.

task('deploy:staging', [
    'deploy:upload', 
    'deploy:writable_dirs',
    'deploy:composer',
]);

Because we split our tasks into meaningful parts, we can re-use them later for another production server, and even for other projects!

Zero Downtime Deployment

Currently, our Apache server root is pointing to the /var/www/public directory. When we’re deploying a new version of our application, we need to put the server in maintenance mode for a few minutes to avoid any downtime for users.

A simple solution for this problem is to create a list of releases, and point our server’s root to a currentdirectory, which will link to the latest release.

/current (link pointing to the current release)
/releases
    /realease_1
    /realease_2
    /realease_3

Common Deployment Tasks

Deployer has a list of common tasks used by most PHP apps, something like we did earlier. We’ll re-factor our deploy.php to re-use those common tasks where possible.

// deploy.php

require_once "recipe/common.php";

set('ssh_type', 'ext-ssh2');
set('default_stage', 'staging');
env('deploy_path', '/var/www');
set('copy_dirs', [
    'app/commands',
    'app/config',
    'app/controllers',
    'app/database',
    'app/lang',
    'app/models',
    'app/src',
    'app/start',
    'app/tests',
    'app/views',
    'app/filters.php',
    'app/routes.php',
    'bootstrap',
    'public',
    'composer.json',
    'composer.lock',
    'artisan',
    '.env',
]);
set('shared_dirs', [
    'app/storage/cache',
    'app/storage/logs',
    'app/storage/meta',
    'app/storage/sessions',
    'app/storage/views',
]);
set('writable_dirs', get('shared_dirs'));
set('http_user', 'www-data');

First we set the some variables that we’ll be using inside our tasks. shared_dirswritable_dirs andhttp_user are used by the common tasks we’re going to use next.

task('deploy:upload', function() {
    $files = get('copy_dirs');
    $releasePath = env('release_path');

    foreach ($files as $file)
    {
        upload($file, "{$releasePath}/{$file}");
    }
});

We kept the deploy:upload task in this case, but you can also use the deploy:update_code task to pull your application from Git remote host. Don’t forget to set the necessary attributes when using it.

set('repository', 'http://github.com/whyounes/500pxAPI_Test.git');
env('branch', 'master');
// deploy.php

task('deploy:staging', [
    'deploy:prepare',
    'deploy:release',
    'deploy:upload',
    'deploy:shared',
    'deploy:writable',
    'deploy:symlink',
    'deploy:vendors',
    'current',
])->desc('Deploy application to staging.');

after('deploy:staging', 'success');

deploy:prepare: Test the connection, shared folder, releases folder, etc.

deploy:release: Create the release directory.

deploy:upload: Our task for uploading files.

deploy:shared: Create shared folders if they do not exist. Uses the shared_dirs attributes we set earlier.

deploy:writable: Set writable directories.

deploy:symlink: Create a symbolic link from the release to current.

deploy:vendors: Run Composer installation.

current: Print the current release name.

success: Print a success message.

Deploy 2

Deploy dirs

Deployment Recipes

Because most of us are using frameworks for our projects. Deployer has some pre-configured recipes for well-known frameworks like Laravel, Symfony, Yii, Zend, etc. Check the recipes section in the documentation for more details.

Conclusion

Deployer has a really nice API to make the deployment process easy and configurable. If you’ve never used a deployment tool to automate your deployment process, I really encourage you to try it!

Easy Deployment of PHP Applications with Deployer with php

Easy Deployment of PHP Applications with Deployer with php Posted on 13-05-2016  Deployer is packaged as a PHAR file that we can download to our local machine. We can also move it to the user’s bin directory to make it global. Check the documentation for more details. 6.3333333333333/10 574

Comment:

To comment you must be logged in members.

Files with category

  • How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    View: 4071    Download: 0   Comment: 0   Author: none  

    How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    Category: Php&mySql
    Fields: Other

    1.6666666666667/3 review
    With the explosion of machine learning services in recent years, it has become easier than ever for developers to create “smart apps”. In this article, I’ll introduce you to Microsoft’s offering for providing machine-learning capabilities to apps.

  • How to MySqli Tutorial PHP MySqli Extension

    View: 395    Download: 0   Comment: 0   Author: none  

    How to MySqli Tutorial PHP MySqli Extension

    Category: Php&mySql
    Fields: Other

    0/0 review
    PHP provides three api to connect mysql Database.

  • Make Laravel Artisan Commands

    View: 377    Download: 0   Comment: 0   Author: none  

    Make Laravel Artisan Commands

    Category: Php&mySql
    Fields: Other

    0/0 review
    Artisan is the command line tool used in Laravel framework. It offers a bunch of useful command that can help you develop application quickly. Apart from Artisan available commands, you can create your own custom commands to improve your workflow.

  • Check if a Number is a Power of 2

    View: 343    Download: 0   Comment: 0   Author: none  

    Check if a Number is a Power of 2

    Category: Php&mySql
    Fields: Other

    1.5/3 review
    How to check if a number is a power of 2. To understand this question, let’s take some example.

  • Concatenate columns in MySql

    View: 403    Download: 0   Comment: 0   Author: none  

    Concatenate columns in MySql

    Category: Php&mySql
    Fields: Other

    0/2 review
    Artisan is the command line tool used in Laravel framework. It offers a bunch of useful command that can help you develop application quickly. Apart from Artisan available commands, you can create your own custom commands to improve your workflow

  • How to Query NULL Value in MySql

    View: 336    Download: 0   Comment: 0   Author: none  

    How to Query NULL Value in MySql

    Category: Php&mySql
    Fields: Other

    5/1 review
    Misunderstanding NULL is common mistake beginners do while writing MySql query. While quering in MySql they compare column name with NULL. In MySql NULL is nothing or in simple word it isUnknown Value so if you use comparison operator for NULL values...

  • How to Abstract Class in PHP

    View: 374    Download: 0   Comment: 0   Author: none  

    How to Abstract Class in PHP

    Category: Php&mySql
    Fields: Other

    0/0 review
    What is an abstract class in PHP and when to use an abstract class in your application. In this tutorial, we’ll learn about abstract class and their implementation.

  • Use Enums in Rails for Mapped Values

    View: 337    Download: 0   Comment: 0   Author: none  

    Use Enums in Rails for Mapped Values

    Category: Php&mySql
    Fields: Other

    2.5/2 review
    When I worked in a call center, we used to mark cases with different statuses. This allowed upper management to get a handle on where cases stood, what the bottlenecks were and flow of calls. Thankfully it has been a long time since I worked in a...

 

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd