Teenager, it's time to deploy your PHP code in a more elegant way.

Source: Internet
Author: User
Tags symlink codeigniter yii zend zend framework least privilege

Let's recall how you posted your code last time:

1. First back up the code on the line with FTP

2. Upload the modified file

3. Test if the function is normal

4. Website 500, hurriedly replace back with a backup

5. Replace the wrong/replace the leak

6. A server was published successfully

7. Log in each one to perform the publish operation once

8. Overtime Work done

9. The boss is mad

...

Especially now the Internet industry, pay attention to rapid iteration, small steps to run. Changes like bug fixes or minor features are issued almost every day, and the large-feature version iterations are almost once a week. I believe a lot of colleagues like I said above to publish their own code it. Or perhaps a little bit more advanced, go directly to the server and execute a git pull command that drags down the code in the repository, but what if your code is running in a cluster? Do you run git pull once per machine login? What if there is a problem with the code that needs to be rolled back?

If you're still deploying your code in this way as I said, then I hope you'll be patient with this article and get rid of the pain of code deployment.

Actually, it's a circle around. Today, I would like to introduce you to the Code publishing tool written in PHP: Deployer.

The deployer has the following attractive features:

-Fast adoption of technologies such as concurrent publishing, SSH channel multiplexing, cache availability and caching to accelerate code deployment

-Atomic deployment performs all defined operations within the newly released version, such as download dependencies, setting file access permissions, and so on, without directly affecting the line, and only after all success, the last step of setting the soft chain will actually replace the code on the line

-Fast rollback because of the atomic deployment, rollback is just a reset of the soft-link point

-Concurrent deployment of the same deployment process on all machines in a clustered environment

-Consistent cluster environment, only successful execution of all machines, one failure

-built-in multiple framework publishing templates such as Laravel, Yii, Symfony, CodeIgniter, Zend framework, etc.

-Easy to expand it's easy to write a publishing process with common templates based on your project

Installation:

global require deployer/deployer

After the installation is complete, switch to your project directory, perform DEP init, and select the resulting deployment template according to the framework used by your project:

