选择服务器环境
推荐使用Linux系统(Ubuntu/CentOS),确保稳定的网络环境。
硬件要求:至少2GB内存,20GB存储空间(根据项目规模调整)。
安装必要依赖
执行命令更新系统并安装基础工具:
sudo apt-get update && sudo apt-get upgrade -y # Ubuntu/Debian sudo yum update -y && sudo yum install -y curl wget # CentOS
通过包管理器安装
Ubuntu/Debian:
sudo apt-get install git -y
CentOS:
sudo yum install git -y
验证安装结果
git --version # 输出示例:git version 2.34.1
新建系统用户
sudo adduser git # 按提示设置密码(可选禁用登录)
限制Shell访问
修改/etc/passwd
文件,将git用户的Shell替换为git-shell
:
sudo usermod -s /usr/bin/git-shell git
创建存储目录
sudo mkdir -p /opt/git/project.git sudo chown git:git /opt/git/project.git
初始化裸仓库
切换到git用户并初始化:
sudo -u git git init --bare /opt/git/project.git
客户端生成密钥对
在开发者电脑执行:
ssh-keygen -t ed25519 -C "your_email@example.com"
服务器端授权密钥
将客户端公钥(id_ed25519.pub
追加到服务器文件:
sudo su git mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys echo "公钥内容" >> ~/.ssh/authorized_keys
仓库访问控制
sudo chown -R git:developers /opt/git/project.git sudo chmod -R 770 /opt/git/project.git
gitolite
或gitlab
实现细粒度权限管理(适合大型团队)。钩子脚本(Hooks)
在/opt/git/project.git/hooks
目录添加脚本,实现自动部署:
# post-receive示例 #!/bin/sh git --work-tree=/var/www/html checkout -f
克隆仓库
git clone git@服务器IP:/opt/git/project.git
推送代码
git remote add origin git@服务器IP:/opt/git/project.git git push origin main
git log
检查提交记录。/opt/git
目录并压缩存储。top
或htop
观察服务器资源占用。sudo systemctl status sshd
)及防火墙设置。chmod +x post-receive
)。引用说明
本文参考Git官方文档、Linux用户管理指南及《Pro Git》技术手册编写。