linux 搭建 git 服务
git 服务在服务器,项目目录也在服务器
假设当前服务器IP地址: 1.2.3.4
git 仓库,提供 git 服务在服务器上的路径: /home/www/food.git
项目目录,存放项目文件,也就是除开 .git 目录的其它文件, 其在服务器上的路径: /www/wwwgit/food
确定一个使用 git 服务器的用户,并赋于密码,比如 git
[root@localhost ~]# useradd git
[root@localhost ~]# passwd git
创建仓库, 把 Git 仓库的 owner 修改为 git
[root@localhost ~]# mkdir -p /home/www/food.git
[root@localhost ~]# git init --bare /home/www/food.git # 新建一个裸仓库
[root@localhost ~]# chown git:git /home/www/food.git # 冒号前面的git表示用户 冒号后面的表示组
裸仓库就是不让该目录有工作区,只保存历史提交的版本信息,真正的有工作区应该是项目目录
本地克隆仓库,克隆 git 仓库并非项目目录
$ git clone git@1.2.3.4:/home/www/food.git
可能会提示输入密码,该密码为服务器上 git 用户的密码
下面演示一次完整的推拉操作
本地客户端
$ git clone git@1.2.3.4:/home/www/food.git
$ cd food
$ echo 'init' >> README.md
$ git add .
$ git commit -m 'init'
$ git push
服务器端
[root@localhost ~]# mkdir -p /www/wwwgit # 创建一个所有项目的根目录
[root@localhost ~]# chown git:git /www/wwwgit # 该目录所属 git 用户
[root@localhost ~]# cd /www/wwwgit
[root@localhost wwwgit]# git clone /home/www/food.git # 服务器端克隆该服务的 git 服务的仓库
[root@localhost wwwgit]# git pull # 需要拉取时
同步更新
服务不需要每次拉取只需要本地 push 就 ok
[root@localhost ~]# vim /home/www/food.git/hooks/post-receive
#!/bin/sh
unset GIT_DIR
projectPath=/www/wwwgit/food # 服务器上该仓库对应的项目路径
cd $projectPath
git add . -A && git stash
git pull origin master
# 最后 esc -> shift + : -> wq 保存并退出
~
~
~
[root@localhost ~]# chown git:git /home/www/food.git/hooks/post-receive # 更改所属
[root@localhost ~]# chmod +x /home/www/food.git/hooks/post-receive # 添加可执行的权限
现在只需要在本地 push 然后服务器上的项目目录下面就不再 pull 了
ssh 验证
在服务器上为用户 git 生成 .ssh 目录:
[root@localhost ~]# cd /home/git
[root@localhost git]# mkdir .ssh
[root@localhost git]# chown -R git:git .ssh/
[root@localhost git]# chmod 700 .ssh
[root@localhost .ssh]# cd .ssh
[root@localhost .ssh]# touch authorized_keys # 存放不同公钥的文件
[root@localhost .ssh]# chown -R git:git authorized_keys
[root@localhost .ssh]# chmod 600 authorized_keys
.ssh 目录及 authorized_keys 一定要是 git 所属,否则 ssh 验证不会生效
本地生成唯一的 ssh key:
$ ssh-keygen
$ cat ~/.ssh/id_rsa.pub
只需要将本地的 id_rsa.pub 文件的内容追加到服务器上的 authorized_keys 后即可