LoginSignup
4
2

More than 3 years have passed since last update.

【Vagrant/Mac】ローカルと仮想マシンのフォルダを共有/同期する方法

Last updated at Posted at 2020-04-28

執筆にあたり

自己紹介も含め、簡単に今の状況を書きます。

実務でPHPを使うことになったので、まずはパーフェクトPHPで学習を進めようと思っている駆け出しです。

折角なので(ローカルを汚したくないという思いもあり)、Vagrantを使った仮想環境で学習しようと決意。

ただ、学習の都度vagrantにsshログインしてviで開発していくのも面倒だと思ったので、ローカルと仮想マシンでフォルダ同期が出来ることを知り、、、
色々調べるも古い情報だったり、パスの記述方法が違ったりして、ハマったので備忘録として残します。

前提条件

macOS Catalina 10.15.3
Vagrant 2.2.7

ここまでに至る環境構築については以下を参照しました。
わかりやすかったです。ありがとうございます!(勝手にリンク失礼します)
Vagrant+VirtualBoxで仮想環境を構築し、PHPの実装内容をブラウザで確認する

上記の手順を一通り終えたことを前提に書いていきます。

1.Vagrantfileの修正

まずはローカルでの作業です。
ルートディレクトリから以下を実行します
(今回のケースはcentos7というディレクトリに移動しておりますが、bootしたい仮想マシンのVagrantfileが置いてあるディレクトリに移動してください)

$ cd centos7/
$ vim Vagrantfile

開いて少しスクロールすると、以下のような記述になっている箇所があるかと思います。

# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "../data", "/vagrant_data"

こちらの5行目が「同期するフォルダ設定」が書かれている部分です。
以下のように変更。

# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
config.vm.synced_folder "./shared", "/home/vagrant/shared"

何を書いたかというと、

config.vm.synced_folder "同期したいディレクトリのローカル側のパス","同期したいディレクトリの仮想マシン側のパス"

という構文になります。

ポイントは、"同期したいディレクトリのローカル側のパス"を相対パス(ここで言うとVagrantfileと同ディレクトリに配置されているsharedディレクトリを指してます)、
"同期したいディレクトリの仮想マシン側のパス"は絶対パスで書きます。
ここ間違えるとハマります...。

2.ローカルに共有ディレクトリを作成

1.でVagrantfileに記述したsharedディレクトリがないので作成します。
ローカルで同じディレクトリでの作業です。

$ mkdir shared
$ ls 
Vagrantfile /shared
# sharedディレクトリが作成されました

3.vagrantを再起動

また同じディレクトリで再起動コマンドを実行。

$ vagrant reload

4.vagrantでディレクトリやファイルを作成し、ローカルで確認しよう

vagrantに入り、vagrantで作成したディレクトリやファイルと同じものが、ローカルにもきちんと作成されるかを確認しましょう!

まずは、vagrantにsshで入り、1.で書いたルートディレクトリ直下のvagrant_dataディレクトリが無いので作成。

# vagrantにsshログイン
$ vagrant ssh

# vagrant_dataを作成
$ mkdir shared

# 移動
$ cd shared

# sampleディレクトリを作成
$ mkdir sample

# sample(html)ファイルを作成
$ touch sample.html

# vagrantをログアウト
$ exit

ローカルで同じディレクトリやファイルが作成されているかを確認します。

$ cd shared
$ ls
# /sample sample.html

無事同期されていることが確認できたらOKです!

4
2
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
2