如何在不使用github的情况下将本地git repo部署到VPS

时间:2021-03-24 21:47:33

标签: git continuous-integration

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

我的目标:

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

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

我想:“为什么要使用 bitbucket 并在设置我的服务器以使用此工作流程时添加更多工作的中间步骤?”难道我不能以某种方式直接推送到我的 VPS 并消除对 bitbucket webhook 的需求。

问题:

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

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

附加信息:

  • Linux 服务器/开发环境
  • 将使用 ansible 来配置服务器

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

1 个答案:

答案 0 :(得分:1)

如果您推送到 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

假设您可以通过密钥身份验证通过 ssh 访问您的 VPS,我建议您为您的 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: