上一篇
如何在git上传代码至Linux服务器时确保文件同步无误?
- 前端开发
- 2026-01-15
- 4
Git上传至Linux服务器的详细步骤如下:

Git上传至Linux服务器步骤
准备工作
- 安装Git:确保你的本地开发环境已经安装了Git。
- SSH密钥生成:在本地生成SSH密钥对,并将公钥添加到Linux服务器的~/.ssh/authorized_keys文件中。 sshkeygen t rsa b 4096
- 配置Git用户信息:在本地仓库中配置你的用户信息。 git config global user.name "Your Name" git config global user.email "your_email@example.com"
克隆远程仓库
- 使用SSH协议克隆远程仓库到本地。 git clone git@yourserver.com:/path/to/remoterepo.git
创建新分支
- 在本地创建一个新的分支。 git checkout b newbranch
添加和提交更改
- 在新分支上工作,添加文件并提交更改。 git add . git commit m "Initial commit"
推送到远程仓库
- 将本地分支的更改推送到远程仓库。 git push origin newbranch
在Linux服务器上操作
- 登录到Linux服务器。
- 克隆远程仓库到服务器。 git clone git@yourserver.com:/path/to/remoterepo.git
- 选择服务器上的合适位置创建一个指向远程分支的本地分支。 cd /path/to/remoterepo git checkout b newbranch origin/newbranch
合并或拉取更改
- 在服务器上,将远程分支的更改合并到本地分支。 git pull origin newbranch
部署到服务器
- 根据项目需求,部署代码到服务器。
- 可能需要执行一些部署脚本或命令。
| 步骤 | 命令 | 说明 |
|---|---|---|
| 1 | sshkeygen t rsa b 4096 | 生成SSH密钥 |
| 2 | git clone git@yourserver.com:/path/to/remoterepo.git | 克隆远程仓库 |
| 3 | git checkout b newbranch | 创建新分支 |
| 4 | git add . 和 git commit m "Initial commit" | 添加和提交更改 |
| 5 | git push origin newbranch | 推送到远程仓库 |
| 6 | git checkout b newbranch origin/newbranch | 在服务器上创建本地分支 |
| 7 | git pull origin newbranch | 合并远程更改 |
| 8 | 部署命令 | 部署代码到服务器 |
FAQs
Q1:如何解决SSH连接失败的问题?
A1: 确保SSH密钥对已正确生成,并且公钥已添加到Linux服务器的~/.ssh/authorized_keys文件中,检查SSH配置文件~/.ssh/config以确保正确的服务器地址和端口。


Q2:如何查看Git仓库的提交历史?
A2: 使用以下命令查看本地仓库的提交历史。
git log
对于远程仓库,可以使用:
git log origin/newbranch
国内文献权威来源
- 《Git权威指南》
- 《Linux服务器配置与管理》
- 《SSH权威指南》