Docker Machineを試す

Dockerを再び触り始める前にまずはDocker Machineを試してみます。

※このエントリは[はてなブログ](http://nmtysh.hatenablog.com/entry/2016/03/13/225117)にも同じ内容を投稿しています。

# 0. 環境

- Max OS X 10.11
- Homebrew
- VirtualBox

```bash
$ brew -v
Homebrew 0.9.5 (git revision 2d5e5; last commit 2016-03-12)
$ VBoxManage -v
5.0.16r105871
```

# 1. Homebrewで Docker Machineをインストールする

## 1.1 まずはdockerからインストール

```bash
$ brew install docker
==> Downloading https://homebrew.bintray.com/bottles/docker-1.10.3.el_capitan.bo
######################################################################## 100.0%
==> Pouring docker-1.10.3.el_capitan.bottle.tar.gz
==> Caveats
Bash completion has been installed to:
  /usr/local/etc/bash_completion.d

zsh completion has been installed to:
  /usr/local/share/zsh/site-functions
==> Summary
🍺  /usr/local/Cellar/docker/1.10.3: 10 files, 11.2M
$ docker -v
Docker version 1.10.3, build 20f81dd
```

## 1.2 続いてDocker Machineをインストール

```bash
$ brew install docker-machine
==> Downloading https://homebrew.bintray.com/bottles/docker-machine-0.6.0.el_cap
######################################################################## 100.0%
==> Pouring docker-machine-0.6.0.el_capitan.bottle.tar.gz
==> Caveats
Bash completion has been installed to:
  /usr/local/etc/bash_completion.d
==> Summary
🍺  /usr/local/Cellar/docker-machine/0.6.0: 5 files, 36.8M
$ docker-machine -v
docker-machine version 0.6.0, build e27fb87
```

# 2. Local環境にDocker Machineを作成します。

## 2.1 create

createサブコマンドを使って作成します。
driverにVirtualBoxを選択しているので内部ではBoot2Dockerを使用して作成されます。
初回起動時はisoイメージファイルの取得があるため時間がかかります。

```bash
$ docker-machine create --driver virtualbox docker-machine
Creating CA: /Users/User/.docker/machine/certs/ca.pem
Creating client certificate: /Users/User/.docker/machine/certs/cert.pem
Running pre-create checks...
(docker-machine) Image cache directory does not exist, creating it at /Users/User/.docker/machine/cache...
(docker-machine) No default Boot2Docker ISO found locally, downloading the latest release...
(docker-machine) Latest release for github.com/boot2docker/boot2docker is v1.10.3
(docker-machine) Downloading /Users/User/.docker/machine/cache/boot2docker.iso from https://github.com/boot2docker/boot2docker/releases/download/v1.10.3/boot2docker.iso...
(docker-machine) 0%....10%....20%....30%....40%....50%....60%....70%....80%....90%....100%
Creating machine...
(docker-machine) Copying /Users/User/.docker/machine/cache/boot2docker.iso to /Users/User/.docker/machine/machines/docker-machine/boot2docker.iso...
(docker-machine) Creating VirtualBox VM...
(docker-machine) Creating SSH key...
(docker-machine) Starting the VM...
(docker-machine) Check network to re-create if needed...
(docker-machine) Found a new host-only adapter: "vboxnet1"
(docker-machine) Waiting for an IP...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with boot2docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Checking connection to Docker...
Docker is up and running!
To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: docker-machine env docker-machine
```

この状態ですでにDocker Machineが起動しています。

どんなVMが作成されたのか確認して見ます。

```bash
$ VBoxManage list vms
(省略)
"docker-machine" {9f226873-bb24-4e20-8c62-2f8d82467746}
$ VBoxManage showvminfo docker-machine
Name:            docker-machine
Groups:          /
Guest OS:        Linux 2.6 / 3.x / 4.x (64-bit)
UUID:            9f226873-bb24-4e20-8c62-2f8d82467746
Config file:     /Users/User/.docker/machine/machines/docker-machine/docker-machine/docker-machine.vbox
Snapshot folder: /Users/User/.docker/machine/machines/docker-machine/docker-machine/Snapshots
Log folder:      /Users/User/.docker/machine/machines/docker-machine/docker-machine/Logs
Hardware UUID:   9f226873-bb24-4e20-8c62-2f8d82467746
Memory size:     1024MB
Page Fusion:     off
VRAM size:       8MB
CPU exec cap:    100%
HPET:            on
Chipset:         piix3
Firmware:        BIOS
Number of CPUs:  1
PAE:             on
Long Mode:       on
CPUID Portability Level: 0
CPUID overrides: None
Boot menu mode:  disabled
Boot Device (1): DVD
Boot Device (2): DVD
Boot Device (3): HardDisk
Boot Device (4): Not Assigned
ACPI:            on
IOAPIC:          on
Time offset:     0ms
RTC:             UTC
Hardw. virt.ext: on
Nested Paging:   on
Large Pages:     on
VT-x VPID:       on
VT-x unr. exec.: on
Paravirt. Provider: Default
State:           running (since 2016-03-13T01:42:23.311000000)
Monitor count:   1
3D Acceleration: off
2D Video Acceleration: off
Teleporter Enabled: off
Teleporter Port: 0
Teleporter Address:
Teleporter Password:
Tracing Enabled: off
Allow Tracing to Access VM: off
Tracing Configuration:
Autostart Enabled: off
Autostart Delay: 0
Default Frontend:
Storage Controller Name (0):            SATA
Storage Controller Type (0):            IntelAhci
Storage Controller Instance Number (0): 0
Storage Controller Max Port Count (0):  30
Storage Controller Port Count (0):      30
Storage Controller Bootable (0):        on
SATA (0, 0): /Users/User/.docker/machine/machines/docker-machine/boot2docker.iso (UUID: c73a0e3e-2c7f-4c87-9c90-ae3581335348)
SATA (1, 0): /Users/User/.docker/machine/machines/docker-machine/disk.vmdk (UUID: 334e7b36-fcd1-4fd4-933c-5e114b837215)
NIC 1:           MAC: 080027XXXXXX, Attachment: NAT, Cable connected: on, Trace: off (file: none), Type: 82540EM, Reported speed: 0 Mbps, Boot priority: 0, Promisc Policy: deny, Bandwidth group: none
NIC 1 Settings:  MTU: 0, Socket (send: 64, receive: 64), TCP Window (send:64, receive: 64)
NIC 1 Rule(0):   name = ssh, protocol = tcp, host ip = 127.0.0.1, host port = 58882, guest ip = , guest port = 22
NIC 2:           MAC: 080027YYYYYY, Attachment: Host-only Interface 'vboxnet1', Cable connected: on, Trace: off (file: none), Type: 82540EM, Reported speed: 0 Mbps, Boot priority: 0, Promisc Policy: deny, Bandwidth group: none
NIC 3:           disabled
NIC 4:           disabled
NIC 5:           disabled
NIC 6:           disabled
NIC 7:           disabled
NIC 8:           disabled
Pointing Device: PS/2 Mouse
Keyboard Device: PS/2 Keyboard
UART 1:          disabled
UART 2:          disabled
UART 3:          disabled
UART 4:          disabled
LPT 1:           disabled
LPT 2:           disabled
Audio:           disabled
Clipboard Mode:  disabled
Drag and drop Mode: disabled
Session name:    headless
Video mode:      720x400x0 at 0,0 enabled
VRDE:            disabled
USB:             disabled
EHCI:            disabled
XHCI:            disabled

USB Device Filters:

<none>

Available remote USB devices:

<none>

Currently Attached USB Devices:

<none>

Bandwidth groups:  <none>

Shared folders:

Name: 'Users', Host path: '/Users' (machine mapping), writable

VRDE Connection:    not active
Clients so far:     0

Video capturing:    not active
Capture screens:    0
Capture file:       /Users/User/.docker/machine/machines/docker-machine/docker-machine/docker-machine.webm
Capture dimensions: 1024x768
Capture rate:       512 kbps
Capture FPS:        25

Guest:

Configured memory balloon size:      0 MB
OS type:                             Linux26_64
Additions run level:                 2
Additions version:                   5.0.16 r105871

Guest Facilities:

Facility "VirtualBox Base Driver": active/running (last update: 2016/03/13 01:42:42 UTC)
Facility "VirtualBox System Service": active/running (last update: 2016/03/13 01:43:02 UTC)
Facility "Seamless Mode": not active (last update: 2016/03/13 01:42:42 UTC)
Facility "Graphics Mode": not active (last update: 2016/03/13 01:42:42 UTC)
$ VBoxManage showhdinfo 334e7b36-fcd1-4fd4-933c-5e114b837215
UUID:           334e7b36-fcd1-4fd4-933c-5e114b837215
Parent UUID:    base
State:          locked write
Type:           normal (base)
Location:       /Users/User/.docker/machine/machines/docker-machine/disk.vmdk
Storage format: VMDK
Format variant: dynamic default
Capacity:       20000 MBytes
Size on disk:   2 MBytes
Encryption:     disabled
In use by VMs:  docker-machine (UUID: 9f226873-bb24-4e20-8c62-2f8d82467746)
```

メモリーが1GB, Diskが20GBのVMが作成されていることが解ります。
また/Usersが共有フォルダとしてマウントされているようです。

## 2.2 ls

lsサブコマンドで作成したDocker Machineの一覧を確認できます。

```bash
$ docker-machine ls
NAME             ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER    ERRORS
docker-machine   -        virtualbox   Running   tcp://192.168.99.100:2376           v1.10.3
```

## 2.3 env

envサブコマンドでdockerコマンドに必要な環境変数を設定します。

```bash
$ docker-machine env docker-machine
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.100:2376"
export DOCKER_CERT_PATH="/Users/User/.docker/machine/machines/docker-machine"
export DOCKER_MACHINE_NAME="docker-machine"
# Run this command to configure your shell:
# eval $(docker-machine env docker-machine)

$ eval $(docker-machine env docker-machine)
$ env | grep DOCKER
DOCKER_HOST=tcp://192.168.99.100:2376
DOCKER_MACHINE_NAME=docker-machine
DOCKER_TLS_VERIFY=1
DOCKER_CERT_PATH=/Users/User/.docker/machine/machines/docker-machine
```

環境変数を削除する場合は`--unset`オプション(あるいは`-u`)を付けます。

```bash
$ docker-machine env --unset
unset DOCKER_TLS_VERIFY
unset DOCKER_HOST
unset DOCKER_CERT_PATH
unset DOCKER_MACHINE_NAME
# Run this command to configure your shell:
# eval $(docker-machine env --unset)

$ eval $(docker-machine env --unset)
$ env | grep DOCKER
$
```

## 2.4 dockerを試す

試しにdockerを実行してみます。

### 2.4.1 Hello, World

```bash
$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

$ docker run busybox echo hello
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
f810322bba2c: Pull complete
a3ed95caeb02: Pull complete
Digest: sha256:97473e34e311e6c1b3f61f2a721d038d1e5eef17d98d1353a513007cf46ca6bd
Status: Downloaded newer image for busybox:latest
hello
```

### 2.4.2 daemon実行

ついでにwebサーバーも動かしてみます。

```
$ docker run -d -p 8000:80 nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
fdd5d7827f33: Pull complete
a3ed95caeb02: Pull complete
716f7a5f3082: Pull complete
7b10f03a0309: Pull complete
Digest: sha256:f6a001272d5d324c4c9f3f183e1b69e9e0ff12debeb7a092730d638c33e0de3e
Status: Downloaded newer image for nginx:latest
0887cee790555e69f8a7f7d0efdfad0e2b9545ee8a4a3b54f2fbb92590127214
```

起動したらcurlで取得してみます(ブラウザでも可)
Docker Machineのipサブコマンドで対象Machineのipアドレスが取得できます。

```
$ curl "http://$(docker-machine ip docker-machine):8000"
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
```

### 2.4.3 dockerの後片付け

#### 2.4.3.1 nginxコンテナを停止

```bash
$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                           NAMES
0887cee79055        nginx               "nginx -g 'daemon off"   4 minutes ago       Up 4 minutes        443/tcp, 0.0.0.0:8000->80/tcp   grave_boyd
$ docker stop 0887cee79055
0887cee79055
$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
```

#### 2.4.3.2 コンテナを削除

```bash
$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
0887cee79055        nginx               "nginx -g 'daemon off"   6 minutes ago       Exited (0) 57 seconds ago                       grave_boyd
c7c9e4f02f7c        busybox             "echo hello"             8 minutes ago       Exited (0) 8 minutes ago                        reverent_ride
$ docker rm 0887cee79055
0887cee79055
$ docker rm c7c9e4f02f7c
c7c9e4f02f7c
$  docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
```

#### 2.4.3.3 イメージファイルを削除

```bash
$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              af4b3d7d5401        3 days ago          190.5 MB
busybox             latest              3240943c9ea3        3 weeks ago         1.114 MB
$ docker rmi nginx
Untagged: nginx:latest
Deleted: sha256:af4b3d7d5401624ed3a747dc20f88e2b5e92e0ee9954aab8f1b5724d7edeca5e
Deleted: sha256:42d2184b31e555191b5329abd0c9a97f82fe8c51991f19017e90d657398488cf
Deleted: sha256:b9dfb6190c842c4dda3115b829b4157cf9859554090fca1c4c51f56f7a40eca6
Deleted: sha256:1a31d9de2c5959dfcc9ede61e0575b119a125c7a206a77b88c6dfbeec35829f1
Deleted: sha256:8cc268db9c78453fc2203f4b7005e0b3c7291ae63e3d9c874ba53e5be664c9b8
Deleted: sha256:5ae35615df0549b450258af03ec74a0f7996d8aa30df5eae7cea7f9b08ed4be4
Deleted: sha256:02ff90df226000c1386080f59bc06672a0c442ce1dd5769c294f443368c4deb4
Deleted: sha256:894fdee79cd8b48c0b0b6ac6664ad0327c67782c80a1d81ac2d0a65505d0e116
Deleted: sha256:917c0fc99b353c0397a9effdf042d72529de7c452669b1e11b05bec3088c7056
$ docker rmi busybox
Untagged: busybox:latest
Deleted: sha256:3240943c9ea3f72db51bea0a2428e83f3c5fa1312e19af017d026f9bcf70f84b
Deleted: sha256:a3aeefae0d4b8f61fac9d341713675479f2b28319bd9a2c31b366de1e9efcee0
Deleted: sha256:16a7ebd378002f1261dfb5e21cc22d9473aaac7e06a1cd4ff4e26cfd75432e8f
$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
```

## 2.5 ip

先ほどのipサブコマンドです。
指定したDocker Machineのipアドレスが取得できます。

```bash
$ docker-machine ip docker-machine
192.168.99.100
```

## 2.6 ssh

sshサブコマンドで指定したDocker Machineへssh接続ができます。

```bash
$ docker-machine ssh docker-machine
                        ##         .
                  ## ## ##        ==
               ## ## ## ## ##    ===
           /"""""""""""""""""\___/ ===
      ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
           \______ o           __/
             \    \         __/
              \____\_______/
 _                 _   ____     _            _
| |__   ___   ___ | |_|___ \ __| | ___   ___| | _____ _ __
| '_ \ / _ \ / _ \| __| __) / _` |/ _ \ / __| |/ / _ \ '__|
| |_) | (_) | (_) | |_ / __/ (_| | (_) | (__|   <  __/ |
|_.__/ \___/ \___/ \__|_____\__,_|\___/ \___|_|\_\___|_|
Boot2Docker version 1.10.3, build master : 625117e - Thu Mar 10 22:09:02 UTC 2016
Docker version 1.10.3, build 20f81dd
```

## 2.7 stop

Docker Machineを停止します。

```bash
$ docker-machine stop docker-machine
Stopping "docker-machine"...
Machine "docker-machine" was stopped.
```

## 2.8 start

Docker Machineを起動します。
stop->startするとipアドレスが変わる場合がありますので、都度envサブコマンドで環境変数を設定しなおしたほうが良さそうです。

```bash
$ docker-machine start docker-machine
Starting "docker-machine"...
(docker-machine) Check network to re-create if needed...
(docker-machine) Waiting for an IP...
Machine "docker-machine" was started.
Waiting for SSH to be available...
Detecting the provisioner...
Started machines may have new IP addresses. You may need to re-run the `docker-machine env` command.
```

## 2.9 rm

Docker Machine自体を削除します。
VirtualBoxで試した場合は仮想Diskイメージを含めてすべてが消えましたので、大事なデータが有れば先にDocker Machine内から吸い出しておいてください。

```bash
$ docker-machine rm docker-machine
About to remove docker-machine
Are you sure? (y/n): y
Successfully removed docker-machine
$ docker-machine ls
NAME   ACTIVE   DRIVER   STATE   URL   SWARM   DOCKER   ERRORS
$ VBoxManage list vms
```

作るときは少し時間がかかりますが、消すときはさっくり消えました。
Vagrantのdestroyよりも速かったです。

今回はVirtualBox環境に作成したので今度はEC2にDocker Machineを作成してみたいと思います。

# X. 関連

- [Docker Machine でローカルマシン上に Docker ホストを構築する #docker - クリエーションライン株式会社](http://www.creationline.com/lab/11117)
- [Docker Machine リファレンス - Qiita](http://qiita.com/spesnova/items/073dd64a8a1d580d9ae9)
- [Get started with a local VM](https://docs.docker.com/machine/get-started/)
- [Docker Machine を使って VirtualBox に Dockerホストを立てる - Qiita](http://qiita.com/spesnova/items/038af6a8a4e401e3d2aa)