You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Git新手求助:如何正确实现本地Staging仓库推送到Production文件夹?

实现本地Git仓库推送至生产目录的规范方案

你的核心需求是确保只有已提交到Git的代码能同步到生产目录,同时遵循Git规范,避免直接推送非bare仓库的风险。以下是标准可行的方案:

1. 创建中转用的Bare仓库

Bare仓库是Git专门用于共享版本历史的仓库(无工作区,仅存版本数据),是推送操作的标准目标。

# 选择一个合适的位置创建bare仓库(比如和production_folder同级)
mkdir /path/to/prod_bare.git && cd /path/to/prod_bare.git
git init --bare

2. 在Staging仓库配置远程推送目标

将刚才创建的bare仓库添加为Staging_folder的远程仓库:

cd /path/to/Staging_folder
git remote add production /path/to/prod_bare.git

3. 推送已提交代码到Bare仓库

每次确保所有变更都已提交后,再执行推送(Git会阻止未提交的变更被推送,刚好满足你的需求):

# 先提交所有本地变更
git add .
git commit -m "提交说明:比如完成XX功能"
# 推送到远程production仓库的master分支
git push production master

4. 在生产目录获取实际文件

production_folder作为工作区,通过克隆bare仓库来获取代码文件:

cd /path/to/production_folder
# 克隆bare仓库到当前目录(最后的.表示不创建子文件夹)
git clone /path/to/prod_bare.git .

后续更新时,直接在production_folder拉取最新代码即可:

git pull production master

进阶:自动同步生产目录(可选)

如果不想每次推送后手动拉取,可以给bare仓库添加post-receive钩子,实现推送完成后自动更新生产目录:

  1. 在bare仓库的hooks目录创建钩子文件:
cd /path/to/prod_bare.git/hooks
touch post-receive
  1. 编辑post-receive文件,添加以下内容(替换为你的production_folder路径):
#!/bin/sh
GIT_WORK_TREE=/path/to/production_folder git checkout -f master
  1. 给钩子文件添加执行权限:
chmod +x /path/to/prod_bare.git/hooks/post-receive

这样以后你在Staging_folder执行git push后,production_folder会自动同步最新的已提交代码。


内容的提问来源于stack exchange,提问作者Peter Lustig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 03:52:22