github actionsを使ってmainブランチにpushした時に自動で本番環境(indigo VPS)に公開できるように設定したのでメモ。
環境
- サーバー webARENA indigo VPS 1GB
- OS : ubuntu 20.04 LTS
- githubはプライベートリポジトリ
- webpackでバンドルしたディレクトリのみ公開したい
ディレクトリ構成
root/
┣build/
┃ ┣ data/
┃ ┣ template/
┃ ┣ js/
┃ ┗ index.html
┣public/
┃ ┣ data/
┃ ┣ template/
┃ ┗ index.html
┗scr/
┗ index.js
webpackでバンドルしたものがbuildディレクトリなので公開用ディレクトリにはここだけデプロイします。
手順
1. VPSでgit pullできるようにする
まずはVPSにsshで接続。
gitが使えるか確認
$ git --version
git version 2.30.1 // このように出力されてればok
command not foundの場合はgitをインストール
$ sudo apt-get install git
gitの初期設定を行う。
ユーザーネームとメールアドレスはgithubのユーザーと同じものを設定する。
$ git config --global user.name your-username
$ git config --global user.email your-email
正しく登録できたか確認
$ cat ~/.gitconfig
// 以下が出力されてればok
[user]
name = your-username
email = your-email
git cloneするディレクトリを用意。今回はvar/git/以下にcloneしました。
$ cd /var/
$ sudo mkdir git
$ cd git/
git cloneします。
$ sudo git clone https://github.com/username/repositoryname.git
Username for 'https://github.com':
Password for 'https://github.com':
ユーザーネームとパスワードを求められるので入力します。パスワードはログインpwではなくアクセストークンなので注意。
cloneできたらssh接続ユーザーに所有を書き換えます。
$ sudo chown -R ssh-user repositoryname
これでpullできるか確認
$ cd repositoryname
$ git pull
Username for 'https://github.com':
Password for 'https://github.com':
Already up to date. // このように出力されればok
UsernameとPasswordを省略できるよう設定します。
$ git remote set-url origin https://username:password@github.com/username/repositoryname.git
省略できるようになったか確認
$ git pull
ユーザー名とパスワードを聞かれなければok
2. github actionsの設定
githubのリポジトリへアクセスし、Actionsタブからseup workflow yourselfを選択。
main.ymlの中身を以下のように書き換え
name: CD
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install SSH Key for Deploy
uses: appleboy/ssh-action@master
with:
key: ${{ secrets.SSH_KEY }}
host: ${{ secrets.HOST_NAME }}
username: ${{ secrets.SSH_USER }}
port: ${{ secrets.SSH_PORT }}
script: |
cd /var/git/repositoryname/
git pull
cp -r /var/git/repositoryname/build/* /var/www/kanaru.jp/public_html/
name:CDは任意の名前でok
on: push: branches: [main] でmainブランチにプッシュされた時に実行される。
SSH_KEY、HOST_NAME、SSH_USER、SSH_PORTは後でgithubに登録します。
ssh接続後、script以下が実行されます。
// gitリポジトリへ移動
cd /var/git/repositoryname/
// pullする
git pull
// buildの中身を公開ディレクトリにコピー
cp -r /var/git/repositoryname/build/* /var/www/xxx.com/public_html/
※公開ディレクトリの方もsshユーザーが書き込み権限を持っている必要があります。
これでコミットします。
mainブランチに/.github/workflows/main.ymlが追加されてればok。
githubにsecretsを登録

settingタブ -> secrets -> New repository secret をクリック
Name : HOST_NAME Value : vpsのipアドレス
Name : SSH_KEY Value : ssh接続する時のkey
Name : SSH_USER Value : ssh接続する時のユーザーネーム
Name : SSH_PORT Value : ssh接続する時のポート(デフォルトだと22番ポート)
ssh_keyは —–BEGIN OPENSSH PRIVATE KEY—– ・・・・ —–END OPENSSH PRIVATE KEY—–まで全てコピペする。
3. ローカルからpushしてみる

actionsにプッシュした内容が緑のチェックマークでついてればok。
公開ディレクトリの内容が書き変わってるか確認。
以上。