2014年11月4日 星期二

Docker on Ubuntu 14.04

Install Docker
# echo deb https://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list

# apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
# apt-get update
# apt-get install -y lxc-docker


Pull Ubuntu image
[with proxy]
# service docker stop
# HTTP_PROXY=[proxy] docker -d&
# docker pull ubuntu
[without proxy]
# docker pull ubuntu

Run a Docker Container
# docker run -i -t ubuntu /bin/bash

Frequently used commands
1.列出所有image
# docker images

2.列出所有運作中的container
# docker ps

3.列出所有container 包含暫停中或已結束的container
# docker ps -a

4.刪除container
# docker rm [container id]

5.刪除image
# docker rmi [image id]
note:如果image正在被某個container使用的話,就必須先刪除使用的container才能刪除image

6.build image
# docker build .
note:此指令必須跟Dockerfile同一層

6-1. build image時加入tag
# docker build -t [tag] .

6-2. build image不使用cache
# docker build --no-cache .
note:假設上一次build的時候發生錯誤(either Dockerfile寫錯 或是環境出錯等等),如果仍使用cache則會停留在出錯的狀態。另一個避免錯誤的方式是如6-3 不保留過程產生的container

6-3. build image但不保留過程中產生的container
# docker build --rm .

7. 啟動container
# docker run [image id or tag]

7-1. 啟動container with (I)nteractive and (T)ty
# docker run -t -i [image id or tag] /bin/bash
#note 啟動container並進入bash shell

7-2. 啟動container 並在背景執行
# docker run -i -t -d [image id or tag]
#note 要返回container 則執行 docker attach [container id] 回去

7-3. 啟動container 並掛載local 資料夾
# docker run -v /local/dir:/docker/dir [image id or tag]

7-4. 啟動container 並forward port
# docker run -p host_port:container_port -p host_port:container_port/udp [image id or tag]
#note -p 後面接一組 host_port:container_port,如果是udp則在後面加上/udp

7-5. 啟動container並與host時間同步
# docker run -v /etc/localtime:/etc/localtime:ro [image id or tag]

7-6. 啟動container並傳入環境變數
# docker run --env var_name=var_value [image id or tag]

7-7. 啟動container並給予tag
# docker run --name [tag] [image id or tag]

8. 跳出container
當進入container後,想要回到host的shell但不想結束container
ctrl+ p + q

9. 跳回container
# docker attach [container id]

10. 啟動container
# docker start [container id]
#note 當container是在exit狀態時,在attach必須先start container

11. Commit 變更
# docker commit -m "commit msg" -a "author" [container id] [repository]
#note -a和 repository非必要

12. 列出image/container 資訊
# docker inspect [image or container id]
#note 可以利用執行完docker inspect後檢查$?來判斷image or container是否已經存在

13. 匯出container
# docker export [container id] >image_name
#note 如果要順便壓縮的話docker export [container id] |gzip -c >image_name

14. 匯入container
# cat [image path] |docker import - [tag]
#note 匯入壓縮的image  # gzip -dc [image path] | docker import - tag

#15 限制container的memory 使用量
# docker run -m [memory size ex. -m 2g]
#note:如果有出現"WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.
則必須修改/etc/default/grub

GRUB_CMDLINE_LINUX=" 
更改成 
GRUB_CMDLINE_LINUX="cgroup_enable=memory swapaccount=1"
執行sudo update-grub 並重新開機