?TbDepInitPleaseSelectYourProjectType (DefaultsToCommon):[0]Common[1]Laravel[2 symfony [< Span class= "Hljs-number" >3] Yii [4" zend framework  [5] CakePHP [6 codeigniter [7" drupal > 0    

If your framework does not use any of the frameworks listed above, select 0 and then enter to generate a generic publishing template.

Doing this should generate a deploy.php file in your project's root directory, all you need to do is edit the script, fill in some of your own server and project configurations, and then customize some tasks.

Below I will use a specific configuration file to describe the usage of deployer, the configuration file is as follows:

<?phpNamespaceDeployer;UseSymfony\Component\Console\Input\Inputoption;Require' recipe/common.php '; option (' Tag ',NULL, Inputoption::value_optional,' posted tag ');Global configuration File Set (' Ssh_type ',' native ');There are three ways to log in to a remote host: Phpseclib (default), native, Ext-ssh2set (' Ssh_multiplexing ',true);Whether to turn on SSH channel multiplexing (turn on reduce server and local load and increase speed) set (' Keep_releases ',10);Error 10 previous version, set to 1 indicates that the historical version set is always saved (' Repository ',' [email protected]:loc/loc-api.git ');The address of the Code warehouse, which only supports Gitset (' Branch ',' Master ');The branch set that is used by default when publishing code (' Shared_files ', []);List of shared files The files listed here will be moved to the shared directory in the project root directory, and the soft chain set (' Shared_dirs ', []);Shared Directories Ibid. set (' Writable_mode ',' chmod ');Which method of controlling writable permissions, in 4: Chown, CHGRP, chmod, ACL (default) set (' Writable_chmod_mode ',' 0755 ');When using chmod to control writable permissions, the writable permission value set (' Writable_dirs ', []);A writable directory specifies that those directories are sets that need to be written by the Web server (' Clear_path ', []);Set the directory set that needs to be deleted when the code is published (' Http_user ',' Nginx ');Web server users, generally do not set, Deployer will automatically determine the set (' Release_name ',function (){Set the name of the release, where tag is the preferred name, the word will use Date + time to indicate the release timeif (input ()->hasoption (' Tag ') {return input ()->getoption (' tag '); }Return Date (' Ymd-h:i ');});Multiple servers can be set up and posted to multiple servers synchronously according to SettingsParameters can be set individually for each server, and parameters that are set override the Global parameter server (' Prod_1 ',' xxx.xxx.xxx.xxx ')->user (' Root ')->password (' xxxxx ')->set (' Deploy_path ','/VAR/WWW/TB ')Code deployment Directory, note: Your webserver, such as Nginx, set the root directory should be/var/www/tb/current,Because current is a soft-chain->stage that points to the actual version that is currently used on the line (' prod ');Identifies the server type that is used for Server grouping server (' Prod_2 ',' xxx.xxx.xxx.xxx ')->user (' Root ')->password (' xxxxx ')->set (' Deploy_path ','/VAR/WWW/TB ')->set (' Branch ',' Master ')Specifies the branch that is destined for this server, overwriting the global setting's branch parameter->set (' Extra_stuff ',‘...‘)Optionally specify what other parameters->stage (' prod '); Server' Beta ',' xxx.xxx.xxx.xxx ')->user (' Root ')->password (' xxxxx ')->set (' Deploy_path ','/var/www/test ')->set (' Branch ',' Beta ')The test environment uses the Beta branch->stage (' Beta ');Put in the Beta groupThe Configured Tasks task (' Success ',function (){Deployer::setdefault (' Terminate_message ',' <info> released successfully!</info> ');}) ->once ()->setprivate ();Increase the once call then this task will be executed locally, not the remote server, and only once DESC is executed (' Restart php-fpm ');You can add a description to the task, and you'll see this description task when you perform the DEP list (' Php-fpm:restart ',function (){Run (' Systemctl restart Php-fpm.service ');The run function defines the operation performed on the server, usually a shell command, which can have a return value and return a command print});Smart as you must have found, you can use the run function to make some batch Management Server tasks, such as bulk reload all nginx configuration files, batch execution server scripts and so on after (' Deploy:symlink ',' Php-fpm:restart ');A hook function that performs a php-fpm restart task after the set up of a soft chain task desc (' Publish project '); task (' Deploy ', [You can set up a composite task, and the second parameter is all the subtasks that the composite task includes, which will be executed sequentially' Deploy:prepare ',Prepare before publishing, check if some required directories exist, do not exist and will automatically create' Deploy:lock ',Generate lock files to avoid two release processes on a single server at the same time, resulting in state confusion' Deploy:release ',Create a Code store directory' Deploy:update_code ',Update the code, usually git, you can also rewrite the task, using the upload method, upload using SFTP' Deploy:shared ',//processing shared files or directories  ' deploy:writable ', / /Set Directory writable permissions  ' deploy:vendors ', //based on composer configuration, install dependent  ' deploy:clear_paths ', //perform the delete operation according to the Clear_path parameter set  ' Deploy:symlink ', //set the symbol to connect to the latest updated code, which is the code for this release at this time  ' Deploy:unlock ', //delete lock file for next release //according to keep_releases parameters, clear older version, free server disk space  ' success ' Span class= "Hljs-comment" >//perform a successful task, as defined above, generally used to prompt]); After ( ' deploy:failed ',  ' Deploy:unlock '); //if the publication fails, delete the lock file so that the next retry           

The above is a more complete automated deployment script configuration, is it easy to feel? Because most of the configuration work has been done for you when you perform DEP init!

One more thing to do next is to add the Ssh-key of the server you want to deploy into your Git account's authentication library, and you can create an account that only has git pull and git clone permissions in the repository, keeping the principle of least privilege. It is important to note that after the key is added, the first Git clone on the server may require you to enter Yes, so the surest way is to go to each server to be deployed to execute Git clone, drag the warehouse code to another directory.

After doing the above, all the preparatory work is done. The next step is to deploy the test.

First check that the configuration has no problem:

config:dump beta    // 打印beta环境的配置dep config:dump prod    // 打印生产环境的配置

If there is no problem with the printed configuration, then perform the release task:

// 发布当前beta分支到beta环境dep --tag=v1.1 deploy prod // 发布v1.1这个tag的代码到生产环境,可以增加-p选项,并发发往所有服务器

A successful deployment should have output similar to the following:

? TB git: (master)? Dep--tag=v1. 1 deploy prod_1? Executing task deploy:prepare? Executing task deploy:lock? Executing task deploy:release? Executing task Deploy:update_code? Executing task deploy:shared? Executing task deploy:writable? Executing task deploy:vendors? Executing task deploy:clear_paths? Executing task deploy:symlink? Executing task Php-fpm:restart? Executing task deploy:unlock? Executing task cleanup? Executing task success released successfully! 

See which version of the current production environment is used

dep current prod  //这里应该会输出v1.1 

To see which version of the current production environment is used:

dep current prod  //这里应该会输出v1.1 

If there is a problem after publishing to the line and you need to roll back, just do it:

dep rollback prod   // 实际上只是修改软链指向,所以很快就能执行完成且基本不可能失败

Again with DEP current PROD should be able to see the rollback to the previous version

Again, such as the previous execution of the problem, was interrupted, re-execution may prompt: Deploy locked, then only use execution:

deploy:unlock prod // 删除锁文件

If the disk space on the line is tight (not usually), you can delete the earlier version by executing the following command:

dep cleanup

Here's about deployer all you should have mastered.  Although the first configuration does take some time, it may be half an hour or half a day. But in return is the next more elegant, fast, safe, easy rollback of the release process, so think about it is still a little excited?

If you have any problems with the installation, you can add the group: 632109190 for discussion. The students who are interested in PHP, Java, and OPS can add in, and I'll wait for you:)

Teenager, it's time to deploy your PHP code in a more elegant way.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.