はじめてのDocker

[Docker](https://www.amazon.co.jp/Docker-Adrian-Mouat/dp/4873117763/)を第1章から第4章まで読んだのでメモ。

+ ホストOS

```
# cat /etc/redhat-release
CentOS release 6.7 (Final)
```

# Install

## install

```
# curl https://get.docker.com > install.sh
# chmod +x install.sh
# ./install.sh
```

## 起動

```
# /etc/init.d/docker restart
```

## 確認

```
# docker version
Client version: 1.7.1
Client API version: 1.19
Go version (client): go1.4.2
Git commit (client): 786b29d
OS/Arch (client): linux/amd64
Server version: 1.7.1
Server API version: 1.19
Go version (server): go1.4.2
Git commit (server): 786b29d
OS/Arch (server): linux/amd64
```

# 基本コマンド群

## 初めてのイメージの実行

+ Debianのイメージをダウンロードして`echo "Hello World"`を実行

```
# docker run debian echo "Hello World"
```
```
Hello world
```

## インタラクティブセッション

```
# docker run -i -t debian /bin/bash
```
```
root@a046a027a7bf:/# echo "Hello World"
Hello World
root@a046a027a7bf:/# exit
exit
```

## ホスト名を指定

```
# docker run -h CONTAINER -i -t debian /bin/bash
```
```
root@CONTAINER:/#
```

## ps

+ 実行中のコンテナ

```
# docker ps
```
```
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
4063d700d513        debian              "/bin/bash"         4 minutes ago       Up 4 minutes                            stupefied_poincare
```

+ 全コンテナ(終了したコンテナ含む)

```
# docker ps -a
```
```
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
4063d700d513        debian              "/bin/bash"         6 minutes ago       Up 6 minutes                                   stupefied_poincare
a046a027a7bf        debian              "/bin/bash"         8 minutes ago       Exited (0) 7 minutes ago                       compassionate_babbage
```

## inspect

```
# docker inspect stupefied_poincare
```
```
[
{
    "Id": "4063d700d513f6a730486dab9ad4c9311552525c5d0514d79ca5d1f85909d926",
    "Created": "2017-01-03T23:55:14.39212229Z",
    "Path": "/bin/bash",
    "Args": [],
    "State": {
        "Running": true,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 9150,
        "ExitCode": 0,
        "Error": "",
        "StartedAt": "2017-01-03T23:55:14.747637756Z",
        "FinishedAt": "0001-01-01T00:00:00Z"
    },
    "Image": "30a77eab48278f32a9f3ee32f8f5914428be48415fac8e24cb56af6a2ac39929",
    "NetworkSettings": {
        "Bridge": "",
        "EndpointID": "68d59ea164afd4ce912cea106246ccecbcd31f6884104bf7af694cd2372aa5a1",
        "Gateway": "172.17.42.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "HairpinMode": false,
        "IPAddress": "172.17.0.2",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "MacAddress": "02:42:ac:11:00:02",
        "NetworkID": "c082cc42f7b81f05841f37cde7a0e513b48426086e0c1b32e911f487f5744607",
        "PortMapping": null,
        "Ports": {},
        "SandboxKey": "/var/run/docker/netns/4063d700d513",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null
    },
    "ResolvConfPath": "/var/lib/docker/containers/4063d700d513f6a730486dab9ad4c9311552525c5d0514d79ca5d1f85909d926/resolv.conf",
    "HostnamePath": "/var/lib/docker/containers/4063d700d513f6a730486dab9ad4c9311552525c5d0514d79ca5d1f85909d926/hostname",
    "HostsPath": "/var/lib/docker/containers/4063d700d513f6a730486dab9ad4c9311552525c5d0514d79ca5d1f85909d926/hosts",
    "LogPath": "/var/lib/docker/containers/4063d700d513f6a730486dab9ad4c9311552525c5d0514d79ca5d1f85909d926/4063d700d513f6a730486dab9ad4c9311552525c5d0514d79ca5d1f85909d926-json.log",
    "Name": "/stupefied_poincare",
    "RestartCount": 0,
    "Driver": "devicemapper",
    "ExecDriver": "native-0.2",
    "MountLabel": "",
    "ProcessLabel": "",
    "Volumes": {},
    "VolumesRW": {},
    "AppArmorProfile": "",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": null,
        "ContainerIDFile": "",
        "LxcConf": [],
        "Memory": 0,
        "MemorySwap": 0,
        "CpuShares": 0,
        "CpuPeriod": 0,
        "CpusetCpus": "",
        "CpusetMems": "",
        "CpuQuota": 0,
        "BlkioWeight": 0,
        "OomKillDisable": false,
        "Privileged": false,
        "PortBindings": {},
        "Links": null,
        "PublishAllPorts": false,
        "Dns": null,
        "DnsSearch": null,
        "ExtraHosts": null,
        "VolumesFrom": null,
        "Devices": [],
        "NetworkMode": "bridge",
        "IpcMode": "",
        "PidMode": "",
        "UTSMode": "",
        "CapAdd": null,
        "CapDrop": null,
        "RestartPolicy": {
            "Name": "no",
            "MaximumRetryCount": 0
        },
        "SecurityOpt": null,
        "ReadonlyRootfs": false,
        "Ulimits": null,
        "LogConfig": {
            "Type": "json-file",
            "Config": {}
        },
        "CgroupParent": ""
    },
    "Config": {
        "Hostname": "CONTAINER",
        "Domainname": "",
        "User": "",
        "AttachStdin": true,
        "AttachStdout": true,
        "AttachStderr": true,
        "PortSpecs": null,
        "ExposedPorts": null,
        "Tty": true,
        "OpenStdin": true,
        "StdinOnce": true,
        "Env": [
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "/bin/bash"
        ],
        "Image": "debian",
        "Volumes": null,
        "VolumeDriver": "",
        "WorkingDir": "",
        "Entrypoint": null,
        "NetworkDisabled": false,
        "MacAddress": "",
        "OnBuild": null,
        "Labels": {}
    }
}
]
```

## diff

```
# docker diff compassionate_babbage
```
```
C /root
A /root/.bash_history
```

## logs

```
# docker logs compassionate_babbage
```
```
root@a046a027a7bf:/# echo "Hello World"
Hello World
root@a046a027a7bf:/# exit
exit
```

## rm

+ 停止したコンテナの全削除

```
# docker rm -v $(docker ps -aq -f status=exited)
```

# Dockerfile

## イメージの構築

```
# mkdir cowsay
# cd cowsay/
# touch Dockerfile
# vi Dockerfile
```
```
FROM debian:wheezy

MAINTAINER takaheraw
RUN apt-get update && apt-get install -y cowsay fortune
COPY entrypoint.sh /

ENTRYPOINT ["/entrypoint.sh"]
```
```
# vi entrypoint.sh
```
```
#!/bin/bash

if [ $# -eq 0 ]; then
  /usr/games/fortune | /usr/games/cowsay
else
  /usr/games/cowsay "$@"
fi
```

+ build

```
# docker build -t test/cowsay-dockerfile .
```

## コンテナ実行

+ 引数なし

```
# docker run test/cowsay-dockerfile
```
```
 _________________________________________
/ Swerve me? The path to my fixed purpose \
| is laid with iron rails, whereon my     |
| soul is grooved to run. Over unsounded  |
| gorges, through the rifled hearts of    |
| mountains, under torrents' beds,        |
| unerringly I rush!                      |
|                                         |
\ -- Captain Ahab, "Moby Dick"            /
 -----------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
```

+ 引数あり


```
# docker run test/cowsay-dockerfile Fuck
```
```
 ______
< Fuck >
 ------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
```

# レジストリ(Docker Hub)にアップロード

+ Docker Hubの自分のユーザ名からはじまるリポジトリ名でbuildしてpush

```
# docker build -t takaheraw/cowsay .
# docker push takaheraw/cowsay
```

https://hub.docker.com/r/takaheraw/cowsay/

# 公式イメージ(Redis)の利用

## pull

```
# docker pull redis
```

## バックグラウンド起動

```
# docker run --name myredis -d redis
```

+ 新しいコンテナを立ち上げ、２つのコンテナをリンク

```
# docker run --rm -it --link myredis:redis redis /bin/bash
root@16e217924a95:/data# redis-cli -h redis -p 6379
redis:6379> set "persistence" "test"
OK
redis:6379> save
OK
redis:6379> exit
root@16e217924a95:/data# exit
exit
```

## 永続化

```
# docker run --rm --volumes-from myredis -v $(pwd)/backup:/backup debian cp /data/dump.rdb /backup/
# ls backup
dump.rdb
```

## 停止・削除

```
# docker stop myredis
```
```
# docker rm -v myredis
```