Author: Xiao Fu Ge
Blog: https://bugstack.cn
Original: https://mp.weixin.qq.com/s/VtTHUfyiITNSoGy052jkXQ
Precipitate, share, and grow, so that you and others can gain something! 😄
https://www.bilibili.com/video/BV11S4y1d7hS/?aid=721628967&cid=440147596&page=1
I. Introduction
Brother Xiaofu, I have set up three servers to maintain the school game club site, I am numb!
📧 female fan letter : Brother Fu, my sophomore year, the kind of sophomore girl who can learn programming 😄. Recently, didn't I see a lot of people promoting server white leather jackets every day? I bought them on 11.1, and asked two students in the dormitory to buy them together. They both bought them for three years. Thinking of this, the three of us can build and maintain our school’s game club site, daily maintenance of the school’s game competitions, publicity, and notifications, and can also use the programming skills I learned by the way. Originally, I thought that I could show up in time for EDG VS DK, but the domain name has to be filed for many days. And with the three of us staying up all night tossing servers, doing site websites, and filing domain names, we really encountered too many problems. I used to feel that we could take off after learning the textbooks, but now we are all hips. I can only learn Fu Ge's cloud server operation video once and deploy verification once, and I have learned a lot! Thanks again to Brother Fu! So now the problem is coming, that is, Brother Fu, your B station video only has 6 sections, I followed after watching it, but this time I encountered a new problem, that is, my three servers have configured the Nginx load according to the video. From now on, I have to upload website files to three servers via FTP every time, and sometimes I forget one. What's going on, Brother Fu thinks of a way.
📨 Fu Ge replied to : There is a way, you can set your website code to a private warehouse and upload it to Github or Gitee. Both code bases support webhook. Simply put, when you push the code to the code base, the code base One or more callback hooks that you have configured in advance will be called. In fact, it is to call the URL provided by your three load-balanced sites to notify you that the code base has the latest updated code. You can call it when you receive the URL. After the notification, use the git pull
command to pull the newly uploaded website code to the server. The current effect is that after you maintain the code on GitHub and upload the latest website content, the three sites can be automatically deployed. The brief process is as follows:
program process :
- In your own website, provide the webhooks URL access address, and configure it to Settings -> Webhooks
Github/Gitee
code library, which will be described in detail below - For example, the content developed by webhooks.php in the figure is that when the call is received, the git pull operation is started after obtaining the
shell_exec("git pull origin main 2>&1");
- After the webhooks configuration is completed, when we push the local code to the warehouse (Github/Gitee) through git push, the warehouse will call all webhooks.php to pull the code in the warehouse (Github/Gitee) to the site , This completes the update of the entire site content.
🤔 Brother Fu, I understand what you said, but I need you to do it again!
2. Environmental description
- [Required] Use Github , Gitee , Codechina maintain the website code, because these code libraries can support the configuration of webhooks
- [Required] Linux cloud server (public IP); install Git, install Nginx, install PHP, install FTP
- [Optional] Use the pagoda operation and maintenance panel to deploy site blogs, which will be more convenient to operate
Three, site configuration
First of all, , we use the Linux pagoda operation and maintenance panel to add a blog site. Before adding, you need to install the Nginx, FTP, and PHP modules in the pagoda. If you are unfamiliar with the operations here, you can first see Xiao Fu at station B The recorded cloud server learning video, address: https://space.bilibili.com/15637440/channel/seriesdetail?sid=479958 PS: Of course, you can also install Nginx or Apache server through commands without using the pagoda. The required software is also possible.
1. Environmental installation
Install Git
- Requirements: When the site receives the webhooks callback, use git pull to pull the website code, so you need to install git
- Command:
yum -y install git
- verify:
[root@CodeGuide ~]# git version
git version 2.27.0
Install Nginx, FTP
- Requirements: When deploying a blog site, you will need to upload to the Nginx server and FTP
- Operation: You can use the
software store to install directly in the pagoda
Configure PHP, allowing exec script commands
- Requirements: Since we are using the webhook callback operation developed by PHP, the PHP module needs to be installed here
- Installation: Install directly in the software store of the pagoda
Configuration: After installing the PHP module, you need to
php.ini
of PHP, delete exec and shell_exec under disable_functions, so that you can execute script commands in the webhooks.php file. As shown in the figure:
2. Site configuration
- After the environment is installed, you can add a website site. Your website running code needs to be uploaded to this site. It provides FTP operation and there is a
file in the pagoda operation and maintenance panel. You can modify the site content online.
3. Visit the site
- Address: http://39.96.73.167 -you can change to your own access IP
- Description: After the site is created by default, there will be
/www/wwwroot/39.96.73.167
directory. At this point, you can modify online
Fourth, create a public key
SSH is a login tool for Linux systems, and is now widely used for server login and various encrypted communications.
1. View running users
Generally, php is run by the www
. We can upload an index.php to the root directory of the site via ftp, and then visit the site to view the project path and user directory.
index.php is as follows
<?php
header('Content-type: text/html; charset=utf-8');
ini_set("error_reporting", "E_ALL & ~E_NOTICE");
echo "Hi,Webhooks!By 小傅哥<br/>";
echo '<br/>测试:输出项目路径和用户目录:<br/>';
exec("cd ~ && cd - && cd -", $output);
echo '<pre>';
echo print_r($output);
echo '</pre>';
- If you haven't
php.ini
indisable_functions = {exec、shell_exec}
, then the script command in this php file will report an error.
Visit site
- Project path:
[0] => /www/wwwroot/39.96.73.167
- User directory:
[1] => /home/www
- www is this user directory, which is the user
2. Generate and configure the public key
2.1 Open www user
- Command:
vim /etc/passwd
Configuration:
sbin/nologin
tobin/bash
2.2 Generate public key
Because we have started the www login permission, before generating the public key, we need to switch to the www account, command: su www
- Switch user:
su www
- Generate public key:
ssh-keygen -t rsa -C "184172133@qq.com"
-press Enter by default View the public key:
cat ~/.ssh/id_rsa.pub
-not visible under other accounts, only visible by switching to www
2.3 Configure public key (Github)
- Address: https://github.com/settings/ssh/new
Configuration: Configure
cat ~/.ssh/id_rsa.pub
here, as follows:- With this public key configuration, we can automatically pull the code through the script instructions in webhooks.php.
Five, webhooks update blog
1. Clone my code
- Source code: Follow the public account: bugstack wormhole stack -Reply:
guide-webhooks
- Usage: You can fork my source code to your Github first, and then deploy it to your site. After learning and figuring out the principles, deal with your own site
2. Deploy to the site
- Here we need to use
git clone "your website code git address" on the site first to clone the Github code into our blog, which is actually to start the deployment. And this step is actually the way to use Git on a daily basis, clone the code first, and constantly git pull updates.
- Command:
[www@CodeGuide 39.96.73.167]$ git clone git@github.com:fuzhengwei/guide-webhooks.git
-Note that you need to switch to your own code base address, otherwise webhooks will not take effect
3. Change the website running directory
- Because we have cloned our blog running code from Github on the blog site, we need to switch the running directory of the website to this folder, so that we can access our blog code normally.
4. Configure webhooks
webhooks.php
callback script
<?php
/**
* Git webhooks 自动部署脚本
* 地址:https://github.com/fuzhengwei/guide-webhooks/settings/hooks
*/
// 接收post参数
$requestBody = file_get_contents("php://input");
if (empty($requestBody)) {
exit('data null!');
}
// Content type = application/json
$content = json_decode($requestBody, true);
// 验证 Webhooks 配置的 Secret,也可以不验证
/*if (empty($content['password']) || $content['password'] != '123456') {
exit('password error');
}*/
// 项目存放物理路径,也就是站点的访问地址
$path = "/www/wwwroot/39.96.73.167/guide-webhooks/";
// 判断需要下拉的分支上是否有提交,我们这里的分支名称为 main
if ($content['ref'] == 'refs/heads/main') {
// 执行脚本 git pull,拉取分支最新代码
$res = shell_exec("cd {$path} && git pull origin main 2>&1"); // 当前为www用户
// 记录日志 ($content 返回的是一整个对象,可以按需获取里面的内容,写入日志)
$res_log = '------------------------->' . PHP_EOL;
$res_log .= '用户 ' . $content['pusher']['name'] . ' 于 ' . date('Y-m-d H:i:s') . ' 向项目【' . $content['repository']['name'] . '】分支【' . $content['ref'] . '】PUSH ' . $content['commits'][0]['message'] . PHP_EOL;
$res_log .= $res . PHP_EOL;
// 追加方式,写入日志文件
file_put_contents("git_webhook_log.txt", $res_log, FILE_APPEND);
}
echo 'done';
- Among the code files we cloned from Github, there is a file named
webhooks.php
, which is used to pull Github's corresponding blog code library script file when processing Github callbacks. Now http://39.96.73.167/webhooks.php can be configured to Github's webhooks, as shown in the figure:
- Configuration, URL, Content type, Secret, and trigger. Just confirm after the configuration is complete. In addition, you can configure webhooks for multiple server instances so that they can be deployed together when pushing the code to the Github repository.
Six, deployment verification
At present , visit the blog like this, as follows: Next we start to modify the blog file and submit, verify the automatic deployment update site
1. Add code in index.php
- You can modify any content in the index.php file, or add new content.
2. Push code to Github
- Push the newly modified content to the code base and wait for the Github webhooks callback script
3. Verify blog updates
- Address: http://39.96.73.167/
Effect:
- By visiting the blog address, you can already see our newly added content, and the update has been automatically deployed to the site! ✌🏻
4. View script execution log
In our webhooks.php, when the git pull script is executed, there is also a log record, which is convenient for knowing who is right to the website!
git_webhook_log.txt
- git_webhook_log.txt is a log file recorded in webhooks.php, you can expand other content that needs to be output by yourself.
5. View webhooks push log
- Every time webhooks are executed, there will be a corresponding record to tell you whether the code push is successfully callback. And in the log, you can also see the content of the JSON file that webhooks pushes to you, and you can get the information you need from it, such as who pushed it, which branch it pushed it on, what files it pushed, and so on.
- A piece of pushed JSON is also intercepted here, and the rest of the information can be checked by yourself in the push record.
Seven, summary
- In this chapter, we take you through the use of webhooks thoroughly, and let the friends who need this technology make their site deployment changes
smarter. Of course, keeping records by myself has also helped some juniors and younger sisters!
- So now if you have a server in your hand and don’t know how to use it, you can now toss it up, because Brother Fu has recorded the introductory video and written the operation article for you, then don’t wait, go! young people! Course link: https://space.bilibili.com/15637440/channel/seriesdetail?sid=479958
8. Series recommendation
- "Netty+JavaFx Actual Combat: Imitating Desktop WeChat Chat" code open source, cloud deployment, video explanation, just to give you a Star!
- Cloudreve self-built cloud disk practice, I said that no one can limit my capacity and speed!
- Build 4 in a day, Xiao Fu will teach you how to build a blog!
- Xiao Fu, a code farmer with a "side job"!
- reasonable, as long as you are a tossing programmer, you really don't need to spend money on training to find a job after graduation!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。