1. 更新系统并安装必要工具
# 更新系统
sudo yum update -y
# 安装EPEL仓库(如果需要更新版本的Git)
sudo yum install epel-release -y
2. 安装Git
# 安装Git
sudo yum install git -y
# 验证安装
git --version
3. 创建Git用户和目录
# 创建git系统用户
sudo useradd -r -m -s /bin/bash git
# 切换到git用户
sudo su - git
# 创建Git仓库目录
mkdir ~/repositories
4. 配置SSH访问(推荐方式)
# 为git用户生成SSH密钥(如果需要)
mkdir ~/.ssh
chmod 700 ~/.ssh
# 导入开发者的公钥到authorized_keys
# 将开发者的公钥添加到 ~/.ssh/authorized_keys
# 每行一个公钥
# 设置权限
chmod 600 ~/.ssh/authorized_keys
5. 初始化仓库
# 切换到仓库目录
cd ~/repositories
# 创建裸仓库(示例)
git init --bare myproject.git
# 设置权限
sudo chown -R git:git myproject.git
6. 客户端访问示例
从客户端机器:
# 克隆仓库
git clone git@your-server-ip:repositories/myproject.git
# 或者使用绝对路径
git clone git@your-server-ip:/home/git/repositories/myproject.git
7. 安装GitWeb(Web界面 - 可选)
# 安装GitWeb
sudo yum install gitweb httpd -y
# 配置GitWeb
sudo vi /etc/gitweb.conf
添加以下内容:
$projectroot = "/home/git/repositories";
$git_temp = "/tmp";
启动Apache:
sudo systemctl start httpd
sudo systemctl enable httpd
8. 安装GitLab(更完整的企业方案 - 可选)
如果需要更完整的功能(issue跟踪、CI/CD等):
# 安装必要的依赖
sudo yum install -y curl policycoreutils-python openssh-server
# 安装Postfix(用于邮件通知)
sudo yum install postfix
sudo systemctl enable postfix
sudo systemctl start postfix
# 添加GitLab仓库
curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
# 安装GitLab CE
sudo EXTERNAL_URL="http://your-server-ip" yum install -y gitlab-ce
# 配置并启动
sudo gitlab-ctl reconfigure
9. 防火墙配置(如果需要)
# 开放SSH端口
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
10. 基本Git服务器管理脚本
创建一个简单的管理脚本 /usr/local/bin/git-create:
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 repository-name"
exit 1
fi
REPO_PATH="/home/git/repositories/$1.git"
sudo -u git git init --bare "$REPO_PATH"
echo "Repository created at: $REPO_PATH"
echo "Clone with: git clone git@$(hostname):repositories/$1.git"
设置权限:
sudo chmod +x /usr/local/bin/git-create
注意事项:
安全性:
- 使用SSH密钥认证而非密码
- 定期更新系统和Git
- 限制git用户的shell访问
性能优化:
- 大型仓库可启用Git缓存
- 考虑使用Git LFS处理大文件
备份策略:
# 简单备份脚本
sudo tar czf /backup/git-repos-$(date +%Y%m%d).tar.gz /home/git/repositories/
这样的Git服务器配置适合小型团队使用。对于大型团队或企业级需求,建议考虑GitLab、Gitea或Gogs等更完善的解决方案。