Docker發(fā)端于一個名為dotcloud的開源項目;隨著編寫者不斷挖掘它的潛力,它迅速變成了一個炙手可熱的項目。它由GO語言編寫的,并且只支持Linux。它基于Linux容器(LxC)來創(chuàng)建一個虛擬環(huán)境。Docker不會通過建立獨有的操作系統(tǒng)、進程和對硬件進行模擬來創(chuàng)建屬于自己的虛擬機。請注意:虛擬環(huán)境VE(Virtual Environment)和虛擬機(VM)很不一樣。虛擬機是由虛擬工具或者模擬器(HyperV 、VMWare等)創(chuàng)建的,是一個全鏡像的主機源,其中包括操作系統(tǒng)、硬盤調整、網絡和虛擬進程。過于臃腫的結構吃掉了大量的硬盤空間同時拖慢了運行和開機速度。
一臺VE就像是輕量級的VM,它在已有的內核關于底層硬件的鏡像上建立一個可以用來運行應用的‘容器’。它也可以用來創(chuàng)建操作系統(tǒng),因為所謂的操作系統(tǒng)也不過是一個跑在內核上的應用而已??梢园袲ocker想象成LxC的一個強化版,只是具有以下LxC所不具有的特性:
LxC是一個Linux提供的收容功能接口,通過LxC提供的API和簡單的工具,使得Linux用戶可以簡單的創(chuàng)建和管理系統(tǒng)或者應用的空間。LXC容器
Docker通常用于如下場景:
web應用的自動化打包和發(fā)布;自動化測試和持續(xù)集成、發(fā)布;在服務型環(huán)境中部署和調整數據庫或其他的后臺應用;從頭編譯或者擴展現有的OpenShift或Cloud Foundry平臺來搭建自己的PaaS環(huán)境。
Docker實踐解決方案:
參考文檔:
Docker的安裝非常簡單,這里只介紹Ubuntu 14.04的安裝,其他發(fā)行版本的安裝可以參考官網手冊。
$ sudo apt-get update$ sudo apt-get install docker.io$ sudo ln -sf /usr/bin/docker.io /usr/local/bin/docker
獲取當前docker版本
$ sudo docker versionClient version: 1.1.1Client API version: 1.13Go version (client): go1.2.1Git commit (client): bd609d2Server version: 1.1.1Server API version: 1.13Go version (server): go1.2.1Git commit (server): bd609d2
$ sudo docker search ubuntu
$ sudo docker pull ubuntu # remote index 獲取ubuntu官方鏡像$ sudo docker images # 查看當前鏡像列表REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZEubuntu 13.10 5e019ab7bf6d 3 weeks ago 180 MBubuntu saucy 5e019ab7bf6d 3 weeks ago 180 MBubuntu 12.04 74fe38d11401 3 weeks ago 209.6 MB... ...
$ sudo docker run -i -t ubuntu:14.04 /bin/bash
注: ubuntu會有多個版本,通過指定tag來啟動特定的版本[image]:[tag]
$ sudo docker ps # 查看當前運行的容器, ps -a列出當前系統(tǒng)所有的容器CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES6c9129e9df10 ubuntu:14.04 /bin/bash 6 minutes ago Up 6 minutes cranky_babbage
Ctrl-D
or exit
Ctrl-p + Ctrl-q
docker attach CONTAINER ID
$ sudo docker # docker命令幫助Usage: docker [OPTIONS] COMMAND [arg...] -H=[unix:///var/run/docker.sock]: tcp://host:port to bind/connect to or unix://path/to/socket to useA self-sufficient runtime for linux containers.Commands: attach Attach to a running container # 當前shell下attach連接指定運行鏡像 build Build an image from a Dockerfile # 通過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 # 查看docker容器變化 events Get real time events from the server # 從docker服務獲取容器實時事件 export Stream the contents of a container as a tar archive # 導出容器的內容流作為一個tar歸檔文件[對應import] history Show the history of an image # 展示一個鏡像形成歷史 images List images # 列出系統(tǒng)當前鏡像 import Create a new filesystem image from the contents of a tarball # 從tar包中的內容創(chuàng)建一個新的文件系統(tǒng)映像[對應export] info Display system-wide information # 顯示系統(tǒng)相關信息 inspect Return low-level information on a container # 查看容器詳細信息 kill Kill a running container # kill指定docker容器 load Load an image from a tar archive # 從一個tar包中加載一個鏡像[對應save] login Register or Login to the docker registry server # 注冊或者登陸一個docker源服務器 logs Fetch the logs of a container # 輸出當前容器日志信息 port Lookup the public-facing port which is NAT-ed to PRIVATE_PORT # 查看映射端口對應的容器內部源端口 pause Pause all processes within a container # 暫停容器 ps List containers # 列出容器列表 pull Pull an image or a repository from the docker registry server # 從docker鏡像源服務器拉取指定鏡像或者庫鏡像 push Push an image or a repository to the docker registry server # 推送指定鏡像或者庫鏡像至docker源服務器 restart Restart a running container # 重啟運行的容器 rm Remove one or more containers # 移除一個或者多個容器 rmi Remove one or more images # 移除一個或多個鏡像[無容器使用該鏡像才可刪除,否則需刪除相關容器才可繼續(xù)或-f強制刪除] run Run a command in a new container # 在一個新的容器中運行一個命令 save Save an image to a tar archive # 保存一個鏡像為一個tar包[對應load] search Search for an image in the docker index # 在docker index中搜索鏡像 start Start a stopped containers # 啟動容器 stop Stop a running containers # 停止容器 tag Tag an image into a repository # 給源中鏡像打標簽 top Lookup the running processes of a container # 查看容器中運行的進程信息 unpause Unpause a paused container # 取消暫停容器 version Show the docker version information # 查看docker版本號 wait Block until a container stops, then print its exit code # 截取容器停止時的退出狀態(tài)值
docker選項幫助
$ sudo docker --helpUsage of docker: --api-enable-cors=false Enable CORS headers in the remote API # 遠程API中開啟CORS頭 -b, --bridge="" Attach containers to a pre-existing network bridge # 橋接網絡 use 'none' to disable container networking --bip="" Use this CIDR notation address for the network bridge's IP, not compatible with -b # 和-b選項不兼容,具體沒有測試過 -d, --daemon=false Enable daemon mode # daemon模式 -D, --debug=false Enable debug mode # debug模式 --dns=[] Force docker to use specific DNS servers # 強制docker使用指定dns服務器 --dns-search=[] Force Docker to use specific DNS search domains # 強制docker使用指定dns搜索域 -e, --exec-driver="native" Force the docker runtime to use a specific exec driver # 強制docker運行時使用指定執(zhí)行驅動器 -G, --group="docker" Group to assign the unix socket specified by -H when running in daemon mode use '' (the empty string) to disable setting of a group -g, --graph="/var/lib/docker" Path to use as the root of the docker runtime # 容器運行的根目錄路徑 -H, --host=[] The socket(s) to bind to in daemon mode # daemon模式下docker指定綁定方式[tcp or 本地socket] specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd. --icc=true Enable inter-container communication # 跨容器通信 --ip="0.0.0.0" Default IP address to use when binding container ports # 指定監(jiān)聽地址,默認所有ip --ip-forward=true Enable net.ipv4.ip_forward # 開啟轉發(fā) --iptables=true Enable Docker's addition of iptables rules # 添加對應iptables規(guī)則 --mtu=0 Set the containers network MTU # 設置網絡mtu if no value is provided: default to the default route MTU or 1500 if no default route is available -p, --pidfile="/var/run/docker.pid" Path to use for daemon PID file # 指定pid文件位置 -r, --restart=true Restart previously running containers # 重新啟動以前運行的容器 -s, --storage-driver="" Force the docker runtime to use a specific storage driver # 強制docker運行時使用指定存儲驅動 --selinux-enabled=false Enable selinux support # 開啟selinux支持 --storage-opt=[] Set storage driver options # 設置存儲驅動選項 --tls=false Use TLS; implied by tls-verify flags # 開啟tls --tlscacert="/root/.docker/ca.pem" Trust only remotes providing a certificate signed by the CA given here --tlscert="/root/.docker/cert.pem" Path to TLS certificate file # tls證書文件位置 --tlskey="/root/.docker/key.pem" Path to TLS key file # tls key文件位置 --tlsverify=false Use TLS and verify the remote (daemon: verify client, client: verify daemon) # 使用tls并確認遠程控制主機 -v, --version=false Print version information and quit # 輸出docker版本信息
官方鏡像源地址:registry.hub.docker.com
$ sudo docker searchUsage: docker search TERMSearch the docker index for images # 從docker鏡像主頁搜索鏡像 --automated=false Only show automated builds --no-trunc=false Don't truncate output -s, --stars=0 Only displays with at least xxx stars
示例:
$ sudo docker search -s 100 ubuntu # 查找star數至少為100的鏡像,找出只有官方鏡像start數超過100,默認不加s選項找出所有相關ubuntu鏡像NAME DESCRIPTION STARS OFFICIAL AUTOMATEDubuntu Official Ubuntu base image 425 [OK]
$ sudo docker info Containers: 7 # 容器個數Images: 102 # 鏡像個數Storage Driver: aufs # 存儲驅動,默認aufs Root Dir: /var/lib/docker/aufs # 根目錄 Dirs: 116Execution Driver: native-0.2 # 執(zhí)行驅動Kernel Version: 3.13.0-24-genericWARNING: No swap limit support
$ sudo docker pull # pull拉取鏡像Usage: docker pull NAME[:TAG]Pull an image or a repository from the registry$ sudo docker push # push推送指定鏡像Usage: docker push NAME[:TAG]Push an image or a repository to the registry
示例:
$ sudo docker pull ubuntu # 下載官方ubuntu docker鏡像,默認下載所有ubuntu官方庫鏡像$ sudo docker pull ubuntu:14.04 # 下載指定版本ubuntu官方鏡像
$ sudo docker push 192.168.0.100:5000/ubuntu# 推送鏡像庫到私有源[可注冊docker官方賬戶,推送到官方自有賬戶]$ sudo docker push 192.168.0.100:5000/ubuntu:14.04 # 推送指定鏡像到私有源
列出當前系統(tǒng)鏡像
$ sudo docker images -hUsage: docker images [OPTIONS] [NAME]List images -a, --all=false Show all images (by default filter out the intermediate image layers) # -a顯示當前系統(tǒng)的所有鏡像,包括過渡層鏡像,默認docker images顯示最終鏡像,不包括過渡層鏡像 -f, --filter=[] Provide filter values (i.e. 'dangling=true') --no-trunc=false Don't truncate output -q, --quiet=false Only show numeric IDs
示例:
$ sudo docker images # 顯示當前系統(tǒng)鏡像,不包括過渡層鏡像$ sudo docker images -a # 顯示當前系統(tǒng)所有鏡像,包括過渡層鏡像$ sudo docker images ubuntu # 顯示當前系統(tǒng)docker ubuntu庫中的所有鏡像REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZEubuntu 12.04 ebe4be4dd427 4 weeks ago 210.6 MBubuntu 14.04 e54ca5efa2e9 4 weeks ago 276.5 MBubuntu 14.04-ssh 6334d3ac099a 7 weeks ago 383.2 MB
刪除一個或者多個鏡像
$ sudo docker rmiUsage: docker rmi IMAGE [IMAGE...]Remove one or more images -f, --force=false Force removal of the image # 強制移除鏡像不管是否有容器使用該鏡像 --no-prune=false Do not delete untagged parents # 不要刪除未標記的父鏡像
$ sudo docker run Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]Run a command in a new container -a, --attach=[] Attach to stdin, stdout or stderr. -c, --cpu-shares=0 CPU shares (relative weight) # 設置cpu使用權重 --cidfile="" Write the container ID to the file # 把容器id寫入到指定文件 --cpuset="" CPUs in which to allow execution (0-3, 0,1) # cpu綁定 -d, --detach=false Detached mode: Run container in the background, print new container id # 后臺運行容器 --dns=[] Set custom dns servers # 設置dns --dns-search=[] Set custom dns search domains # 設置dns域搜索 -e, --env=[] Set environment variables # 定義環(huán)境變量 --entrypoint="" Overwrite the default entrypoint of the image # ? --env-file=[] Read in a line delimited file of ENV variables # 從指定文件讀取變量值 --expose=[] Expose a port from the container without publishing it to your host # 指定對外提供服務端口 -h, --hostname="" Container host name # 設置容器主機名 -i, --interactive=false Keep stdin open even if not attached # 保持標準輸出開啟即使沒有attached --link=[] Add link to another container (name:alias) # 添加鏈接到另外一個容器[這個會專門章節(jié)講解] --lxc-conf=[] (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1" -m, --memory="" Memory limit (format: <number><optional unit>, where unit = b, k, m or g) # 內存限制 --name="" Assign a name to the container # 設置容器名 --net="bridge" Set the Network mode for the container # 設置容器網絡模式 'bridge': creates a new network stack for the container on the docker bridge 'none': no networking for this container 'container:<name|id>': reuses another container network stack 'host': use the host network stack inside the container. Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure. -P, --publish-all=false Publish all exposed ports to the host interfaces # 自動映射容器對外提供服務的端口 -p, --publish=[] Publish a container's port to the host # 指定端口映射 format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort (use 'docker port' to see the actual mapping) --privileged=false Give extended privileges to this container # 提供更多的權限給容器 --rm=false Automatically remove the container when it exits (incompatible with -d) # 如果容器退出自動移除和-d選項沖突 --sig-proxy=true Proxify received signals to the process (even in non-tty mode). SIGCHLD is not proxied. # ? -t, --tty=false Allocate a pseudo-tty # 分配偽終端 -u, --user="" Username or UID # 指定運行容器的用戶uid或者用戶名 -v, --volume=[] Bind mount a volume (e.g., from the host: -v /host:/container, from docker: -v /container) # 掛載卷[這個會專門章節(jié)講解] --volumes-from=[] Mount volumes from the specified container(s) # 從指定容器掛載卷 -w, --workdir="" Working directory inside the container # 指定容器工作目錄
示例:
$ sudo docker images ubuntuREPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZEubuntu 14.04 e54ca5efa2e9 4 weeks ago 276.5 MB... ...$ sudo docker run -t -i -c 100 -m 512MB -h test1 -d --name="docker_test1" ubuntu /bin/bash # 創(chuàng)建一個cpu優(yōu)先級為100,內存限制512MB,主機名為test1,名為docker_test1后臺運行bash的容器a424ca613c9f2247cd3ede95adfbaf8d28400cbcb1d5f9b69a7b56f97b2b52e5$ sudo docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESa424ca613c9f ubuntu:14.04 /bin/bash 6 seconds ago Up 5 seconds docker_test1$ sudo docker attach docker_test1root@test1:/# pwd/root@test1:/# exitexit
關于cpu優(yōu)先級:
By default all groups have 1024 shares. A group with 100 shares will get a ~10% portion of the CPU time:
docker start
|stop
|kill
|restart
|pause
|unpause
|rm
|commit
|inspect
|logs
-t
選項可指定超時時間 -s
可以指定發(fā)送kill信號類型-t
選項可指定超時時間# Find IP address of container with ID <container_id> 通過容器id獲取ip$ sudo docker inspect <container_id> | grep IPAddress | cut -d ’"’ -f 4
無論如何,這些ip是基于本地系統(tǒng)的并且容器的端口非本地主機是訪問不到的。此外,除了端口只能本地訪問外,對于容器的另外一個問題是這些ip在容器每次啟動的時候都會改變。
Docker解決了容器的這兩個問題,并且給容器內部服務的訪問提供了一個簡單而可靠的方法。Docker通過端口綁定主機系統(tǒng)的接口,允許非本地客戶端訪問容器內部運行的服務。為了簡便的使得容器間通信,Docker提供了這種連接機制。
-P
使用時需要指定--expose
選項,指定需要對外提供服務的端口
$ sudo docker run -t -P --expose 22 --name server ubuntu:14.04
使用docker run -P
自動綁定所有對外提供服務的容器端口,映射的端口將會從沒有使用的端口池中(49000..49900)自動選擇,你可以通過docker ps
、docker inspect <container_id>
或者docker port <container_id> <port>
確定具體的綁定信息。
基本語法
$ sudo docker run -p [([<host_interface>:[host_port]])|(<host_port>):]<container_port>[/udp] <image> <cmd>
默認不指定綁定ip則監(jiān)聽所有網絡接口。
# Bind TCP port 8080 of the container to TCP port 80 on 127.0.0.1 of the host machine.$ sudo docker run -p 127.0.0.1:80:8080 <image> <cmd># Bind TCP port 8080 of the container to a dynamically allocated TCP port on 127.0.0.1 of the host machine.$ sudo docker run -p 127.0.0.1::8080 <image> <cmd># Bind TCP port 8080 of the container to TCP port 80 on all available interfaces of the host machine.$ sudo docker run -p 80:8080 <image> <cmd># Bind TCP port 8080 of the container to a dynamically allocated TCP port on all available interfaces$ sudo docker run -p 8080 <image> <cmd>
# Bind UDP port 5353 of the container to UDP port 53 on 127.0.0.1 of the host machine.$ sudo docker run -p 127.0.0.1:53:5353/udp <image> <cmd>
Docker uses Linux bridge capabilities to provide network connectivity to containers. The docker0 bridge interface is managed by Docker for this purpose. When the Docker daemon starts it :
Dokcer通過使用Linux橋接提供容器之間的通信,docker0橋接接口的目的就是方便Docker管理。當Docker daemon啟動時需要做以下操作:
$ sudo brctl show # brctl工具依賴bridge-utils軟件包bridge name bridge id STP enabled interfacesdocker0 8000.000000000000 no
$ sudo ifconfig docker0docker0 Link encap:Ethernet HWaddr xx:xx:xx:xx:xx:xxinet addr:172.17.42.1 Bcast:0.0.0.0 Mask:255.255.0.0
在容器運行時,每個容器都會分配一個特定的虛擬機口并橋接到docker0。每個容器都會配置同docker0 ip相同網段的專用ip地址,docker0 的IP地址被用于所有容器的默認網關。
$ sudo docker run -t -i -d ubuntu /bin/bash52f811c5d3d69edddefc75aff5a4525fc8ba8bcfa1818132f9dc7d4f7c7e78b4$ sudo brctl showbridge name bridge id STP enabled interfacesdocker0 8000.fef213db5a66 no vethQCDY1N
以上, docker0 扮演著52f811c5d3d6 container這個容器的虛擬接口vethQCDY1N interface橋接的角色。
Docker會嘗試尋找沒有被主機使用的ip段,盡管它適用于大多數情況下,但是它不是萬能的,有時候我們還是需要對ip進一步的規(guī)劃。Docker允許你管理docker0橋接或者通過-b
選項自定義橋接網卡,需要安裝bridge-utils
軟件包。
基本步驟如下:
# Stop Docker$ sudo service docker stop# Clean docker0 bridge and# add your very own bridge0$ sudo ifconfig docker0 down$ sudo brctl addbr bridge0$ sudo ifconfig bridge0 192.168.227.1 netmask 255.255.255.0# Edit your Docker startup file$ echo "DOCKER_OPTS=\"-b=bridge0\"" >> /etc/default/docker# Start Docker$ sudo service docker start# Ensure bridge0 IP is not changed by Docker$ sudo ifconfig bridge0bridge0 Link encap:Ethernet HWaddr xx:xx:xx:xx:xx:xxinet addr:192.168.227.1 Bcast:192.168.227.255 Mask:255.255.255.0# Run a container$ docker run -i -t ubuntu /bin/bash# Container IP in the 192.168.227/24 rangeroot@261c272cd7d5:/# ifconfig eth0eth0 Link encap:Ethernet HWaddr xx:xx:xx:xx:xx:xxinet addr:192.168.227.5 Bcast:192.168.227.255 Mask:255.255.255.0# bridge0 IP as the default gatewayroot@261c272cd7d5:/# route -nKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0.0.0 192.168.227.1 0.0.0.0 UG 0 0 0 eth0192.168.227.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
不同容器之間的通信可以借助于pipework
這個工具:
$ git clone https://github.com/jpetazzo/pipework.git$ sudo cp -rp pipework/pipework /usr/local/bin/
$ sudo apt-get install arping bridge-utils -y
Ubuntu14.04
# cat /etc/network/interfacesauto loiface lo inet loopbackauto eth0iface eth0 inet manualauto br0iface br0 inet staticaddress 10.0.128.219netmask 255.255.255.192gateway 10.0.128.254bridge_ports eth0bridge_stp offbridge_fd 0bridge_maxwait 0dns-nameservers 10.0.127.110dns-search intranet.123u.com
# ifup br0# Bash=$(docker run -i -d -t 10.0.128.219:5000/ubuntu:14.04 /bin/bash)# pipework br0 $Bash 10.0.128.223/26
為方便管理,我們需要對官方的鏡像做一些定制,我們可以構建私有的docker registry
The fastest way to get running:
apt-get install docker.io
docker run -p 5000:5000 registry
That will use the official image from the Docker index.[因為國內被墻的原因,速度比較慢,推薦第二種方式]
$ sudo apt-get install build-essential python-dev libevent-dev python-pip liblzma-dev$ git clone https://github.com/dotcloud/docker-registry.git$ cd docker-registry/$ cp config/config_sample.yml config/config.yml$ mkdir /data/registry -p$ pip install .
$ sudo gunicorn --access-logfile - --debug -k gevent -b 0.0.0.0:5000 -w 1 docker_registry.wsgi:application
生產環(huán)境可以通過如supervisord
創(chuàng)建8個workers,或者通過nginx和apache來管理,具體可以參考docker-registry readme。
$ sudo gunicorn -k gevent --max-requests 100 --graceful-timeout 3600 -t 3600 -b localhost:5000 -w 8 docker_registry.wsgi:application
$ docker tag 74fe38d11401 192.168.0.219:5000/ubuntu:12.04$ docker push 192.168.0.219:5000/ubuntu
docker管理數據的方式有兩種:
數據庫是一個或多個容器專門指定繞過Union File System
的目錄,為持續(xù)性或共享數據提供一些有用的功能:
你可以使用-v
選項添加一個數據卷,或者可以使用多次-v
選項為一個docker容器運行掛載多個數據卷。
$ sudo docker run --name data -v /data -t -i centos:6.4 /bin/bash# 創(chuàng)建數據卷綁定到到新建容器,新建容器中會創(chuàng)建/data數據卷bash-4.1# ls -ld /data/drwxr-xr-x 2 root root 4096 Jul 23 06:59 /data/bash-4.1# df -ThFilesystem Type Size Used Avail Use% Mounted on... ... ext4 91G 4.6G 82G 6% /data
創(chuàng)建的數據卷可以通過docker inspect
獲取宿主機對應路徑
$ sudo docker inspect data... ... "Volumes": { "/data": "/var/lib/docker/vfs/dir/151de401d268226f96d824fdf444e77a4500aed74c495de5980c807a2ffb7ea9" }, # 可以看到創(chuàng)建的數據卷宿主機路徑 "VolumesRW": { "/data1": true }... ...
-v
選項除了可以創(chuàng)建卷,也可以掛載當前主機的一個目錄到容器中。
$ sudo docker run --name web -v /source/:/web -t -i centos:6.4 /bin/bashbash-4.1# ls -ld /web/drwxr-xr-x 2 root root 4096 Jul 23 06:59 /web/bash-4.1# df -Th... ... ext4 91G 4.6G 82G 6% /webbash-4.1# exit
默認掛載卷是可讀寫的,可以在掛載時指定只讀
$ sudo docker run --rm --name test -v /source/:/test:ro -t -i centos:6.4 /bin/bash
如果你有一些持久性的數據并且想在容器間共享,或者想用在非持久性的容器上,最好的方法是創(chuàng)建一個數據卷容器,然后從此容器上掛載數據。
創(chuàng)建數據卷容器
$ sudo docker run -t -i -d -v /test --name test centos:6.4 /bin/bash
使用--volumes-from
選項在另一個容器中掛載/test卷
$ sudo docker run -t -i -d --volumes-from test --name test1 centos:6.4 /bin/bash
添加另一個容器
$ sudo docker run -t -i -d --volumes-from test --name test2 centos:6.4 /bin/bash
也可以繼承其它掛載有/test卷的容器
$ sudo docker run -t -i -d --volumes-from test1 --name test3 centos:6.4 /bin/bash
$ sudo docker run --volumes-from test -v $(pwd):/backup centos:6.4 tar cvf /backup/test.tar /testtar: Removing leading `/' from member namestar: /test/test.tar: file is the archive; not dumped/test//test/b/test/d/test/c/test/a
啟動一個新的容器并且從test
容器中掛載卷。然后我們掛載當前目錄$(pwd)
到容器中為backup,然后備份卷數據為test.tar,即備份數據存放在當前宿主機的所在路徑下。
$ ls # 當前目錄下產生了test卷的備份文件test.tartest.tar
你可以恢復給同一個容器或者另外的容器,新建容器并解壓備份文件到新的容器數據卷:
$ sudo docker run -t -i -d -v /test --name test2 centos:6.4 /bin/bash$ sudo docker run --volumes-from test2 -v $(pwd):/backup centos:6.4 tar xvf /backup/test.tar# 恢復之前的文件到新建卷中test/test/btest/dtest/ctest/a
之前介紹過通過端口映射連接容器中對外提供的服務。這是你與運行在容器中的服務和應用進行交互的方式之一。在本節(jié)中,會介紹同網絡端口方式訪問一樣好用的方式,即鏈接容器。docker容器具有一個鏈接系統(tǒng)允許多個容器連接在一起并且共享連接信息。docker鏈接將創(chuàng)建一個父子關系,其中父容器可以看到關于它子容器選擇的信息。
執(zhí)行docker鏈接依賴容器的名稱,在創(chuàng)建容器時,如果不指定容器的名字,則默認會自動創(chuàng)建一個名字。這種命名提供了兩個很有用的功能:
web
web
鏈接到容器db
可以通過--name
選項給容器自定義命名:
$ sudo docker run -d -t -i --name bash centos:6.4 bash$ sudo docker ps -lCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES70be821b7804 centos:6.4 bash About a minute ago Up About a minute bash
也可以通過docker inspect
獲取容器名
$ sudo docker inspect -f "{{ .Name }}" 70be821b7804/bash
注:容器名稱必須是唯一,意思是你只能命名一個叫`web`的容器。如果你想復用容器名,則必須在創(chuàng)建新的容器前通過`docker rm`刪除舊的容器。
鏈接允許容器間安全可見通信,使用--link
選項創(chuàng)建鏈接。
$ sudo docker run -d -t -i --name test1 centos:6.4 bash
創(chuàng)建一個容器鏈接到test1
容器
$ sudo docker run -d -t -i --name test2 --link test1:test1 centos:6.4 bash
--link name:alias
$ sudo docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES1966fe2a909c centos:6.4 bash 2 minutes ago Up 2 minutes test220f7f53b61df centos:6.4 bash 4 minutes ago Up 4 minutes test1,test2/test1
從上面命令輸出可以看出test2鏈接到test1容器的父/子關系。