git推送到vps

git推送到vps

本地操作

  • 安装git
  • 生成ssh密钥
1
2
3
git config --global user.name "yourname"
git config --global user.email youremail@example.com
ssh-keygen -t rsa -C "youremail@example.com

最后生成的ssh密钥在~/.ssh/中

VPS操作

  • 安装并配置Git

安装后您可能想要做的第一件事是在Git中配置自己的名称和电子邮件地址,以便您提交的更改包含正确的信息。 您可以通过使用以下命令来完成此操作:

1
2
git config --global user.name "yourname"
git config --global user.email "youremail@example.com"
  • 创建git用户并切换到git用户
1
2
adduser git
su git

根据提示填写内容。这步很重要,不切换用户后面需要手动修改文件的拥有者与组

  • 创建仓库
1
2
3
cd /var/www/
mkdir repos
git init --bare repos.git
  • 添加钩子函数

钩子函数在push文件后执行checkout

1
2
3
cd blog.git/hooks
vi post-receive
chmod +x post-receive

post-receive内容如下

1
2
#!/bin/sh
git --work-tree=/var/www/repos --git-dir=/var/www/repos.git checkout -f

测试git仓库是否可用,在本地机器另找空白文件夹,执行如下命令

1
git clone git@server_ip:/var/www/repos.git

clone没有报错,提示clone到空的resp

  • 建立本地与vps ssh信任关系

将本地的公钥复制到vps的authorized_keys文件里(公钥即上文中本地执行cat ~/.ssh/id_rsa.pub查看的内容)

1
2
3
4
su git
cd ~
mkdir .ssh && cd .ssh
vim authorized_keys

push本地文件

经过上述步骤后,可以将本地文件push到vps中,以hugo为例,进入publish目录,初始化git仓库,操作如下

1
2
3
4
5
6
cd publish
git init
git add -A
git commit -m "building site"
git remote add origin git@server_ip:/var/www/repos.git
git push --set-upstream origin master

修改本地文件后,可以使用脚本一键push

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/bin/bash

echo -e "\033[0;32mDeploying updates to VPS...\033[0m"

# Build the project.
cd exampleSite
hugo # if using a theme, replace by `hugo -t <yourtheme>`

# Go To Public folder
cd public
# Add changes to git.

git add -A

# Commit changes.
msg="rebuilding site `date`"

if [ $# -eq 1 ]; then
msg="$1"
fi

git commit -m "$msg"

# Push source and build repos.
git push origin master

# Come Back
cd ..

note:

从本地git push到vps中的文件owner与group都是上文中创建的git用户,需要确保nginx有权限访问这些html文件,可以将nginx worker用户与git放到一个组,设置文件组访问权限

参考链接

https://www.jianshu.com/p/d1f7cfb8ecf0

# 推荐文章
  1.git推送到vps
  2.http服务器搭建
  3.linux网卡命名
  4.docker使用
  5.hexo创建博客

评论


:D 一言句子获取中...

加载中,最新评论有1分钟延迟...