搭建git服务器,并且自动部署到web服务器上和同步到gittee和github上
一、首先在服务器上安装git
1 | yum -y install git |
二、添加git用户,并且限制登录权限
1、添加git用户,并且设置shell为/usr/bin/git-shell,目的是为了不让git用户远程登陆,并且在该用户的家目录下创建authorized_keys文件,并更改属主、属组和权限,用来存客户端机器上的公钥:
[root@localhost ~]# useradd -s /usr/bin/git-shell git [root@localhost ~]# cd /home/git/ [root@localhost /home/git]# mkdir .ssh/ [root@localhost /home/git]# touch .ssh/authorized_keys [root@localhost /home/git]# chmod 600 .ssh/authorized_keys [root@localhost /home/git]# chown -R git:git .ssh [root@localhost /home/git]# passwd git # 设置一下git用户的密码 更改用户 git 的密码 。 新的 密码: 重新输入新的 密码: passwd:所有的身份验证令牌已经成功更新。 [root@localhost /home/git]#
三、创建证书登录
1、在本地电脑上创建公钥
https://www.cnblogs.com/poloyy/p/12189140.html
2、收集所有需要登录的用户的公钥,就是他们自己的id_rsa.pub
文件,把所有公钥导入到/home/git/.ssh/authorized_keys
文件里,一行一个
四、初始化Git仓库
1、先选定一个目录作为Git仓库,假定是/home/git/sample.git
,在/home/git
目录下输入命令
1 | git init --bare sample.git |
2、分配中权限
1 | chown -R git:git sample.git |
五、禁用git用户shell登录
1、通过编辑/etc/passwd
文件完成,找到你的git用户的一行,例如
1 2 3 | git:x:1001:1001:,,,:/home/git:/bin/bash 把/bin/bash改为/usr/bin/git-shell,例如 git:x:1001:1001:,,,:/home/git:/usr/bin/git-shell |
这样,git用户可以正常通过ssh使用git,但无法登录shell,因为我们为git用户指定的git-shell每次一登录就自动退出。
六、克隆远程仓库
1 | git clone git@server:sample.git |
server是你的服务器域名或ip地址,如果clone成功,那么你的git服务器就搭建成功了。
七、自动同步到web服务目录下
1、因为我是web目录和git是同一台服务器,编辑 /home/git/sample.git/hooks/post-receive
, post-receive
就是在git服务器收到代码推送后(push
完成之后)执行的脚本。
#!/bin/sh while read oldrev newrev refname do branch=$(git rev-parse --symbolic --abbrev-ref $refname) if [ "master" == "$branch" ]; then # Do something echo "post-receive in branch master" >> /tmp/git-sample.log unset GIT_DIR wwwPath=/www/wwwroot/www.tea.com cd $wwwPath && /usr/bin/git pull origin master exit 0 fi done
从脚本内容可以看出,我们在判断当前push
的分支是master
时执行git pull origin master
操作。
2、给执行权限
chown -R git:git /home/git/sample.git/hooks/post-receive
chmod +x /home/git/sample.git/hooks/post-receive
3、把仓库clone到自己的web服务器下(因为是git仓库和web目录在同一台服务器主机上,这里clone使用的是)
git clone /home/git/sample.git /www/wwwroot/www.tea.com
2、因为同步脚本的执行用户是git,所以要保证项目目录要赋予git写权限。容易出问题的也是权限问题。
1 2 | chmod -R 777 /www/wwwroot/www.tea.com chown git:git /www/wwwroot/www.tea.com |
好了,试试吧~
八、把本地代码自动同步到github和gittee上
1、首先把自己的公钥id_ras.pub 分别加到github和gitte
详细教程如下:
https://blog.csdn.net/shi851051279/article/details/95892542
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)