dockerで起動したUbuntu 12.04にsshを通す

簡単に手順をまとめると

  1. Dockerfileにimageのつくりかたを書く
  2. docker buildでimageをビルドする
  3. 2でつくったimageにdocker tagで名前をつける
  4. sshでつなぐためにIPアドレスを調べる
  5. docker runでcontainerを起動
  6. docker portで起動したcontainerの22番ポートはどのポートからNATされているか調べる
  7. 4,6で調べたIP, portにsshで接続する
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
$ cat Dockerfile
FROM ubuntu:12.04
MAINTAINER Ryota Arai "[email protected]"

RUN apt-get update
RUN apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN bash -c 'echo "root:root" | chpasswd'

CMD /usr/sbin/sshd -D
EXPOSE 22

$ docker build .
...
Step 5 : RUN mkdir /var/run/sshd
 ---> Running in e5e76f5de639
 ---> 92522331a6d7
Step 6 : RUN bash -c 'echo "root:root" | chpasswd'
 ---> Running in 7bdd5904cfdc
 ---> e93182966cc0
Step 7 : CMD /usr/sbin/sshd -D
 ---> Running in 1d978643a6e3
 ---> 455c7944ecc7
Step 8 : EXPOSE 22
 ---> Running in 3db08698551a
 ---> 88568c47ff16
Successfully built 88568c47ff16

$ docker tag 88568c47ff16 ryotarai/sshd
$ ip addr | grep -A4 docker0:
4: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
    link/ether 8a:cd:f7:fb:52:b0 brd ff:ff:ff:ff:ff:ff
    inet 172.16.42.1/24 scope global docker0
    inet6 fe80::f457:bff:fe76:ae7d/64 scope link
       valid_lft forever preferred_lft forever

$ ssh [email protected] -p $(docker port $(docker run -d ryotarai/sshd) 22)
The authenticity of host '[172.16.42.1]:49166 ([172.16.42.1]:49166)' can't be established.
ECDSA key fingerprint is 42:af:ab:c1:57:1c:a1:76:6f:ff:f6:b4:84:40:5a:dd.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[172.16.42.1]:49166' (ECDSA) to the list of known hosts.
[email protected]'s password:
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.8.0-26-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

-bash: warning: setlocale: LC_ALL: cannot change locale (en_US)
[email protected]:~#