LoginSignup
4
5

More than 5 years have passed since last update.

Git(GitHub)+VPS(Vultr)で自動デプロイ環境構築

Last updated at Posted at 2017-05-07

自分用のメモとして。

やりたいこと

  • ローカルで開発
  • GitHubのリポジトリーにpush、同時にVPSのリポジトリーにもpush
  • VPSに自動デプロイされる:raised_hands:

環境

  • ローカル
    • OS:OSX El Capitan
    • Git:GitHub
  • VPS
    • Vultr
      • CentOS 7.3.1611
      • Nginx 1.13.0
      • Git 1.8.3.1

Git(GitHub)

あらかじめ「testing」というリポジトリーを作成しておきます。

VPS(Vultr)

configファイルを使って、SSH接続できるようにしておきます。
以下は記述例です。

~/.ssh/config
Host vultr
  HostName 12.34.56.789
  Port 22
  User hoge
  IdentityFile ~/.ssh/id_rsa

リポジトリー

オーソドックスなやりかたとして、リポジトリーを2つ用意します。

  • ノンベアリポジトリー(ローカルリポジトリー)
    • ワークツリーある。
    • チェックアウトとかマージとかできる。
  • ベアリポジトリー(リモートリポジトリー)
    • ワークツリーない。
    • チェックアウトとかマージとかできない。
    • いわゆる更新管理用。

これがややこしいのですが、VPSには両方のリポジトリーを置きます。
ディレクトリー構造としては以下になります。

var
└── www
    ├── html
    │    └── testing (ノンベアリポジトリー)
    └── testing.git (ベアリポジトリー)

ベアリポジトリーは公開する必要がないので、/var/www配下にしています。

流れ

ローカルのリポジトリー → ①GitHubのリポジトリー「testing」

②VPSのベアリポジトリー「testing.git」

VPSのノンベアリポジトリー「testing」(公開される)

※①と②は同時にpushします。

手順

まず、GitHubから「testing」を/var/www/htmlにcloneします。

cd /var/www/html
git clone https://github.com/{username}/testing.git

cloneしたリポジトリーをもとに、ベアリポジトリー「testing.git」を/var/wwwに作成します。

cd /var/www
git clone -bare /var/www/html/testing testing.git

つぎに、ベアリポジトリー「testing.git」のhooksを設定します。

cd /var/www/testing.git/hooks
vi post-update
post-update
#!/bin/sh
(cd /var/www/html/testing && git --git-dir=.git pull origin master)

ファイルに実行権限をつけて、動くか確認します。

chmod a+x post-receive
./post-receive

さいごに、GitHubからローカルに「testing」をcloneして、configファイルを編集します。
cloneする場所はホームディレクトリー直下の「git」フォルダー配下にしています。

~/git/testing/.git/config
[remote "origin"]
  url = https://{username}@github.com/{username}/testing.git
  url = ssh://user@hostname:port/var/www/testing.git ←この行を追加
  ...

user、hostname、portは、VPSのものです。
ローカルの~/.ssh/configにあわせて変更してください。

補足

1人だけで作業するのであればこれで問題ないと思います。
が、複数人でデプロイしあうには不十分なので、Netlifyなどをご検討ください。

参考

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5