New FAMILUG

The PyMiers

Saturday 21 December 2013

Docker - Giới thiệu Docker và sử dụng

Home page: http://docs.docker.io
Các bài viết khác về docker: http://www.familug.org/search/label/Docker

Giới thiệu về docker

Docker là gì?
docker, the Linux Container Runtime, runs Unix processes with strong guarantees of isolation across servers. Your software runs repeatably everywhere because its Container includes any dependencies.
Ngắn gọn lại, nếu các bạn biết đến các file portable trên Windows [1], thì docker cũng làm 1 nhiệm vụ tương tự như vậy, container docker chứa application đã deploy, sau khi `đóng gói` có thể mang đi chạy ở các môi trường khác nhau ở các máy khác nhau ( Hiện nay mới chỉ support Ubuntu, Arch, Fedora... ), mà ko mất công deploy lại.

Các thuật ngữ được sử dụng:

- File system: http://docs.docker.io/en/latest/terms/filesystem/
- Layer: http://docs.docker.io/en/latest/terms/layer/
- Image: http://docs.docker.io/en/latest/terms/image/
- Container: http://docs.docker.io/en/latest/terms/container/

Trong phạm vi bài giới thiệu, mình không đi quá sâu sẽ gây nhàm chán. Nên bạn muốn tìm hiểu thì vào link để đọc, document đã ghi khá rõ. Cơ bản thành phần cấu tạo nên Container được mô tả như hình dưới:



Cài đặt


Mình sử dụng trên Ubuntu 12.04, mặc định:

clouduser@backup-demo:~$ uname -a
Linux backup-demo 3.2.0-53-virtual #81-Ubuntu SMP Thu Aug 22 21:21:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
Docker làm việc tốt nhất trên kernel 3.8 nên cần upgrade.

# install the backported kernel 
sudo apt-get update 
sudo apt-get install linux-image-generic-lts-raring linux-headers-generic-lts-raring 
# reboot 
sudo reboot
clouduser@backup-demo:~$ uname  -a
Linux backup-demo 3.8.0-34-generic #49~precise1-Ubuntu SMP Wed Nov 13 18:05:00 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
Các bước cài đặt tiếp theo:

# Add key
sudo sh -c "wget -qO- https://get.docker.io/gpg | apt-key add -"

# Add Source list
sudo sh -c "echo deb http://get.docker.io/ubuntu docker main\ > /etc/apt/sources.list.d/docker.list"

sudo apt-get update 
sudo apt-get install lxc-docker
 
Kiểm tra process của docker đang chạy:

clouduser@backup-demo:~$ ps -ef | grep docker
root      2070  2069  0 02:48 ?        00:00:00 /usr/bin/docker -d
1000      2125   929  0 02:49 pts/0    00:00:00 grep --color=auto docker


Bạn đã có thể bắt đầu 'hello world' với docker: http://docs.docker.io/en/latest/examples/hello_world/
Hoặc tập sử dụng trên CLI online ở http://www.docker.io/gettingstarted/

 

Sử Dụng

Bạn cần sử dụng quyền sudo để thao tác với docker

