Hugh's Blog

Linux 搭建 Git 服务器

搭建 Git 服务器很简单,做个记录。

首先添加 git 用户并配置:

sudo adduser git
su git
cd
mkdir .ssh && chmod 700 .ssh
touch .ssh/authorized_keys && chmod 600 .ssh/authorized_keys
# 添加公钥到 authorized_keys,以便登录
# cat id_rsa.your.pub >> ~/.ssh/authorized_keys

添加项目仓库:

cd /srv/git
mkdir project.git
cd project.git
git init --bare
# Initialized empty Git repository in /srv/git/project.git/

服务器方面已经配置完成,接下来是客户端:

cd myproject
git init
git add .
git commit -m 'initial commit'
git remote add origin git@gitserver:/srv/git/project.git
# 如果是额外的 SSH 端口,使用如下地址
# git remote add origin ssh://git@{ip_address}:{port:1234}/srv/git/project.git
git push origin master

为了安全,只让 git 用户执行 git 相关的操作,禁止其他 shell 命令,其中 git-shell 是 Git 提供的 shell 环境:

# 查看是否已经加载 `git-shell`
cat /etc/shells
# 如果没有加载的话,查找路径并添加到系统 shells
which git-shell
sudo vim /etc/shells
# 设置 `git` 用户 shell 环境
sudo chsh git -s $(which git-shell)

设置了之后,如果 git 用户尝试登录的话,会提示如下错误:

ssh git@gitserver
fatal: Interactive git shell is not enabled.
hint: ~/git-shell-commands should exist and have read and execute access.
Connection to gitserver closed.

参考

Git on the Server - Setting Up the Server