首页 > 解决方案 > 如何在不使用 github 的情况下将本地 git repo 部署到 VPS

问题描述

我有一个本地 git repo,我正在其中工作,并试图找出一个很好的工作流程,将我的本地开发部署到我的生产 VPS 服务器。

我的目标:

我希望能够在我的本地 git repo 上工作并简单地做一个git push production master 将我的生产 VPS 服务器与我的最新更改同步,然后添加一个 git 挂钩来执行一个 bash 脚本来自动在远程服务器上进行所有必要的部署无需我在运行上述 git 命令之外进行干预。

到目前为止,我已经研究过使用 bitbucket 和他们的 webhook 服务,但是我相信我需要在我的 VPS 上设置一个侦听器服务器来接收这些 webhook 通知,然后相应地处理它们。

我想:“为什么有这个使用 bitbucket 的中间步骤并且必须添加更多工作来设置我的服务器以使用这个工作流程?” 我不能以某种方式直接推送到我的 VPS 并消除对 bitbucket webhook 的需求。

问题:

如何在我的 VPS 上设置此架构?在我的本地 git repo 和远程服务器之间创建连接需要哪些步骤 - 最终目标是能够做一个简单的git push production master

这是一个深思熟虑的方法还是我在这里忽略了任何潜在的问题?

附加信息:

欢迎任何帮助或指点,谢谢

标签: gitcontinuous-integration

解决方案


如果你在你的 VPS 上推送到一个裸仓库,你可以使用 post-receive 钩子在那里部署文件。以下是稀疏签出的示例,您可以根据需要选择从部署中排除某些文件。

创建用于部署文件子集的裸仓库(稀疏签出)

##
## Note: In this example the deploy host and dev host are the same which is 
## why we're using local paths; ~/git/camero.git will represent the bare repo
## on the remote host.
##

# create the bare repo
# (leave out --shared if you're the only one deploying)
git init --bare --shared ~/git/camero.git

# configure it for sparse checkout
git --git-dir=~/git/camero.git config core.sparseCheckout true

# push your code to it
git --git-dir=~/dev/camero remote add deploy ~/git/camero.git
git --git-dir=~/dev/camero push deploy master
#!/bin/sh
#
# sample post-receive script
#  ~/git/camero.git/hooks/post-receive
#

deploy_branch='master'
deploy_dir='/some/place/on/this/host'

while read -r oldrev newrev ref; do
    test "${ref##*/}" == "$deploy_branch" && \
    git --work-tree="$deploy_dir" checkout -f $deploy_branch || \
    echo "not deploying branch ${ref##*/}"
done
#
# sample sparse-checkout file
# Note: the pattern syntax is the same as for .gitignore
# Save this file in ~/git/camero.git/info/sparse-checkout
#

# deploy all python files
*.py

# ... except for the test python files
!*Test*.py

假设您可以通过密钥身份验证对您的 VPS 进行 ssh 访问,我建议您为您的 VPS 设置一个带有主机条目的 ~/.ssh/config 文件。它将简化您的 git 命令。

# sample .ssh/config host entry
Host vps
    Hostname 192.0.2.1
    User your_username
    # any other ssh configuration needed by vps

然后你可以替换~/git/vps:


推荐阅读