将本地项目上传到 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)。

相关推荐
掘我的金2 小时前
galgamex 容器化部署实战:从 Dockerfile、Compose 到 Prisma 初始化与首个账号
github
我的收藏手册2 小时前
性能监控shell脚本编写
前端·git·github
CoderJia程序员甲2 小时前
GitHub 热榜项目 - 日榜(2025-09-07)
ai·github·开源项目·github热榜
AAA修煤气灶刘哥5 小时前
ES 聚合爽到飞起!从分桶到 Java 实操,再也不用翻烂文档
后端·elasticsearch·面试
Elasticsearch5 小时前
Elastic Observability 中 Discover 的跟踪,用于深入的应用洞察
elasticsearch
掘我的金5 小时前
Text2Light 安装案例:从 GPU 可用到 OpenEXR 报错,再到顺利出图(Windows + Conda)
github
Elasticsearch6 小时前
使用 cloud-native Elasticsearch 与 ECK 运行
elasticsearch
杨杨杨大侠6 小时前
第3章:实现基础事件总线
java·github·eventbus
杨杨杨大侠6 小时前
第4章:添加注解支持
java·github·eventbus
libokaifa6 小时前
C++ 基础学习
前端·架构·github