在 Windows 上建立 Git 远程仓库可以通过以下步骤实现,这里提供两种主要方法:

方法一:使用纯 Git 创建裸仓库(推荐)

这是最轻量级的方式,适合个人或小团队使用。

  1. 安装 Git

    • 下载安装 Git for Windows
    • 安装时勾选所有默认选项,特别是 Git Bash
  2. 创建裸仓库

    # 打开 Git Bash
    cd /d/  # 进入 D 盘
    mkdir myrepo.git
    cd myrepo.git
    git init --bare
    
  3. 设置共享权限

    • 右键点击 myrepo.git 文件夹 → 属性 → 共享 → 高级共享
    • 勾选 “共享此文件夹”
    • 设置共享名(如 gitrepo
    • 权限 → 添加用户并赋予 “完全控制”
  4. 使用远程仓库

    # 在客户端电脑克隆仓库
    git clone //[计算机名]/gitrepo/myrepo.git
    
    # 或使用 IP 地址
    git clone //192.168.1.100/gitrepo/myrepo.git
    

方法二:使用 SSH 协议(更安全)

适合需要加密传输的场景

  1. 启用 OpenSSH 服务器

    # PowerShell 管理员模式
    Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
    Start-Service sshd
    Set-Service -Name sshd -StartupType Automatic
    
  2. 创建裸仓库

    mkdir C:\git\myproject.git
    cd C:\git\myproject.git
    git init --bare
    
  3. 配置 SSH 访问

    # 创建 .ssh 目录
    mkdir C:\Users\YourUsername\.ssh
    
    # 获取客户端公钥,保存到 authorized_keys
    notepad C:\Users\YourUsername\.ssh\authorized_keys
    
  4. 客户端连接

    git clone ssh://YourUsername@your-windows-ip/C:/git/myproject.git
    

方法三:使用第三方工具(功能更全)

适合需要 Web 界面和高级功能的团队

  1. 安装 Gitea (推荐)

    # 下载
    curl -L https://dl.gitea.com/gitea/1.22.0/gitea-1.22.0-windows-4.0-amd64.exe -o gitea.exe
    
    # 安装为服务
    .\gitea.exe web --install-service
    
  2. 访问 Web 界面

    • 浏览器打开 http://localhost:3000
    • 完成初始配置
    • 创建新仓库
  3. 客户端使用

    git clone http://your-windows-ip:3000/username/myrepo.git
    

常用管理命令

# 创建新仓库
git init --bare newrepo.git

# 添加远程
git remote add origin //server/gitrepo/myrepo.git

# 推送代码
git push -u origin main

# 修复权限问题
cd /d/myrepo.git
chmod -R 755 .

防火墙配置

# 开放文件共享端口
netsh advfirewall firewall add rule name="Git SMB" dir=in action=allow protocol=TCP localport=445

# 开放 SSH 端口
netsh advfirewall firewall add rule name="Git SSH" dir=in action=allow protocol=TCP localport=22

# 开放 HTTP 端口 (Gitea)
netsh advfirewall firewall add rule name="Gitea HTTP" dir=in action=allow protocol=TCP localport=3000

优化建议

  1. 固定 IP:为服务器设置静态 IP
  2. DDNS:使用花生壳等工具解决动态 IP 问题
  3. 备份:定期备份仓库目录
    # 简单备份脚本
    Compress-Archive -Path C:\git -DestinationPath D:\backups\git-$(Get-Date -Format yyyyMMdd).zip
    
  4. 权限管理
    # 创建专用用户组
    net localgroup GitUsers /add
    icacls "C:\git" /grant:r "GitUsers:(OI)(CI)F"
    

选择哪种方式取决于您的需求:

  • 快速共享:方法一(文件共享)
  • 安全传输:方法二(SSH)
  • 完整功能:方法三(Gitea)

对于大多数 Windows 用户,方法一(文件共享)是最简单直接的解决方案,无需额外配置即可在局域网内使用。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