docker help để list các option của docker.
clouduser@backup-demo:~$ docker help
Usage: docker [OPTIONS] COMMAND [arg...]
 -H=[unix:///var/run/docker.sock]: tcp://host:port to bind/connect to or unix://path/to/socket to use

A self-sufficient runtime for linux containers.

Commands:
    attach    Attach to a running container
    build     Build a container from a Dockerfile
    commit    Create a new image from a container's changes
    cp        Copy files/folders from the containers filesystem to the host path
    diff      Inspect changes on a container's filesystem
    events    Get real time events from the server
    export    Stream the contents of a container as a tar archive
    history   Show the history of an image
    images    List images
    import    Create a new filesystem image from the contents of a tarball
    info      Display system-wide information
    insert    Insert a file in an image
    inspect   Return low-level information on a container
    kill      Kill a running container
    load      Load an image from a tar archive
    login     Register or Login to the docker registry server
    logs      Fetch the logs of a container
    port      Lookup the public-facing port which is NAT-ed to PRIVATE_PORT
    ps        List containers
    pull      Pull an image or a repository from the docker registry server
    push      Push an image or a repository to the docker registry server
    restart   Restart a running container
    rm        Remove one or more containers
    rmi       Remove one or more images
    run       Run a command in a new container
    save      Save an image to a tar archive
    search    Search for an image in the docker index
    start     Start a stopped container
    stop      Stop a running container
    tag       Tag an image into a repository
    top       Lookup the running processes of a container
    version   Show the docker version information
    wait      Block until a container stops, then print its exit code





 Có rất nhiều Examples ở đây để thực hành: http://docs.docker.io/en/latest/examples/

Quản lý images/containers

List các images đang có:

docker images -a

List các containers:

docker ps -a

List các container đang chạy:

docker ps

Remove image:

docker rmi <image id>

Remove container:

docker rm <container id>

Dockerfile


Dockerfile là 1 file template để build image. Nếu coi việc build image tuần tự bằng tay giống việc gõ các lệnh bash thì có thể coi Dockerfile giống như 1 file bash vậy.

Cấu trúc Dockerfile rất đơn giản, chỉ có 10 hàm được dùng. Tra cứu các hàm tại đây: http://docs.docker.io/en/latest/use/builder/

Dùng Dockerfile build image


Nội dung của 1 Dockerfile để cài openssh-server trên ubuntu 12.04 image

clouduser@backup-demo:~/docker$ cat Dockerfile 

# FROM: base on this image
FROM ubuntu:12.04

# MAINTAINER: Dockerfile author
MAINTAINER Lam Dang Tung

# ENV: to set an environment variable
ENV USER root
ENV HOME /root

# RUN: run a command
RUN apt-get update
RUN apt-get install -y openssh-server 
RUN mkdir /var/run/sshd
RUN echo "root:123456" | chpasswd

# EXPOSE: exposes port for container
EXPOSE 22

# ENTRYPOINT: make container executable with command
ENTRYPOINT /usr/sbin/sshd -D

 cd đến folder chứa Dockerfile và dùng docker build -t <image tag> . để build image

image tag là lamdt/ssh
docker build -t lamdt/ssh .
Uploading context 10.24 kB
Step 1 : FROM ubuntu:12.04
Pulling repository ubuntu
8dbd9e392a96: Download complete
 ---> 8dbd9e392a96
Step 2 : MAINTAINER Lam Dang Tung
 ---> Running in 99ea761f56a8
 ---> 62e7555f00bd
Step 3 : ENV USER root
 ---> Running in 1f190f72706a
 ---> 6c558132b77f
Step 4 : ENV HOME /root
 ---> Running in 44c613dd2012
 ---> b58d9d956fb7
Step 5 : RUN apt-get update
 ---> Running in 25ed0a4b26ac
......

 ---> 3c82fd19a88a
Step 6 : RUN apt-get install -y openssh-server
 ---> Running in 6370346bc2bd

......
 ---> be807df511bd
Step 7 : RUN mkdir /var/run/sshd
 ---> Running in 161ff5c313d0
 ---> 13cc03230011
Step 8 : RUN echo "root:123456" | chpasswd
 ---> Running in bf827247b5f4
 ---> 8eedcdc3afe9
Step 9 : EXPOSE 22
 ---> Running in f70d33303fff
 ---> 47728b435ca6
Step 10 : ENTRYPOINT /usr/sbin/sshd -D
 ---> Running in 61b8e19d9574
 ---> 8a1bc4691754
Successfully built 8a1bc4691754

 

Kiểm tra kết quả:

# docker images -a
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
<none>              <none>              8eedcdc3afe9        23 seconds ago      181.7 MB
lamdt/ssh           latest              8a1bc4691754        23 seconds ago      181.7 MB
<none>              <none>              13cc03230011        23 seconds ago      181.7 MB
<none>              <none>              47728b435ca6        23 seconds ago      181.7 MB
<none>              <none>              be807df511bd        24 seconds ago      181.7 MB
<none>              <none>              3c82fd19a88a        30 seconds ago      157 MB
<none>              <none>              62e7555f00bd        31 seconds ago      128 MB
<none>              <none>              6c558132b77f        31 seconds ago      128 MB
<none>              <none>              b58d9d956fb7        31 seconds ago      128 MB
ubuntu              12.04               8dbd9e392a96        8 months ago        128 MB


# docker ps -a
CONTAINER ID        IMAGE               COMMAND                CREATED              STATUS              PORTS               NAMES
61b8e19d9574        47728b435ca6        /bin/sh -c /usr/sbin   56 seconds ago       Exit 0                                  stupefied_fermi     
f70d33303fff        8eedcdc3afe9        /bin/sh -c #(nop) EX   56 seconds ago       Exit 0                                  stoic_bohr          
bf827247b5f4        13cc03230011        /bin/sh -c echo "roo   56 seconds ago       Exit 0                                  clever_brattain     
161ff5c313d0        be807df511bd        /bin/sh -c mkdir /va   57 seconds ago       Exit 0                                  dreamy_lumiere      
6370346bc2bd        3c82fd19a88a        /bin/sh -c apt-get i   About a minute ago   Exit 0                                  jolly_thompson      
25ed0a4b26ac        b58d9d956fb7        /bin/sh -c apt-get u   About a minute ago   Exit 0                                  thirsty_pike        
44c613dd2012        6c558132b77f        /bin/sh -c #(nop) EN   About a minute ago   Exit 0                                  prickly_fermat      
1f190f72706a        62e7555f00bd        /bin/sh -c #(nop) EN   About a minute ago   Exit 0                                  dreamy_newton       
99ea761f56a8        ubuntu:12.04        /bin/sh -c #(nop) MA   About a minute ago   Exit 0                                  hopeful_heisenberg  
 

# docker ps
CONTAINER ID        IMAGE               COMMAND                CREATED              STATUS              PORTS               NAMES





docker ps cho thấy chưa có container nào chạy.
Các bước tiếp theo sẽ run image và assign port cho nó

# docker run -d -p 22 lamdt/ssh
be7238580063e1c5da400fe35b4d45497aac4d83850eb00d7a601098da500e13

# docker port be7238580063e1c5da400fe35b4d45497aac4d83850eb00d7a601098da500e13 22
0.0.0.0:49153

# docker ps
CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS                   NAMES
be7238580063        lamdt/ssh:latest    /bin/sh -c /usr/sbin   15 seconds ago      Up 15 seconds       0.0.0.0:49153->22/tcp   berserk_tesla

Giờ đã thấy container be7238580063 đang chạy và port 49153 của host được map với port 22 của container


Bạn có thể ssh vào container qua port 49153:

với user `root` và pass `123456` đã khai báo trong Dockerfile:


# ssh root@0.0.0.0 -p 49153
The authenticity of host '[0.0.0.0]:49153 ([0.0.0.0]:49153)' can't be established.
ECDSA key fingerprint is 5d:c0:af:8b:64:b2:c4:71:0c:35:5d:0e:29:9d:87:00.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[0.0.0.0]:49153' (ECDSA) to the list of known hosts.
root@0.0.0.0's password:
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.8.0-29-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.


root@be7238580063:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
25: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 2a:5c:64:3c:f7:5a brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.6/16 scope global eth0
    inet6 fe80::285c:64ff:fe3c:f75a/64 scope link
       valid_lft forever preferred_lft forever
root@be7238580063:~# uname -a
Linux be7238580063 3.8.0-29-generic #42~precise1-Ubuntu SMP Wed Aug 14 16:19:23 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
root@be7238580063:~# ping 8.8.8.8
-bash: ping: command not found
root@be7238580063:~# ls /
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  selinux  srv  sys  tmp  usr  var

 

Debug





Log của docker lưu lại /var/log/upstart/docker.log
Cần quyền root để xem log này.

Log level mặc định là INFO, muốn chuyển sang DEBUG cần tắt service và khởi động bằng tay với option -D

sudo initctl stop docker
sudo /usr/bin/docker -d -D


[1]: Định nghĩa: http://www.vn-zoom.com/f166/khai-niem-ve-phan-mem-portable-164121.html


TODO: packing container và chuyển sang chạy ở host khác




4 comments:

  1. sudo sh -c "echo deb http://get.docker.io/ubuntu docker main\ > /etc/apt/sources.list.d/docker.list"

    dấu \ ở sau main là cái hack gì thế :-o

    ReplyDelete
  2. > Cơ bản thành phần cấu tạo nên Container được mô tả như hình dưới:

    nhìn vào hình hem hiểu nó là gì lun :3

    ReplyDelete
  3. xem thêm các bài viết về docker ở: http://www.familug.org/search/label/Docker

    ReplyDelete