温馨提示×

ubuntu中gitlab如何搭建私有仓库

小樊
49
2025-10-31 21:26:56
栏目: 智能运维

Ubuntu环境下搭建GitLab私有仓库完整步骤

1. 准备工作

  • 系统要求:Ubuntu 20.04及以上版本(推荐),确保系统已更新(sudo apt update && sudo apt upgrade -y)。
  • 依赖包:安装GitLab运行必需的组件(包括SSH服务、证书工具、数据库等):
    sudo apt install -y curl openssh-server ca-certificates postfix
    
    安装Postfix时选择“Internet Site”,并设置系统域名(如example.com,若为内网可随意填写)。

2. 添加GitLab官方仓库

  • 导入GPG密钥(验证软件包完整性):
    curl https://packages.gitlab.com/gpg.key | sudo apt-key add -
    
  • 添加APT源(以Ubuntu 22.04为例,其他版本替换jammy为对应代号):
    echo "deb https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu jammy main" | sudo tee /etc/apt/sources.list.d/gitlab-ce.list
    
  • 更新软件包列表
    sudo apt update
    

3. 安装GitLab Community Edition(CE,社区免费版)

  • 安装GitLab
    sudo apt install -y gitlab-ce
    
  • 配置外部访问URL(修改/etc/gitlab/gitlab.rb,将your_server_ip替换为服务器实际IP或域名):
    sudo vim /etc/gitlab/gitlab.rb
    
    找到external_url行,取消注释并修改为:
    external_url 'http://your_server_ip'
    
    若需使用域名,可将your_server_ip替换为域名(如example.com)。

4. 启动GitLab服务

  • 重新配置并启动
    sudo gitlab-ctl reconfigure  # 应用配置变更(耗时约1-2分钟)
    sudo gitlab-ctl start       # 启动GitLab服务
    
  • 设置开机自启(可选但推荐):
    sudo systemctl enable gitlab-runsvdir.service
    

5. 访问GitLab Web界面

  • 获取初始管理员密码(安装后自动生成,有效期24小时):
    sudo cat /etc/gitlab/initial_root_password
    
  • 登录Web界面
    打开浏览器,访问http://your_server_ip,使用默认管理员账号root和上述密码登录。
  • 修改初始密码(登录后立即操作):
    进入root用户设置→Password,设置新密码(需包含大小写字母、数字和特殊字符)。

6. 创建私有仓库

  • 创建用户(可选但推荐,便于权限管理):
    点击右上角头像→Admin AreaUsersNew User,填写用户名、邮箱、密码等信息,点击Create user
  • 创建项目(私有仓库)
    登录后点击右上角New project,输入项目名称(如my-private-repo),选择Visibility LevelPrivate(仅项目成员可访问),点击Create project

7. 配置本地Git客户端

  • 生成SSH密钥(若未生成):
    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
    
    按提示回车,默认保存到~/.ssh/id_rsa(私钥)和~/.ssh/id_rsa.pub(公钥)。
  • 添加公钥到GitLab
    复制公钥内容(cat ~/.ssh/id_rsa.pub),登录GitLab→Profile SettingsSSH Keys,粘贴公钥并点击Add key
  • 克隆私有仓库
    在本地终端执行:
    git clone git@your_server_ip:root/my-private-repo.git
    
    输入GitLab账号密码(或SSH密钥密码)即可克隆。

8. 可选优化(增强安全性与可用性)

  • 配置SSL证书(启用HTTPS)
    使用Let’s Encrypt免费获取证书(需域名):
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d your_domain.com
    
    按提示完成配置,GitLab会自动使用HTTPS访问。
  • 配置防火墙
    若启用ufw(Ubuntu防火墙),允许HTTP(80)、HTTPS(443)和SSH(22)端口:
    sudo ufw allow 80/tcp
    sudo ufw allow 443/tcp
    sudo ufw allow 22/tcp
    sudo ufw enable
    

通过以上步骤,即可在Ubuntu服务器上搭建GitLab私有仓库,实现团队代码的私有化托管与协作。

0