LoginSignup
1

More than 5 years have passed since last update.

vagrantを使ってローカル開発環境を構築する

Last updated at Posted at 2017-04-22

本番デプロイ環境はlinuxの場合が多いので、ローカル開発環境もlinuxであることが望ましいケースが多い。vagrantを使えばすぐにlinuxの仮想環境が構築できる。

1. vagrant + virtual box をインストール

2. 仮想環境立ち上げ (ubuntu14.04)

$ mkdir ubuntu
$ cd ubuntu
$ touch Vagrantfile

config.vm.box に好きなOSを書く。

Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.box_check_update = true
  config.vm.network "forwarded_port", guest: 80, host: 8080
  config.vm.network "private_network", ip: "192.168.33.10"
  # config.vm.network "public_network"
  # config.vm.synced_folder "../data", "/vagrant_data"

  #config.vm.provider "virtualbox" do |vb|
  #  vb.gui = true
  #  vb.memory = "2048"
  #end

  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end
# 立ち上げ
$ vagrant up

3. 仮想環境に接続

$ vagrant ssh

よく使うコマンド (vagrant --helpで確認できる)

#box追加
$ vagrant box add [box名] [boxの場所]
#box list表示
$ vagrant box list
#状態確認
$ vagrant status
#一時停止 ~ sleep mode
$ vagrant suspend
#一時停止からの復帰
$ vagrant resume
#完全停止 ~ shutdown
$ vagrant halt
#再起動
$ vagrant reload
#設定変更だけ反映
$ vagrant provision
#消去
$ vagrant destroy

4. 仮想環境の設定

ubuntuのアップグレード

$ sudo apt-get update
$ sudo apt-get upgrade -y

ロケールの設定

$ sudo apt-get install -y language-pack-ja
$ sudo update-locale LANG=ja_JP.UTF-8

5. サーバー運用・設定の tips

新しいユーザーを追加する

$ sudo apt-get install -y finger
$ sudo adduser <newuser>
#新しいユーザーに sudo権限の付与
$ sudo ls /etc/sudoers.d/
$ sudo cp /etc/sudoers.d/vagrant /etc/sudoers.d/<newuser>
$ sudo nano /etc/sudoers.d
sudoers.d
# CLOUD_IMG: This file was created/modified by the Cloud Image build process
<newuser> ALL=(ALL) NOPASSWD:ALL

sshでの接続に限定する(passwd接続を禁止する)

#passwdを無効にする e: expire
$ sudo passwd -e <newuser> 

(local)$ ssh-keygen

$ mkdir .ssh
$ touch .ssh/authorized_keys
$ nano .ssh/authorized_keys

localで生成した公開鍵(~/.ssh/*.pub)の中身をコピペする

$ chmod 700 .ssh
$ chmod 644 .ssh/authorized_keys

#passwd接続を禁止する
$ sudo nano /etc/ssh/sshd_config

PasswordAuthenticationをnoに変更する

$ sudo service ssh restart

#接続確認
(local)$ ssh <newuser>@localhost -i .ssh/<key_file>

ファイルへのアクセス権限を変更する

$ ls -l
#(owner, group, everyone)
$ chmod 744 hoge.sh
$ chmod 655 index.html 
#所有権を変更する
$ chown <owner> <filename>
$ chgrp <group> <filename>

ファイアウォールを設定する

$ sudo ufw status
$ sudo ufw default deny incoming
$ sudo ufw default accept outgoing
#$ sudo ufw allow <protocol>
$ sudo ufw allow ssh # 20/tcp
$ sudo ufw allow 2222/tcp
$ sudo ufw allow www # 80/tcp
$ sudo ufw enable

6. apache webサーバーを立ててみる

$ sudo apt-get install -y apache2
$ sudo nano /var/www/html/index.html

hello world !

(local)$ open http://localhost:8080

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
1