将本地项目上传到 GitLab/GitHub

以下是将本地项目上传到 GitLab 的完整步骤,从创建仓库到推送代码的详细流程:


1. 在 GitLab 上创建新项目

  1. 登录 GitLab,点击 New project
  2. 选择 Create blank project
  3. 填写项目信息:
    • Project name : 项目名称(如 my-project)。
    • Visibility Level: 选择仓库可见性(公开/私有/内部)。
    • Initialize repository with a README : 不要勾选(避免推送冲突)。
  4. 点击 Create project,生成一个空仓库。

2. 准备本地项目

如果项目未初始化 Git
bash 复制代码
# 进入项目目录
cd /path/to/your/project

# 初始化 Git 仓库
git init

# 添加所有文件到暂存区
git add .

# 提交初始版本
git commit -m "Initial commit"
如果项目已是 Git 仓库

确保暂存区干净:

bash 复制代码
git status  # 确认无未提交的修改

3. 关联远程仓库

获取 GitLab 仓库的 URL(HTTPS 或 SSH):

  • HTTPS:适合临时使用,需每次输入账号密码。
  • SSH:推荐长期使用,需提前配置 SSH 密钥。
添加远程仓库地址
bash 复制代码
git remote add origin git@gitlab.com:your-username/your-project.git

或使用 HTTPS:

bash 复制代码
git remote add origin https://gitlab.com/your-username/your-project.git
验证远程仓库
bash 复制代码
git remote -v

应显示:

复制代码
origin  git@gitlab.com:your-username/your-project.git (fetch)
origin  git@gitlab.com:your-username/your-project.git (push)

4. 推送代码到 GitLab

首次推送(强制关联分支)
bash 复制代码
git push -u origin main
# 若本地分支名为 master,则改为:
# git push -u origin master
后续推送
bash 复制代码
git push

5. 处理常见问题

问题 1:远程仓库非空(如误勾选 README)

报错示例:

复制代码
! [rejected] main -> main (non-fast-forward)

解决方案

  1. 拉取远程仓库并合并:

    bash 复制代码
    git pull origin main --allow-unrelated-histories
  2. 解决冲突后重新推送:

    bash 复制代码
    git push -u origin main
问题 2:权限不足(SSH 配置)

报错示例:

复制代码
Permission denied (publickey).

解决方案

  1. 生成 SSH 密钥:

    bash 复制代码
    ssh-keygen -t ed25519 -C "your-email@example.com"
  2. 将公钥 ~/.ssh/id_ed25519.pub 添加到 GitLab:

    • 进入 GitLab → SettingsSSH Keys → 粘贴公钥。

完整操作示例

bash 复制代码
# 初始化项目
cd my-project
git init
git add .
git commit -m "Initial commit"

# 关联远程仓库
git remote add origin git@gitlab.com:your-username/my-project.git

# 推送代码
git push -u origin main

补充说明

  • 分支管理 :默认分支可能是 mainmaster,根据 GitLab 仓库设置调整。
  • 忽略文件 :建议创建 .gitignore 文件排除临时文件(如 node_modules/, .env 等)。
  • 协作权限 :私有项目需在 GitLab 中添加协作者(Settings → Members)。

相关推荐
LienJack2 小时前
我做了一个 AI Agent 学习站
github·agent
liushangzaibeijing2 小时前
Superpower 使用大纲
大数据·elasticsearch·搜索引擎
Elastic 中国社区官方博客2 小时前
每次操作一个 API 调用:Elastic Cloud Hosted 如何让大规模部署管理变得可行
大数据·运维·数据库·elasticsearch·搜索引擎·serverless
一点一木3 小时前
🚀 2026 年 5 月 GitHub 十大热门项目排行榜 🔥
人工智能·github·ai编程
逛逛GitHub4 小时前
GitHub 狂揽 1.3 万 Star,Anthropic 开源的知识工作者插件。
github
程序员鱼皮6 小时前
我用 GitHub 仓库养 AI 龙虾,自动开发上线项目!保姆级教程
前端·人工智能·ai·程序员·github·编程·ai编程
NPE~7 小时前
[手写系列]从零到一:Github开源你的第一个项目
ai·开源·github·教程·项目实战·规范·yiqguard
似夜晓星辰7 小时前
Markdown文本编辑器Typora平替
编辑器·github
右耳朵猫AI8 小时前
Github趋势榜 2026年第20周
github
Pluchon8 小时前
萌萌技术分享笔记——Java综合项目
java·开发语言·笔记·git·github·mybatis·postman