Docker容器学习梳理--日常操作总结
?
使用Docker已有一段時間了,今天正好有空梳理下自己平時操作Docker時的一些命令和注意細(xì)節(jié):
Docker 命令幫助
$ sudo docker Commands:attach Attach to a running container --將終端依附到容器上1> 運行一個交互型容器[root@localhost ~]# docker run -i -t centos /bin/bash[root@f0a02b473067 /]# 2> 在另一個窗口上查看該容器的狀態(tài)[root@localhost ~]# docker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESd4a75f165ce6 centos "/bin/bash" 5 seconds ago Up 5 seconds cranky_mahavira3> 退出第一步中運行的容器[root@d4a75f165ce6 /]# exitexit4> 查看該容器的狀態(tài)[root@localhost ~]# docker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESd4a75f165ce6 centos "/bin/bash" 2 minutes ago Exited (0) 23 seconds ago cranky_mahavira可見此時容器的狀態(tài)是Exited,那么,如何再次運行這個容器呢?可以使用docker start命令5> 再次運行該容器[root@localhost ~]# docker start cranky_mahaviracranky_mahavira6> 再次查看該容器的狀態(tài)[root@localhost ~]# docker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESd4a75f165ce6 centos "/bin/bash" 6 minutes ago Up 29 seconds cranky_mahavira因為該容器是交互型的,但此刻我們發(fā)現(xiàn)沒有具體的終端可以與之交互,這時可使用attach命令。7> 通過attach命令進行交互[root@localhost ~]# docker attach cranky_mahavira[root@d4a75f165ce6 /]# build Build an image from a Dockerfile--通過Dockerfile創(chuàng)建鏡像commit Create a new image from a container's changes --通過容器創(chuàng)建本地鏡像注意:如果是要push到docker hub中,注意生成鏡像的命名[root@localhost ~]# docker commit centos_v1 centos:v168ad49c999496cff25fdda58f0521530a143d3884e61bce7ada09bdc22337638[root@localhost ~]# docker push centos:v1You cannot push a "root" repository. Please rename your repository to <user>/<repo> (ex: <user>/centos)用centos:v1就不行,因為它push到docker hub中時,是推送到相應(yīng)用戶下,必須指定用戶名。譬如我的用戶名是ivictor,則新生成的本地鏡像命名為:docker push victor/centos:v1,其中v1是tag,可不寫,默認(rèn)是latest cp Copy files/folders from a container to a HOSTDIR or to STDOUT--在宿主機和容器之間相互COPY文件cp的用法如下:Usage: docker cp [OPTIONS] CONTAINER:PATH LOCALPATH|-docker cp [OPTIONS] LOCALPATH|- CONTAINER:PATH如:容器mysql中/usr/local/bin/存在docker-entrypoint.sh文件,可如下方式copy到宿主機# docker cp mysql:/usr/local/bin/docker-entrypoint.sh /root修改完畢后,將該文件重新copy回容器# docker cp /root/docker-entrypoint.sh mysql:/usr/local/bin/ create Create a new container --創(chuàng)建一個新的容器,注意,此時,容器的status只是Created diff Inspect changes on a container's filesystem--查看容器內(nèi)發(fā)生改變的文件,以我的mysql容器為例[root@localhost ~]# docker diff mysqldbC /rootA /root/.bash_historyA /test1.txtA /test.tarA /test.txtC /runC /run/mysqldA /run/mysqld/mysqld.pidA /run/mysqld/mysqld.sock不難看出,C對應(yīng)的均是目錄,A對應(yīng)的均是文件events Get real time events from the server--實時輸出Docker服務(wù)器端的事件,包括容器的創(chuàng)建,啟動,關(guān)閉等。譬如:[root@localhost ~]# docker events2015-09-08T17:40:13.000000000+08:00 d2a2ef5ddb90b505acaf6b59ab43eecf7eddbd3e71f36572436c34dc0763db79: (from wordpress) create2015-09-08T17:40:14.000000000+08:00 d2a2ef5ddb90b505acaf6b59ab43eecf7eddbd3e71f36572436c34dc0763db79: (from wordpress) die2015-09-08T17:42:10.000000000+08:00 839866a338db6dd626fa8eabeef53a839e4d2e2eb16ebd89679aa722c4caa5f7: (from mysql) startexec Run a command in a running container--用于容器啟動之后,執(zhí)行其它的任務(wù)通過exec命令可以創(chuàng)建兩種任務(wù):后臺型任務(wù)和交互型任務(wù)后臺型任務(wù):docker exec -d cc touch 123 其中cc是容器名交互型任務(wù):[root@localhost ~]# docker exec -i -t cc /bin/bashroot@1e5bb46d801b:/# ls123 bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr varexport Export a container's filesystem as a tar archive --將容器的文件系統(tǒng)打包成tar文件有兩種方式(mysqldb為容器名):docker export -o mysqldb1.tar mysqldbdocker export mysqldb > mysqldb.tar history Show the history of an image--顯示鏡像制作的過程,相當(dāng)于dockfileimages List images --列出本機的所有鏡像import Import the contents from a tarball to create a filesystem image--根據(jù)tar文件的內(nèi)容新建一個鏡像,與之前的export命令相對應(yīng)[root@localhost ~]# docker import mysqldb.tar mysql:v1eb81de183cd94fd6f0231de4ff29969db822afd3a25841d2dc9cf3562d135a10[root@localhost ~]# docker imagesREPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZEmysql v1 eb81de183cd9 21 seconds ago 281.9 MB? ? ? ? ? ? ? 譬如下面一例:
? ? ? ? ? ? ? [root@localhost volume2]# docker ps
? ? ? ? ? ? ? CONTAINER ID ? IMAGE ? ? ? ? ? ? ? COMMAND ? ? ?CREATED ? ? ? ?STATUS ? ? ?PORTS ? ? NAMES
? ? ? ? ? ? ? 9cb07559cc17 ? docker.io/ubuntu ? ?"/bin/bash" ?22 hours ago ? Up 22 hours ? ? ? ? ? naughty_bartik
? ? ? ? ? ? ? [root@localhost volume2]# docker export gigantic_goldwasser > wanghui.tar
? ? ? ? ? ? ? [root@localhost volume2]# docker import wanghui.tar wanghui:v1
? ? ? ? ? ? ? sha256:b6cbbaf69a58149f337dcc439a21ed185dcdf96fd7f72ddf45e102d27f47c4ae
? ? ? ? ? ? ? [root@localhost volume2]# docker images
? ? ? ? ? ? ? REPOSITORY ? ?TAG ? IMAGE ID ? ? ? ?CREATED ? ? ? ? ? SIZE
? ? ? ? ? ? ? wanghui ? ? ? v1 ? ?b6cbbaf69a58 ? ?5 seconds ago ? ? 450.9 MB
? ? ? ? ? ? ? [root@localhost volume2]# docker run -i -t wanghui:v1 /bin/bash
? ? ? ? ? ? ? [root@78f4ac39972d /]# ps -ef
Docker option
Usage of docker:--api-enable-cors=false Enable CORS headers in the remote API # 遠(yuǎn)程 API 中開啟 CORS 頭-b, --bridge="" Attach containers to a pre-existing network bridge # 橋接網(wǎng)絡(luò)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 服務(wù)器--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í)行驅(qū)動器--fixed-cidr="" IPv4 subnet for fixed IPs (ex: 10.20.0.0/16)this subnet must be nested in the bridge subnet (which is defined by -b or --bip)-G, --group="docker" Group to assign the unix socket specified by -H when running in daemon modeuse '' (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 # 跨容器通信--insecure-registry=[] Enable insecure communication with specified registries (no certificate verification for HTTPS and enable HTTP fallback) (e.g., localhost:5000 or 10.20.0.0/16)--ip="0.0.0.0" Default IP address to use when binding container ports # 指定監(jiān)聽地址,默認(rèn)所有 ip--ip-forward=true Enable net.ipv4.ip_forward # 開啟轉(zhuǎn)發(fā)--ip-masq=true Enable IP masquerading for bridge's IP range--iptables=true Enable Docker's addition of iptables rules # 添加對應(yīng) iptables 規(guī)則--mtu=0 Set the containers network MTU # 設(shè)置網(wǎng)絡(luò) mtuif 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 文件位置--registry-mirror=[] Specify a preferred Docker registry mirror -s, --storage-driver="" Force the docker runtime to use a specific storage driver # 強制 docker 運行時使用指定存儲驅(qū)動--selinux-enabled=false Enable selinux support # 開啟 selinux 支持--storage-opt=[] Set storage driver options # 設(shè)置存儲驅(qū)動選項--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 并確認(rèn)遠(yuǎn)程控制主機-v, --version=false Print version information and quitDocker run指令
[root@localhost ~]# docker run --help: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] Run a command in a new container-a, --attach=[] Attach to STDIN, STDOUT or STDERR --add-host=[] Add a custom host-to-IP mapping (host:ip) 增加一個定制的'主機-IP'映射 --blkio-weight=0 Block IO (relative weight), between 10 and 1000 -c, --cpu-shares=0 CPU shares (relative weight) --cap-add=[] Add Linux capabilities 增加linux能力 --cap-drop=[] Drop Linux capabilities --cgroup-parent= Optional parent cgroup for the container --cidfile= Write the container ID to the file 把容器的ID寫入文件 --cpu-period=0 Limit CPU CFS (Completely Fair Scheduler) period --cpu-quota=0 Limit the CPU CFS quota --cpuset-cpus= CPUs in which to allow execution (0-3, 0,1) --cpuset-mems= MEMs in which to allow execution (0-3, 0,1) -d, --detach=false Run container in background and print container ID 在后臺運行容器并打印容器ID --device=[] Add a host device to the container 把一個主機設(shè)備添加到容器 --dns=[] Set custom DNS servers 設(shè)置定制的域名服務(wù)器 --dns-search=[] Set custom DNS search domains 設(shè)置定制的域名服務(wù)器的搜索域 -e, --env=[] Set environment variables 設(shè)置環(huán)境變量 --entrypoint= Overwrite the default ENTRYPOINT of the image 覆蓋鏡像的默認(rèn)進入點 --env-file=[] Read in a file of environment variables 讀入一個包含環(huán)境變量的文件 --expose=[] Expose a port or a range of ports 暴露一個端口、端口范圍 -h, --hostname= Container host name 容器的主機名 -i, --interactive=false Keep STDIN 標(biāo)準(zhǔn)輸入 --ipc= IPC namespace to use 使用的IPC命名空間 --pid= PID namespace to use 使用的PID命名空間 --uts= UTS namespace to use -l, --label=[] Set meta data on a container 在容器上,設(shè)置元數(shù)據(jù) --label-file=[] Read in a line delimited file of labels --link=[] Add link to another container 添加一個到另一個容器的連接 --log-driver= Logging driver for container 容器的日志驅(qū)動 --log-opt=[] Log driver options --lxc-conf=[] Add custom lxc options 添加定制的lxc選項 -m, --memory= Memory limit 內(nèi)存限制 --mac-address= Container MAC address (e.g. 92:d0:c6:0a:29:33) 容器的MAC地址 --memory-swap= Total memory (memory + swap), '-1' to disable swap 容器的總內(nèi)存(物理內(nèi)容+交換區(qū)) --name= Assign a name to the container 為容器分配一個名字 --net=bridge Set the Network mode for the container 為容器設(shè)置網(wǎng)絡(luò)模式 --oom-kill-disable=false Disable OOM Killer -p, --publish-all=false Publish all exposed ports to random ports 小寫P,表示容器端口映射到宿主機的具體端口上,比如 -p 8080:80 -P, --publish=[] Publish a container's port(s) to the host 大寫P,表示容器端口映射到宿主機的任意一個端口上,比如 -P --privileged=false Give extended privileges to this container 賦予容器擴展權(quán)限 --read-only=false Mount the container's root filesystem as read only 以只讀的方式裝載容器的根文件系統(tǒng) --restart=no Restart policy to apply when a container exits --rm=false Automatically remove the container when it exits 當(dāng)容器存在時,自動移除容器 --security-opt=[] Security Options 安全選項 --sig-proxy=true Proxy received signals to the process -t, --tty=false Allocate a pseudo-TTY 分配一個偽終端 -u, --u-user= Username or UID (format: <name|uid>[:<group|gid>]) --ulimit=[] Ulimit options -v, --volume=[] Bind mount a volume --volumes-from=[] Mount volumes from the specified container(s) -w, --workdir= Working directory inside the container-------------------------------------------- 當(dāng)運行docker run命令時,Docker會啟動一個進程,并為這個進程分配其獨占的文件系統(tǒng)、網(wǎng)絡(luò)資源和以此進程為根進程的進程組。在容器啟動時,鏡像可能已經(jīng)定義了要運行的二進制文件、暴露的網(wǎng)絡(luò)端口等,但是用戶可以通過docker run命令重新定義(docker run可以控制一個容器運行時的行為,它可以覆蓋docker build在構(gòu)建鏡像時的一些默認(rèn)配置),這也是為什么run命令相比于其它命令有如此多的參數(shù)的原因。 使用方法: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]OPTIONS總起來說可以分為兩類: a)設(shè)置運行方式:決定容器的運行方式,前臺執(zhí)行還是后臺執(zhí)行;設(shè)置containerID;設(shè)置網(wǎng)絡(luò)參數(shù);設(shè)置容器的CPU和內(nèi)存參數(shù);設(shè)置權(quán)限和LXC參數(shù); b)設(shè)置鏡像的默認(rèn)資源,也就是說用戶可以使用該命令來覆蓋在鏡像構(gòu)建時的一些默認(rèn)配置。docker run [OPTIONS]可以讓用戶完全控制容器的生命周期,并允許用戶覆蓋執(zhí)行docker build時所設(shè)定的參數(shù),甚至也可以修改本身由Docker所控制的內(nèi)核級參數(shù)。Operator exclusive options 當(dāng)執(zhí)行docker run時可以設(shè)置以下參數(shù):1.Detached vs ForegroundDetached (-d)- Foreground2.Container IdentificationName (--name)- PID Equivalent3.IPC Setting4.Network Settings5.Clean Up (--rm)6.Runtime Constraints on CPU and Memory7.Runtime Privilege, Linux Capabilities, and LXC Configuration---------------------------------------------------------------------------------------------- 1.Detached vs foreground 當(dāng)我們啟動一個容器時,首先需要確定這個容器是運行在前臺還是運行在后臺。-d=false, 沒有附加標(biāo)準(zhǔn)輸入、輸出、錯誤 ---- 運行在后臺Detached (-d) docker run -d-d=false--detach=false那么容器將會運行在后臺模式。 此時所有I/O數(shù)據(jù)只能通過網(wǎng)絡(luò)資源或者共享卷組來進行交互,因為容器不再監(jiān)聽你執(zhí)行docker run的這個終端命令行窗口。 但你可以通過執(zhí)行docker attach來重新附著到該容器的回話中。 需要注意的是,容器運行在后臺模式下,是不能使用--rm選項的。2.Foregroud 不指定-d參數(shù)(為明確給-d選項指定值,取默認(rèn)值false) --在前臺模式下Docker會在容器中啟動進程,同時將當(dāng)前的命令行窗口附著到容器的標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯誤中 --- 把當(dāng)前的命令行窗口附著到容器的標(biāo)準(zhǔn)輸入、輸出、錯誤上. 也就是說容器中所有的輸出都可以在當(dāng)前窗口中看到。甚至它都可以虛擬出一個TTY窗口,來執(zhí)行信號中斷。 這一切都是可以配置的: -a=[], --attach=[] 把容器的標(biāo)準(zhǔn)輸入、輸出、錯誤附著到當(dāng)前的命令行窗口 -t=false, --tty=false 分配一個偽終端 -i=false, --interactive=false 附著標(biāo)準(zhǔn)輸入到當(dāng)前命令行-------特別注意--------- 注意: -i 選項取默認(rèn)值(false) docker run 沒有-i選項,相當(dāng)于docker run -i=false,即非交互式運行 docker run -i 指定-i選項,即以交互式運行如果在執(zhí)行run命令時沒有指定-a參數(shù),那么Docker默認(rèn)會掛載所有標(biāo)準(zhǔn)數(shù)據(jù)流,包括輸入輸出和錯誤,你可以單獨指定掛載哪個標(biāo)準(zhǔn)流。 # docker run -a=[stdin, stdout] -i -t ubuntu /bin/bash如果要進行交互式操作(例如Shell腳本),那我們必須使用-i -t參數(shù)同容器進行數(shù)據(jù)交互。 但是當(dāng)通過管道同容器進行交互時,就不需要使用-t參數(shù),例如下面的命令: # echo test | docker run -i busybox catDocker容器識別
1.Name(--name) 可以通過三種方式為容器命名: 1)使用UUID長命名("f78375b1c487e03c9438c729345e54db9d20cfa2ac1fc3494b6eb60872e74778") 2)使用UUID短命令("f78375b1c487") 3)使用Name("evil_ptolemy")這個UUID標(biāo)示是由Docker deamon生成的。 如果你在執(zhí)行docker run時沒有指定--name,那么deamon會自動生成一個隨機字符串UUID。 但是對于一個容器來說有個name會非常方便,當(dāng)你需要連接其它容器時或者類似需要區(qū)分其它容器時,使用容器名稱可以簡化操作。無論容器運行在前臺或者后臺,這個名字都是有效的。PID equivalent 如果在使用Docker時有自動化的需求,你可以將containerID輸出到指定的文件中(PIDfile),類似于某些應(yīng)用程序?qū)⒆陨鞩D輸出到文件中,方便后續(xù)腳本操作。 --cidfile="": Write the container ID to the file2.Image[:tag] 當(dāng)一個鏡像的名稱不足以分辨這個鏡像所代表的含義時,你可以通過tag將版本信息添加到run命令中,以執(zhí)行特定版本的鏡像。例如:docker run ubuntu:14.04 [root@localhost ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE docker.io/uifd/ui-for-docker latest 312812aadc64 34 hours ago 8.096 MB docker.io/nginx latest 5e69fe4b3c31 5 days ago 182.5 MB 192.168.1.23:5000/tomcat7 latest 47c5123914a1 6 days ago 562.3 MB docker.io/ubuntu latest 0ef2e08ed3fa 4 weeks ago 130 MB docker.io/centos latest 67591570dd29 3 months ago 191.8 MB docker.io/tomcat latest ebb17717bed4 5 months ago 355.4 MB3.IPC Settings 默認(rèn)情況下,所有容器都開啟了IPC命名空間。--ipc="" : Set the IPC mode for the container,'container:<name|id>': reuses another container's IPC namespace'host': use the host's IPC namespace inside the containerIPC(POSIX/SysV IPC)命名空間提供了相互隔離的命名共享內(nèi)存、信號燈變量和消息隊列。共享內(nèi)存可以提高進程數(shù)據(jù)的交互速度。 共享內(nèi)存一般用在數(shù)據(jù)庫和高性能應(yīng)用(C/OpenMPI、C++/using boost libraries)上或者金融服務(wù)上。 如果需要容器中部署上述類型的應(yīng)用,那么就應(yīng)該在多個容器直接使用共享內(nèi)存了。---------------------------------------------------------------------------------------------- Network settings 默認(rèn)情況下,所有的容器都開啟了網(wǎng)絡(luò)接口,同時可以接受任何外部的數(shù)據(jù)請求。--dns=[] : Set custom dns servers for the container --net="bridge" : Set the Network mode for the container##在docker橋接上,為容器創(chuàng)建一個新的網(wǎng)絡(luò)棧 'bridge' : creates a new network stack for the container on the docker bridge'none' : no networking for this container 沒有為該容器配置網(wǎng)絡(luò)'container:<name|id>' : reuses another container network stack 重用另一個容器的網(wǎng)絡(luò)棧'host' : use the host network stack inside the container 在容器內(nèi)使用主機的網(wǎng)絡(luò)棧--add-host="" : Add a line to /etc/hosts (host:IP) 向容器/etc/hosts的文件中增加一行--mac-address="" : Sets the container's Ethernet device's MAC address 設(shè)置容器網(wǎng)卡的MAC地址你可以通過docker run --net=none來關(guān)閉網(wǎng)絡(luò)接口,此時將關(guān)閉所有網(wǎng)絡(luò)數(shù)據(jù)的輸入輸出,你只能通過STDIN、STDOUT或者files來完成I/O操作。 默認(rèn)情況下,容器使用主機的DNS設(shè)置,你也可以通過--dns來覆蓋容器內(nèi)的DNS設(shè)置。 同時Docker為容器默認(rèn)生成一個MAC地址,你可以通過--mac-address 12:34:56:78:9a:bc來設(shè)置你自己的MAC地址。Docker支持的網(wǎng)絡(luò)模式有: none 關(guān)閉容器內(nèi)的網(wǎng)絡(luò)連接 bridge 通過veth接口來連接容器,默認(rèn)配置。 host 允許容器使用host的網(wǎng)絡(luò)堆棧信息。注意:這種方式將允許容器訪問host中類似D-BUS之類的系統(tǒng)服務(wù),所以認(rèn)為是不安全的。 container 使用另外一個容器的網(wǎng)絡(luò)堆棧信息。----None模式---- 將網(wǎng)絡(luò)模式設(shè)置為none時,這個容器將不允許訪問任何外部router。 這個容器內(nèi)部只會有一個loopback接口,而且不存在任何可以訪問外部網(wǎng)絡(luò)的router。-----Bridge模式----- Docker默認(rèn)會將容器設(shè)置為bridge模式。 此時在主機上面將會存在一個docker0的網(wǎng)絡(luò)接口,同時會針對容器創(chuàng)建一對veth接口。 其中一個veth接口是在主機充當(dāng)網(wǎng)卡橋接作用,另外一個veth接口存在于容器的命名空間中,并且指向容器的loopback。 Docker會自動給這個容器分配一個IP,并且將容器內(nèi)的數(shù)據(jù)通過橋接轉(zhuǎn)發(fā)到外部。-----Host模式----- 當(dāng)網(wǎng)絡(luò)模式設(shè)置為host時,這個容器將完全共享host的網(wǎng)絡(luò)堆棧。 host所有的網(wǎng)絡(luò)接口將完全對容器開放。 容器的主機名也會存在于主機的hostname中。 這時,容器所有對外暴露的端口和對其它容器的連接,將完全失效。-----Container模式----- 當(dāng)網(wǎng)絡(luò)模式設(shè)置為Container時,這個容器將完全復(fù)用另外一個容器的網(wǎng)絡(luò)堆棧。同時使用時這個容器的名稱必須要符合下面的格式:--net container:<name|id>. 比如當(dāng)前有一個綁定了本地地址localhost的Redis容器。 如果另外一個容器需要復(fù)用這個網(wǎng)絡(luò)堆棧, 則需要如下操作: # docker run -d --name redis example/redis --bind 127.0.0.1//use the redis container's network stack to access localhost # docker run --rm -ti --net container:redis example/redis-cli -h 127.0.0.1管理/etc/hosts /etc/hosts文件中會包含容器的hostname信息,我們也可以使用--add-host這個參數(shù)來動態(tài)添加/etc/hosts中的數(shù)據(jù)。 # docker run -ti --add-host db-static:86.75.30.9 ubuntu cat /etc/hosts 172.17.0.22 09d03f76bf2c fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback 86.75.30.9 db-static ##容器啟動時添加進來的 地址到主機名映射---------------------------------------------------------------------------------------------- Clean up 默認(rèn)情況下,每個容器在退出時,它的文件系統(tǒng)也會保存下來,這樣一方面調(diào)試會方便些,因為你可以通過查看日志等方式來確定最終狀態(tài)。 另外一方面,你也可以保存容器所產(chǎn)生的數(shù)據(jù)。 但是當(dāng)你僅僅需要短暫的運行一個容器,并且這些數(shù)據(jù)不需要保存,你可能就希望Docker能在容器結(jié)束時自動清理其所產(chǎn)生的數(shù)據(jù)。 這個時候你就需要--rm這個參數(shù)了。<<<<<< 注意:--rm 和 -d不能共用 >>>>>> --rm=false: Automatically remove the container when it exits (incompatible with -d)Security configuration --security-opt="label:user:USER" : Set the label user for the container --security-opt="label:role:ROLE" : Set the label role for the container --security-opt="label:type:TYPE" : Set the label type for the container --security-opt="label:level:LEVEL" : Set the label level for the container --security-opt="label:disable" : Turn off label confinement for the container 關(guān)閉容器的標(biāo)簽限制 --secutity-opt="apparmor:PROFILE" : Set the apparmor profile to be applied to the container你可以通過--security-opt修改容器默認(rèn)的schema標(biāo)簽。 比如說,對于一個MLS系統(tǒng)來說(譯者注:MLS應(yīng)該是指Multiple Listing System),你可以指定MCS/MLS級別。使用下面的命令可以在不同的容器間分享內(nèi)容: # docker run --security-opt=label:level:s0:c100,c200 -i -t fedora bash如果是MLS系統(tǒng),則使用下面的命令: # docker run --security-opt=label:level:TopSecret -i -t rhel7 bash使用下面的命令可以在容器內(nèi)禁用安全策略: # docker run --security-opt=label:disable -i -t fedora bash如果你需要在容器內(nèi)執(zhí)行更為嚴(yán)格的安全策略,那么你可以為這個容器指定一個策略替代,比如你可以使用下面的命令來指定容器只監(jiān)聽Apache端口: # docker run --security-opt=label:type:svirt_apache_t -i -t centos bash注意:此時,你的主機環(huán)境中必須存在一個名為svirt_apache_t的安全策略。Runtime constraints on CPU and memory 下面的參數(shù)可以用來調(diào)整容器內(nèi)的性能。 -m="" : Memory limit (format: <number><optional unit>, where unit = b, k, m or g) -c=0 : CPU shares (relative weight)通過docker run -m可以調(diào)整容器所使用的內(nèi)存資源。 如果主機支持swap內(nèi)存,那么使用-m可以設(shè)定比主機物理內(nèi)存還大的值。 同樣,通過-c可以調(diào)整容器的CPU優(yōu)先級。 默認(rèn)情況下,所有的容器擁有相同的CPU優(yōu)先級和CPU調(diào)度周期,但你可以通過Docker來通知內(nèi)核給予某個或某幾個容器更多的CPU計算周期。比如,我們使用-c或者--cpu-shares =0啟動了C0、C1、C2三個容器,使用-c=512啟動了C3容器。 這時,C0、C1、C2可以100%的使用CPU資源(1024),但C3只能使用50%的CPU資源(512) 如果這個主機的操作系統(tǒng)是時序調(diào)度類型的,每個CPU時間片是100微秒,那么C0、C1、 C2將完全使用掉這100微秒,而C3只能使用50微秒。Runtime privilege, Linux capabilities, and LXC configuration --cap-add : Add Linux capabilities --cap-drop : Drop Linux capabilities --privileged=false : Give extended privileges to this container --device=[] : Allows you to run devices inside the container without the --privileged flag. --lxc-conf=[] : (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"默認(rèn)情況下,Docker的容器是沒有特權(quán)的,例如不能在容器中再啟動一個容器。這是因為默認(rèn)情況下容器是不能訪問任何其它設(shè)備的。但是通過"privileged",容器就擁有了訪問任何其它設(shè)備的權(quán)限。當(dāng)操作者執(zhí)行docker run --privileged時,Docker將擁有訪問主機所有設(shè)備的權(quán)限,同時Docker也會在apparmor或者selinux做一些設(shè)置,使容器可以容易的訪問那些運行在容器外部的設(shè)備。你可以訪問Docker博客來獲取更多關(guān)于--privileged的用法。同時,你也可以限制容器只能訪問一些指定的設(shè)備。下面的命令將允許容器只訪問一些特定設(shè)備: sudo docker run --device=/dev/snd:/dev/snd ...默認(rèn)情況下,容器擁有對設(shè)備的讀、寫、創(chuàng)建設(shè)備文件的權(quán)限。使用:rwm來配合--device,你可以控制這些權(quán)限。 # docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc Command (m for help): q# docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk /dev/xvdc You will not be able to write the partition table. Command (m for help): q# docker run --device=/dev/sda:/dev/xvdc:w --rm -it ubuntu fdisk /dev/xvdc crash....# docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk /dev/xvdc fdisk: unable to open /dev/xvdc: Operation not permitted使用--cap-add和--cap-drop,配合--privileged 默認(rèn)使用這兩個參數(shù)的情況下,容器擁有一系列的內(nèi)核修改權(quán)限,這兩個參數(shù)都支持all值,如果你想讓某個容器擁有除了MKNOD之外的所有內(nèi)核權(quán)限,那么可以執(zhí)行下面的命令: # docker run --cap-add=ALL --cap-drop=MKNOD ...如果需要修改網(wǎng)絡(luò)接口數(shù)據(jù),那么就建議使用--cap-add=NET_ADMIN,而不是使用--privileged。 # run -t -i --rm ubuntu:14.04 ip link add dummy0 type dummy RTNETLINK answers: Operation not permitted # run -t -i --rm --cap-add=NET_ADMIN ubuntu:14.04 ip link add dummy0 type dummy如果要掛載一個FUSE文件系統(tǒng),那么就需要--cap-add和--device了。 如果Docker守護進程在啟動時選擇了lxclxc-driver(docker -d --exec-driver=lxc),那么就可以使用--lxc-conf來設(shè)定LXC參數(shù)。 但需要注意的是,未來主機上的Docker deamon有可能不會使用LXC,所以這些參數(shù)有可能會包含一些沒有實現(xiàn)的配置功能。 這意味著,用戶在操作這些參數(shù)時必須要十分熟悉LXC。 特別注意:當(dāng)你使用--lxc-conf修改容器參數(shù)后,Docker deamon將不再管理這些參數(shù),那么用戶必須自行進行管理。 比如說,你使用--lxc-conf修改了容器的IP地址,那么在/etc/hosts里面是不會自動體現(xiàn)的,需要你自行維護。把當(dāng)前用戶加入到docker用戶組中 usermod -a -G docker $USER =============================== # docker commit -h Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]] Create a new image from a container's changes ##從一個容器的改變創(chuàng)建一個新的鏡像 -a, --author= Author (e.g., "John Hannibal Smith <hannibal@a-team.com>") -c, --change=[] Apply Dockerfile instruction to the created image --help=false Print usage -m, --message= Commit message -p, --pause=true Pause container during commit ============================# docker tag -h Usage: docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG] Tag an image into a repository ##給鏡像打標(biāo)簽入庫 -f, --force=false Force --help=false Print usage給容器打標(biāo)簽 docker tag 11662b14f5e0 ubuntu:jdk1.7以用戶grid_hd登錄容器 # docker run -it -u grid_hd ubuntu:hd-salve1給目錄下的所有子目錄增加執(zhí)行權(quán)限的腳本 #!/bin/bash find /mnt/sda4/docker/aufs -type d | while read dir dochmod +rx "$dir" done啟動一個docker容器在后臺運行 docker run -d IMAGE[:TAG] 命令 docker logs container_id ##打印該容器的輸出 [root@localhost ~]# docker run -d --name mytest docker.io/centos /bin/sh -c "while true; do echo hello world; sleep 2; done" 37738fe3d6f9ef26152cb25018df9528a89e7a07355493020e72f147a291cd17 [root@localhost ~]# docker logs mytest hello world hello world hello world hello worlddocker attach container_id ##附加該容器的標(biāo)準(zhǔn)輸出到當(dāng)前命令行 [root@localhost ~]# docker attach mytest hello world hello world hello world ....... 此時,Ctrl+C退出container(容器消失),按ctrl-p ctrl-q可以退出到宿主機,而保持container仍然在運行--------------------------------------------------------------- 另外,觀察以下幾點: commit container只會pause住容器,這是為了保證容器文件系統(tǒng)的一致性,但不會stop。如果你要對這個容器繼續(xù)做其他修改:你可以重新提交得到新image2,刪除次新的image1也可以關(guān)閉容器用新image1啟動,繼續(xù)修改,提交image2后刪除image1當(dāng)然這樣會很痛苦,所以一般是采用Dockerfile來build得到最終image,參考[] 雖然產(chǎn)生了一個新的image,并且你可以看到大小有100MB,但從commit過程很快就可以知道實際上它并沒有獨立占用100MB的硬盤空間,而只是在舊鏡像的基礎(chǔ)上修改,它們共享大部分公共的"片"。有四種不同的選項會影響容器守護進程的服務(wù)名稱: 1)-h HOSTNAME 或者 --hostname=HOSTNAME --設(shè)置容器的主機名,僅本機可見。 這種方式是寫到/etc/hostname ,以及/etc/hosts 文件中,作為容器主機IP的別名,并且將顯示在容器的bash中。 不過這種方式設(shè)置的主機名將不容易被容器之外可見。這將不會出現(xiàn)在 docker ps 或者 其他的容器的/etc/hosts 文件中。2)--link=CONTAINER_NAME:ALIAS --使用這個選項去run一個容器, 將在此容器的/etc/hosts文件中增加一個主機名ALIAS,這個主機名是名為CONTAINER_NAME 的容器的IP地址的別名。 這使得新容器的內(nèi)部進程可以訪問主機名為ALIAS的容器而不用知道它的IP。 --link= 關(guān)于這個選項的詳細(xì)討論請看: Communication between containers.3)--dns=IP_ADDRESS --設(shè)置DNS服務(wù)器的IP地址,寫入到容器的/etc/resolv.conf文件中。當(dāng)容器中的進程嘗試訪問不在/etc/hosts文件中的主機A 時,容器將以53端口連接到IP_ADDRESS這個DNS服務(wù)器去搜尋主機A的IP地址。4)--dns-search=DOMAIN --設(shè)置DNS服務(wù)器的搜索域,以防容器嘗試訪問不完整的主機名時從中檢索相應(yīng)的IP。這是寫入到容器的 /etc/resolv.conf文件中的。當(dāng)容器嘗試訪問主機 host,而DNS搜索域被設(shè)置為 example.com ,那么DNS將不僅去查尋host主機的IP,還去查詢host.example.com的 IP。在docker中,如果啟動容器時缺少以上最后兩種選項設(shè)置時,將使得容器的/etc/resolv.conf文件看起來和宿主主機的/etc/resolv.conf文件一致。這些選項將修改默認(rèn)的設(shè)置。注意一點:當(dāng)利用 docker run 來創(chuàng)建容器時,Docker 在后臺運行的標(biāo)準(zhǔn)操作包括:
1)檢查本地是否存在指定的鏡像,不存在就從公有倉庫下載 2)利用鏡像創(chuàng)建并啟動一個容器 3)分配一個文件系統(tǒng),并在只讀的鏡像層外面掛載一層可讀寫層 4)從宿主主機配置的網(wǎng)橋接口中橋接一個虛擬接口到容器中去 5)從地址池配置一個 ip 地址給容器 6)執(zhí)行用戶指定的應(yīng)用程序 7)執(zhí)行完畢后容器被終止簡單補充下.......
在ubuntu中安裝docker # sudo apt-get install docker.io查看docker的版本信息 # docker version查看安裝docker的信息 # docker info查看本機Docker中存在哪些鏡像 # docker images------------------------------------------------------- docker pull 拉取鏡像 docker push 推送指定鏡像示例: 下載官方 ubuntu docker 鏡像,默認(rèn)下載所有 ubuntu 官方庫鏡像 [root@localhost ~]# docker pull ubuntu下載指定版本 ubuntu 官方鏡像 [root@localhost ~]# docker pull ubuntu:14.04推送鏡像庫到私有源(可注冊 docker 官方賬戶,推送到官方自有賬戶) [root@localhost ~]# docker push 192.168.0.100:5000/ubuntu推送指定鏡像到私有源 [root@localhost ~]# docker push 192.168.0.100:5000/ubuntu:14.04------------------------------------------------------ 從 Docker Hub 搜索鏡像 # docker search ubuntu:14.04 示例: 查找star數(shù)至少為10的ubuntu鏡像(默認(rèn)是不加-s選項) [root@localhost ~]# docker search -s 10 ubuntu INDEX NAME DESCRIPTION STARS OFFICIAL AUTOMATED docker.io docker.io/ubuntu Ubuntu is a Debian-based Linux operating s... 5682 [OK] docker.io docker.io/rastasheep/ubuntu-sshd Dockerized SSH service, built on top of of... 75 [OK] docker.io docker.io/ubuntu-upstart Upstart is an event-based replacement for ... 70 [OK] docker.io docker.io/consol/ubuntu-xfce-vnc Ubuntu container with "headless" VNC sessi... 45 [OK] docker.io docker.io/ubuntu-debootstrap debootstrap --variant=minbase --components... 28 [OK] docker.io docker.io/torusware/speedus-ubuntu Always updated official Ubuntu docker imag... 27 [OK] docker.io docker.io/nickistre/ubuntu-lamp LAMP server on Ubuntu 16 [OK] docker.io docker.io/nuagebec/ubuntu Simple always updated Ubuntu docker images... 16 [OK] -------------------------------------------------------顯示一個鏡像的歷史 # docker history birdben/ubuntu:v1列出一個容器里面被改變的文件或者目 # docker diff birdben/ubuntu:v1從一個容器中取日志 # docker logs birdben/ubuntu:v1顯示一個運行的容器里面的進程信息 # docker top birdben/ubuntu:v1從容器里面拷貝文件/目錄到本地一個路徑 # docker cp ID:/container_path to_path -------------------------------------------------------------------------------------------- 查看容器的root用戶密碼 # docker logs <容器名orID> 2>&1 | grep '^User: ' | tail -n1 因為Docker容器啟動時的root用戶的密碼是隨機分配的。所以,通過這種方式就可以得到redmine容器的root用戶的密碼了。查看容器日志 # docker logs -f <容器名orID> ----------------------------------------------------------------------------------- 運行一個新容器,同時為它命名、端口映射、文件夾映射。以redmine鏡像為例 # docker run --name redmine -p 9003:80 -p 9023:22 -d -v /var/redmine/files:/redmine/files -v /var/redmine/mysql:/var/lib/mysql sameersbn/redmine一個容器連接到另一個容器 # docker run -i -t --name sonar -d -link mmysql:db tpires/sonar-server sonar 容器連接到mmysql容器,并將mmysql容器重命名為db。這樣,sonar容器就可以使用db的相關(guān)的環(huán)境變量了。檢查某一特定容器可以使用docker inspect命令,后面跟容器的名稱或唯一ID。 Docker自動創(chuàng)建的容器名稱同樣是不方便記憶的,所以最好在運行容器時使用--name參數(shù)為其指定一個名稱,命令格式為docker run --name=<yourname>。 # docker inspect App_Container使用logs命令查看守護式容器 可以通過使用docker logs命令來查看容器的運行日志,其中--tail選項可以指定查看最后幾條日志,而-t選項則可以對日志條目附加時間戳。使用-f選項可以跟蹤日志的輸出,直到手動停止。 docker logs [OPTIONS] CONTAINER # docker logs App_Container查看運行中容器內(nèi)的進程 docker top CONTAINER [ps OPTIONS] # docker top App_Container構(gòu)建自己的鏡像 # docker build -t <鏡像名> <Dockerfile路徑> 如Dockerfile在當(dāng)前路徑: # docker build -t xx/gitlab .重新查看container的stdout # 啟動top命令,后臺運行 $ ID=$(sudo docker run -d ubuntu /usr/bin/top -b) # 獲取正在running的container的輸出 $ sudo docker attach $ID top - 02:05:52 up 3:05, 0 users, load average: 0.01, 0.02, 0.05 Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie Cpu(s): 0.1%us, 0.2%sy, 0.0%ni, 99.7%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 373572k total, 355560k used, 18012k free, 27872k buffers Swap: 786428k total, 0k used, 786428k free, 221740k cached ^C$ $ sudo docker stop $ID后臺運行(-d)、并暴露端口(-p) # docker run -d -p 127.0.0.1:33301:22 centos6-ssh從Container中拷貝文件出來 # sudo docker cp 7bb0e258aefe:/etc/debian_version . 拷貝7bb0e258aefe中的/etc/debian_version到當(dāng)前目錄下。 注意:只要7bb0e258aefe沒有被刪除,文件命名空間就還在,可以放心的把exit狀態(tài)的container的文件拷貝出來列出當(dāng)前所有正在運行的容器
# docker ps # docker ps -a 為查看所有的容器,包括已經(jīng)停止的。 # docker ps -q 查找已運行的docker容器的ID # docker ps -a -q 查找所有的docker容器的ID # docker ps -l 列出最近一次啟動的容器查看容器的相關(guān)信息
# docker inspect CONTAINER_ID
顯示容器IP地址和端口號,如果輸出是空的說明沒有配置IP地址(不同的Docker容器可以通過此IP地址互相訪問)
# docker inspect --format='{{.NetworkSettings.IPAddress}}' CONTAINER_ID
保存對容器的修改
# docker commit -m "Added ssh from ubuntu14.04" -a "birdben" 6s56d43f627f3 birdben/ubuntu:v1
參數(shù):
-m參數(shù)用來來指定提交的說明信息;
-a可以指定用戶信息的;
6s56d43f627f3代表的時容器的id;
birdben/ubuntu:v1指定目標(biāo)鏡像的用戶名、倉庫名和 tag 信息。
構(gòu)建一個容器
# docker build -t="birdben/ubuntu:v1" .
參數(shù):
-t為構(gòu)建的鏡像制定一個標(biāo)簽,便于記憶/索引等
. 指定Dockerfile文件在當(dāng)前目錄下,也可以替換為一個具體的 Dockerfile 的路徑。
在docker中運行ubuntu鏡像
# docker run <相關(guān)參數(shù)> <鏡像 ID> <初始命令>
守護模式啟動
# docker run -it ubuntu:14.04
交互模式啟動
# docker run -it ubuntu:14.04 /bin/bash
指定端口號啟動
# docker run -p 80:80 birdben/ubuntu:v1
指定配置啟動
# sudo docker run -d -p 10.211.55.4:9999:22 birdben/ubuntu:v1 '/usr/sbin/sshd' -D
參數(shù):
-d:表示以“守護模式”執(zhí)行,日志不會出現(xiàn)在輸出終端上。
-i:表示以“交互模式”運行容器,-i 則讓容器的標(biāo)準(zhǔn)輸入保持打開
-t:表示容器啟動后會進入其命令行,-t 選項讓Docker分配一個偽終端(pseudo-tty)并綁定到容器的標(biāo)準(zhǔn)輸入上
-v:表示需要將本地哪個目錄掛載到容器中,格式:-v <宿主機目錄>:<容器目錄>,-v 標(biāo)記來創(chuàng)建一個數(shù)據(jù)卷并掛載到容器里。在一次 run 中多次使用可以掛載多個數(shù)據(jù)卷。
-p:表示宿主機與容器的端口映射,此時將容器內(nèi)部的 22 端口映射為宿主機的 9999 端口,這樣就向外界暴露了 9999 端口,可通過 Docker 網(wǎng)橋來訪問容器內(nèi)部的 22 端口了。
注意:
這里使用的是宿主機的 IP 地址:10.211.55.4,與對外暴露的端口號 9999,它映射容器內(nèi)部的端口號 22。ssh外部需要訪問:ssh root@10.211.55.4 -p 9999
不一定要使用“鏡像 ID”,也可以使用“倉庫名:標(biāo)簽名”
根據(jù)鏡像啟動容器的時候,如果鏡像的TAG是latest,那么就直接跟鏡像名就行了;如果TAG不是latest,那么鏡像后面要跟上這個TAG標(biāo)識。如下:
[root@linux-node2 ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest 0ef2e08ed3fa 2 weeks ago 130 MB centos7 7.3.1611 d5ebea14da54 3 weeks ago 311 MB由于ubuntu鏡像的TAG標(biāo)識是latest,那么容器啟動的時候,鏡像后面的TAG信息可以省略。 [root@linux-node2 ~]# docker run -i -t ubuntu /bin/bash 但是centos7鏡像的TAG標(biāo)識不是latest,所以容器啟動的時候必須要跟上這個TAG信息。 [root@linux-node2 ~]# docker run -i -t centos7:7.3.1611 /bin/bash [root@2ba57568e836 /]# cat /etc/redhat-release CentOS Linux release 7.3.1611 (Core)不跟TAG的話,就會報錯 [root@linux-node2 ~]# docker run -i -t centos7 /bin/bash Unable to find image 'centos7:latest' locally Pulling repository docker.io/library/centos7 docker: Error: image library/centos7:latest not found. See 'docker run --help'.docker運行一個容器必須是基于鏡像來進行的,一旦容器啟動了,我們就可以登錄到容器中,安裝自己所需的軟件或應(yīng)用程序。
啟動容器的命令中必須跟一個鏡像,啟動容器后執(zhí)行的命令必須放在鏡像后面,如下,/bin/bash必須放在鏡像名稱的后面:
注意:創(chuàng)建應(yīng)用容器的時候,一般會做端口映射,這樣是為了讓外部能夠訪問這些容器里的應(yīng)用。可以通過-P或-p參數(shù)來指定端口映射
1)當(dāng)使用-p標(biāo)記時,可以指定端口映射,即容器端口映射到宿主機的對應(yīng)端口。可以用多個-p指定多個端口映射關(guān)系。如下: [root@localhost ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE docker.io/redis latest e4a35914679d 2 weeks ago 182.9 MB[root@localhost ~]# docker run --name myredis -p 63799:6379 -d docker.io/redis f5d5ff51ace01c5f26fcd65a6ca4853f8556a333c812576123ed71fd3d405737[root@localhost ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f5d5ff51ace0 docker.io/redis "docker-entrypoint.sh" 6 seconds ago Up 5 seconds 0.0.0.0:63799->6379/tcp myredis[root@localhost ~]# docker run --rm -it --name myredis2 --link myredis:redisdb docker.io/redis /bin/bash root@16b660ff9f65:/data# redis-cli -h redisdb -p 6379 redisdb:6379> ping PONG redisdb:6379> set test linux OK redisdb:6379>在別的機器上通過訪問本機的63799端口連接這個容器的redis [root@linux-node2 ~]# redis-cli -h 192.168.1.23 -p 63799 192.168.1.23:63799> get test "linux" 192.168.1.23:63799> ------------------------------------------------------------------------------------------ 可以使用多個-p映射多個端口 [root@localhost ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE centos7 7.3.1611 d5ebea14da54 3 weeks ago 311 MB[root@localhost ~]# docker run -i -t -p 20022:22 -p 8088:80 centos7:7.3.1611 /bin/bash [root@1a7a949e2f41 /]# ------------------------------------------------------------------------------------------2)當(dāng)使用-P標(biāo)記時,Docker 會隨機映射一個 49000~49900 的端口到內(nèi)部容器開放的網(wǎng)絡(luò)端口。如下: [root@localhost ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE docker.io/redis latest e4a35914679d 2 weeks ago 182.9 MB[root@localhost ~]# docker run --name myredis -P -d docker.io/redis 805d0e21e531885aad61d3e82395210b50621f1991ec4b7f9a0e25c815cc0272[root@localhost ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 805d0e21e531 docker.io/redis "docker-entrypoint.sh" 4 seconds ago Up 3 seconds 0.0.0.0:32768->6379/tcp myredis從上面的結(jié)果中可以看出,本地主機的32768端口被映射到了redis容器的6379端口上,也就是說訪問本機的32768端口即可訪問容器內(nèi)redis端口。測試看下,登陸redis容器,隨意寫個數(shù)據(jù) [root@localhost ~]# docker run --rm -it --name myredis2 --link myredis:redisdb docker.io/redis /bin/bash root@be44d955d6f4:/data# redis-cli -h redisdb -p 6379 redisdb:6379> set wangshibo huanqiu OK redisdb:6379> 在別的機器上通過上面映射的端口32768連接這個容器的redis [root@linux-node2 ~]# redis-cli -h 192.168.1.23 -p 32768 192.168.1.23:32768> get wangshibo "huanqiu"start 啟動容器(多個容器,后面就跟多個容器id)
# docker start 117843ade696117843ade696
stop 停止正在運行的容器(多個容器,后面就跟多個容器id)(在容器里面按ctrl+d組合鍵,也會退出當(dāng)前容器)
# docker stop 117843ade696117843ade696
restart 重啟容器(多個容器,后面就跟多個容器id)
# docker restart 117843ade696117843ade696
刪除容器和鏡像
rm 刪除容器(刪除一個或多個,多個之間用空格隔開) # docker rm 117843ade696117843ade696殺死所有running狀態(tài)的容器 # docker kill $(docker ps -a -q) # docker rm $(docker ps -a -q) ----------------------------------------------------------------------------------- rmi 刪除鏡像(刪除一個或多個,多個之間用空格隔開) # docker rmi ed9c93747fe1Deleted刪除所有未打tag的鏡像 # docker rmi $(docker images -q | awk '/^<none>/ { print $3 }')刪除所有鏡像 # docker rmi $(docker images -q)根據(jù)格式刪除所有鏡像 # docker rm $(docker ps -qf status=exited)登錄Docker Hub中心
# docker login
發(fā)布上傳image(push)
# docker push birdben/ubuntu:v1
Docker本機和容器之間的文件拷貝:
1)將本機的/root/test.file文件傳輸?shù)絀D為7bb0e258aefe的容器里的/mnt/wang目錄下 # docker cp /root/test.file 7bb0e258aefe:/mnt/wang/2)拷貝ID為7bb0e258aefe的容器里的/var/id.list文件到本機的/opt下 # docker cp 7bb0e258aefe:/var/id.list /opt/ 實例如下: [root@linux-node2 ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c7bd050b0a23 centos "/bin/bash" 2 hours ago Up 2 hours small_almeida eaf66f1e43ab centos "/sbin/init" 7 weeks ago Up 7 weeks 0.0.0.0:8888->8080/tcp hungry_khorana[root@linux-node2 ~]# docker exec -it eaf66f1e43ab /bin/bash [root@eaf66f1e43ab /]# cd /mnt/ [root@eaf66f1e43ab mnt]# ls [root@eaf66f1e43ab mnt]# mkdir test-haha [root@eaf66f1e43ab mnt]# cd test-haha [root@eaf66f1e43ab test-haha]# touch a b c [root@eaf66f1e43ab test-haha]# pwd /mnt/test-haha [root@eaf66f1e43ab test-haha]# ls a b c [root@eaf66f1e43ab test-haha]#然后拷貝容器文件出來 [root@linux-node2 ~]# docker cp eaf66f1e43ab:/mnt/test-haha /opt/ [root@linux-node2 ~]# ls /opt/test-haha/ a b c鏡像的存出和載入(可以將本機下載的鏡像導(dǎo)出,然后將導(dǎo)出文件上傳到別的機器上,在別的機器上進行鏡像導(dǎo)入)
1)如果要導(dǎo)出鏡像到本地文件,可以使用 docker save命令。 拉取鏡像 [root@linux-node2 ~]# docker pull ubuntu:14.04 [root@linux-node2 ~]# docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE ubuntu 14.04 c4ff7513909d 5 weeks ago 225.4 MB導(dǎo)出鏡像 [root@linux-node2 ~]# docker save ubuntu:14.04 > /opt/ubuntu_14.04.tar.gz 或者: [root@linux-node2 ~]# docker save -o /opt/ubuntu_14.04.tar.gz ubuntu:14.042)將上面的鏡像導(dǎo)出文件上傳到linux-node1機器上,然后在linux-node1機器上使用docker load命令載入這個鏡像 [root@linux-node1 ~]# docker load < /opt/ubuntu_14.04.tar.gz 或者: [root@linux-node1 ~]# docker load --input ubuntu_14.04.tar實例如下: [root@linux-node2 opt]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE centos7 7.3.1611 1d7e06aab5db 24 hours ago 264.7 MB nginx 1.9 c8c29d842c09 9 months ago 182.7 MB [root@linux-node2 opt]# docker save nginx:1.9 > /opt/nginx:1.9.tar.gz [root@linux-node2 opt]# ls nginx:1.9.tar.gz [root@linux-node2 opt]# rsync -e "ssh -p22" -avpgolr /opt/nginx:1.9.tar.gz 192.168.1.23:/opt/登陸192.168.1.23 [root@localhost ~]# cd /opt/ [root@localhost opt]# ls nginx:1.9.tar.gz [root@localhost opt]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE docker.io/centos latest 980e0e4c79ec 5 months ago 196.7 MB docker.io/redis 2.8.19 dd9fe7db5236 22 months ago 110.7 MB導(dǎo)入nginx鏡像 [root@localhost opt]# docker load < /opt/nginx:1.9.tar.gz [root@localhost opt]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE docker.io/centos latest 980e0e4c79ec 5 months ago 196.7 MB nginx 1.9 c8c29d842c09 9 months ago 182.7 MB docker.io/redis 2.8.19 dd9fe7db5236 22 months ago 110.7 MB容器的導(dǎo)出和導(dǎo)入(可以依據(jù)導(dǎo)出的容器快照導(dǎo)入為鏡像,在本地或?qū)⑷萜骺煺瘴募蟼鞯絼e的機器上進行導(dǎo)入鏡像操作都可以)
1)導(dǎo)出容器 如果要導(dǎo)出本地某個容器,可以使用 docker export 命令。 [root@linux-node2 ~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5243af7921c5 centos "/bin/bash" 2 days ago Exited (0) 5 seconds ago sharp_saha[root@linux-node2 ~]# docker export 5243af7921c5 > /opt/centos.tar.gz [root@linux-node2 ~]# ls /opt/ centos.tar.gz這樣將導(dǎo)出上面的ID為5243af7921c5的容器快照到本地的/opt/centos.tar.gz文件了。2)導(dǎo)入容器快照 可以使用 docker import 從容器快照文件中再導(dǎo)入為鏡像為了測試效果,先刪除ID為5243af7921c5的容器,再導(dǎo)入 [root@linux-node2 ~]# docker rm 5243af7921c5 5243af7921c5[root@linux-node2 ~]# cat /opt/centos.tar.gz | docker import - test/centos:v1.0 sha256:d84d758c5cda4aced7cd24a4efefedb3d56076ae127133dac8ac79ca0bab3f3d 或者使用下面命令導(dǎo)入 [root@linux-node2 ~]# docker import /opt/centos.tar.gz test/centos:v1.0[root@linux-node2 ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE test/centos v1.0 d84d758c5cda 5 seconds ago 191.8 MB[root@linux-node2 ~]# docker run -t -i test/centos:v1.0 /bin/bash [root@5056db543cc2 /]# [root@linux-node2 ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5056db543cc2 test/centos:v1.0 "/bin/bash" 19 seconds ago Up 18 seconds tiny_dijkstra這個ID為5056db543cc2的新容器既是導(dǎo)入的上面的容器快照創(chuàng)建的溫馨提示: 用戶既可以使用docker load來導(dǎo)入鏡像存儲文件到本地鏡像庫,也可以使用docker import 來導(dǎo)入一個容器快照到本地鏡像庫。 這兩者的區(qū)別在于容器快照文件將丟棄所有的歷史記錄和元數(shù)據(jù)信息(即僅保存容器當(dāng)時的快照狀態(tài)),而鏡像存儲文件將保存完整記錄,體積也要大。 此外,從容器快照文件導(dǎo)入時可以重新指定標(biāo)簽等元數(shù)據(jù)信息。比如說我在A機器上有個nginx容器,現(xiàn)在要在B機器上啟動一個一模一樣的nginx容器(或者說將A機器上的nginx容器拿到B機器上),方法有下面兩種:
1)將A機器上將nginx容器提交為新的鏡像(docker commit),然后將這個鏡像導(dǎo)出并上傳到B機器上,最后在B機器上導(dǎo)入這個新鏡像并依據(jù)這個鏡像啟動容器,這個就和A機器上的nginx容器一樣了。 2)將A機器上的nginx容器做快照,然后從這個快照文件中導(dǎo)入為鏡像,將這個鏡像上傳到B機器上,最后在B機器上導(dǎo)入這個新鏡像并依據(jù)它啟動容器。在運行狀態(tài)中的容器內(nèi)再次啟動新的進程(docker exec)
雖然Docker鼓勵我們一個容器只運行一個服務(wù),但是當(dāng)我們需要對運行中的容器進行監(jiān)控、維護和管理時,通常需要為運行中的容器啟動新進程。 # docker exec [OPTIONS] CONTAINER COMMAND [ARG...] 這條命令與docker run極為相似,也可以使用-i、-t和-d等參數(shù)。 [root@linux-node2 ~]# docker exec -i -t App_Container /bin/bash示例如下: 創(chuàng)建一個tomcat容器(創(chuàng)建容器后,啟動容器的/bin/bash進程) [root@localhost ~]# docker run -t -i -d --name=tomcat --hostname=wangshibo --dns=8.8.8.8 -p 8888:8080 tomcat7 /bin/bash a5ab82945a88d16c51941c7fbc1e3f581823099835f96423c4fd19b44841b31c [root@localhost ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a5ab82945a88 tomcat7 "/bin/bash" 3 seconds ago Up 2 seconds 0.0.0.0:8888->8080/tcp tomcat在上面tomcat容器已經(jīng)啟動的狀態(tài)下,再在宿主機上啟動該容器中新的進程。(當(dāng)然也可以直接登陸容器內(nèi)啟動這個進程) [root@localhost ~]# docker exec tomcat /usr/local/tomcat7/bin/startup.sh //如果啟動后出現(xiàn)卡的情況,就ctrl+c,不影響啟動結(jié)果。 Tomcat started.登陸到該容器內(nèi)驗證,發(fā)現(xiàn)tomcat進程已經(jīng)通過上面的docker exec啟動了 [root@localhost ~]# docker start tomcat tomcat [root@localhost ~]# docker attach tomcat [root@wangshibo /]# ps -ef|grep tomcat root 40 1 19 09:17 ? 00:00:08 java -Djava.util.logging.config.file=/usr/local/tomcat7/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/usr/local/tomcat7/endorsed -classpath /usr/local/tomcat7/bin/bootstrap.jar:/usr/local/tomcat7/bin/tomcat-juli.jar -Dcatalina.base=/usr/local/tomcat7 -Dcatalina.home=/usr/local/tomcat7 -Djava.io.tmpdir=/usr/local/tomcat7/temp org.apache.catalina.startup.Bootstrap start root 77 1 0 09:17 ? 00:00:00 grep --color=auto tomcat-----------------------------------------------------------------------------------------------------------
一般來說,容器創(chuàng)建后的主機名都是隨機生成的一串字符。DNS也是默認(rèn)和宿主機一樣的(/etc/resolv.conf)
容器創(chuàng)建后,登陸容器是無法修改主機名或DNS配置的,會報錯說:需要root權(quán)限才能修改!
其實容器的主機名或DNS配置是可以在容器創(chuàng)建的時候手動指定的:
Docker容器登陸的方法:
具體參考:Docker容器學(xué)習(xí)梳理--容器登陸方法梳理(attach、exec、nsenter)
查看docker中對應(yīng)容器的IP
命令格式:docker inspect 容器ID |grep IPAddress比如查看ID為b220fabf815a的容器的ip [root@localhost ~]# docker inspect b220fabf815a|grep IPAddress"SecondaryIPAddresses": null,"IPAddress": "172.17.0.4","IPAddress": "172.17.0.4",或者使用"yum install net-tools",安裝后就可以使用ifconfig命令查看ip了======================================================================================= 準(zhǔn)確查看docker容器的ip地址[root@docker-test1 ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b5c97379265a centos "/bin/bash" 12 minutes ago Up 11 minutes kevinmy[root@docker-test1 ~]# docker inspect kevinmy ......"MacAddress": "02:42:ac:11:00:04","Networks": {"bridge": {"IPAMConfig": null,"Links": null,"Aliases": null,"NetworkID": "df0c8465aeb4663aa0abcaddc9c7ea205a7bbaa075e46db7476c85589471cfbc","EndpointID": "3d504eb397a27696857750bc2f5919faf4be8bb1947b10375bee55439f2d7ce4","Gateway": "172.17.0.1","IPAddress": "172.17.0.4","IPPrefixLen": 16,"IPv6Gateway": "","GlobalIPv6Address": "","GlobalIPv6PrefixLen": 0,"MacAddress": "02:42:ac:11:00:04"}}}} ][root@docker-test1 ~]# docker inspect kevinmy|grep IPAddress"SecondaryIPAddresses": null,"IPAddress": "172.17.0.4","IPAddress": "172.17.0.4",[root@docker-test1 ~]# docker inspect kevinmy|grep IPAddress|grep [1-9]"IPAddress": "172.17.0.4","IPAddress": "172.17.0.4",[root@docker-test1 ~]# docker inspect kevinmy|grep IPAddress|grep [1-9]|awk '{print $2}' "172.17.0.4", "172.17.0.4",[root@docker-test1 ~]# docker inspect kevinmy|grep IPAddress|grep [1-9]|awk '{print $2}'|sort|uniq "172.17.0.4",[root@docker-test1 ~]# docker inspect kevinmy|grep IPAddress|grep [1-9]|awk '{print $2}'|sort|uniq|awk -F'"' '{print $2}' 172.17.0.4docker inspect 命令:顯示更底層的容器或image信息(docker inspect images_id/container_id 查看鏡像或容器信息)
Usage: docker inspect CONTAINER|IMAGE [CONTAINER|IMAGE...]Return low-level information on a container or image -f,--format=""Format the output using the given go template. 默認(rèn)返回一個json字符串,更具結(jié)構(gòu)自行提取信息即可docker inspect命令用于獲取容器/鏡像的元數(shù)據(jù),其中-f參數(shù)可以用于獲取指定的數(shù)據(jù)。不過很多用戶容易被該特性的語法搞暈,并很少有人能將它的優(yōu)勢發(fā)揮出來(大部分人都是通過 grep 來獲取指定數(shù)據(jù),雖然有效但比較零散混亂)。本文將詳細(xì)介紹 -f 參數(shù),并給出一些例子來說明如何使用它。下面是針對ID為b220fabf815a的容器的相關(guān)inspect命令 [root@localhost ~]# docker inspect b220fabf815a顯示實例ip: # docker inspect --format='{{.NetworkSettings.IPAddress}}' $INSTANCE_ID [root@localhost ~]# docker inspect --format='{{.NetworkSettings.IPAddress}}' b220fabf815a 172.17.0.4也可以通過grep來獲取ip [root@localhost ~]# docker inspect b220fabf815a|grep IPAddress"SecondaryIPAddresses": null,"IPAddress": "172.17.0.4","IPAddress": "172.17.0.4",或者使用“yum install net-tools”,安裝后就可以使用ifconfig命令查看ip了 列出所有綁定的端口: # docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' $INSTANCE_ID [root@localhost ~]# docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' b220fabf815a22/tcp -> 20020 找出特殊的端口映射: 比如找出容器里22端口所映射的docker本機的端口: # docker inspect --format='{{(index (index .NetworkSettings.Ports "22/tcp") 0).HostPort}}' $INSTANCE_ID [root@localhost ~]# docker inspect --format='{{(index (index .NetworkSettings.Ports "22/tcp") 0).HostPort}}' b220fabf815a 20020特別注意一個細(xì)節(jié):
1)ubuntu14下的docker是沒有service服務(wù)。去除每次sudo運行docker命令,需要添加組: # Add the docker group if it doesn't already exist. $ sudo groupadd docker #改完后需要重新登陸用戶 $ sudo gpasswd -a ${USER} docker2)ubuntu14的febootstrap沒有-i命令3)Dockerfile中的EXPOSE、docker run --expose、docker run -p之間的區(qū)別 Dockerfile的EXPOSE相當(dāng)于docker run --expose,提供container之間的端口訪問。docker run -p允許container外部主機訪問container的端口---------------------------------------------------無法刪除狀態(tài)為Dead的容器---------------------------------------------------
docker中有兩個status為dead的容器,刪除時報錯如下:
Error response from daemon: Driver devicemapper failed to remove root filesystem 33ddd2513fc3cb732fa02e912be1927929d8d028abefa945d8a3984d700a4d74: Device is Busy
解決辦法:
1)看容器進程是否已經(jīng)殺掉。沒有的話,可以手動殺死。
2)mount -l看是不是該容器的路徑還在掛載狀態(tài)。是的話,umount掉。
3)然后再次嘗試docker rm container_id
盡量不要手動去移除dm和docker里面container的相關(guān)文件,以免造成垃圾數(shù)據(jù)。
4)嘗試docker rm -f <container-id>,強制刪除
這樣可以刪除掉docker daemon中的container信息(但是已經(jīng)創(chuàng)建的dm還是ACTIVE的,所以還要再去把dm給刪除了)
---------------------------------------------------容器啟動失敗錯誤1---------------------------------------------------
docker: Error response from daemon: failed to create endpoint mosredis on network bridge: iptables failed: iptables --wait -t filter -A DOCKER ! -i docker0 -o docker0 -p tcp -d 172.17.0.6 -j ACCEPT: iptables: No chain/target/match by that name.(exit status 1).解決辦法: 一般來說,重啟docker服務(wù),即可解決這個問題。 [root@localhost ~]# systemctl restart docker [root@localhost ~]# ---------------------------------- 如果重啟docker服務(wù)解決不了,那么如下操作: [root@localhost ~]# pkill docker [root@localhost ~]# iptables -t nat -F [root@localhost ~]# ifconfig docker0 down [root@localhost ~]# brctl delbr docker0---------------------------------------------------容器啟動失敗錯誤2---------------------------------------------------
docker: Error response from daemon: Cannot start container b0a845a3dedeac7b46002d1c8514077309d88dcc0667b7080bc1ab67d70eb167: [9] System error: SELinux policy denies access.. 如上出現(xiàn)上面的報錯,這是由于selinux造成的!需要關(guān)閉selinux,如下: [root@localhost ~]# setenforce 0 [root@localhost ~]# getenforce Permissive---------------------------------------------------容器yum不能使用--------------------------------------------------
容器啟動后登陸進去,發(fā)現(xiàn)yum不能用,報錯如下: [root@5e91e12186e1 /]# yum list ........ yum-config-manager --disable <repoid> ........ yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true解決辦法:(再不行,就重啟下docker服務(wù),然后登陸容器試試) 先保證容器能正常聯(lián)網(wǎng)(ping www.baidu.com試試) # yum clean all # yum makecache==============關(guān)于docker容器和鏡像以及文件的幾個轉(zhuǎn)化關(guān)系==============
容器轉(zhuǎn)成鏡像: # docker commit <CONTAINER ID> imagename01容器轉(zhuǎn)成文件: # docker export <CONTAINER ID> > /home/export.tar鏡像轉(zhuǎn)成文件: # docker save imagename01 > /home/save.tar注:一般情況下,save.tar比export.tar大一點點而已,export比較小,因為它丟失了歷史和數(shù)據(jù)元metadata文件轉(zhuǎn)成鏡像: # cat /home/export.tar | docker import - imagename02:latestsave.tar文件轉(zhuǎn)成鏡像: # docker load < /home/save.tar查看轉(zhuǎn)成的鏡像: # docker images注意:這里一個鏡像經(jīng)過n次轉(zhuǎn)化之后,可以用sudo docker images --tree查看歷史,用docker tag <LAYER ID> <IMAGE NAME>可以回到某個層(只針對save命令可以回到某個層!)-------------------------------------基于centos7的docker容器出現(xiàn)的一個bug--------------------------------------
centos7下部署的docker容器中啟動服務(wù),報錯如下: [root@a3c8baf6961e .ssh]# systemctl restart sshd.service Failed to get D-Bus connection: Operation not permitted這是centos7容器里面出現(xiàn)的一個BUG! 即centos7鏡像創(chuàng)建的容器里面安裝服務(wù)后,不能用systemctl/service啟動服務(wù),centos6的容器里沒有這個坑! 可以通過使用其他的方式啟動或者換用centos6的鏡像來避免這個錯誤。解決方案如下: 原因是dbus-daemon沒能啟動。其實systemctl并不是不可以使用,可以將你的CMD設(shè)置為/usr/sbin/init即可。 這樣就會自動將dbus等服務(wù)啟動起來。即采用 /usr/sbin/init自動啟動dbus daemon即把之前的容器關(guān)閉并刪除(docker stop container-id),然后重新啟動容器,注意: 啟動時一定要加上參數(shù)--privileged和/sbin/init,如下:[root@localhost ~]# docker run --privileged -i -t centos7:7.3.1611 /sbin/init 上面的容器啟動后,會一直在卡著的狀態(tài)中,先不用管,打開另一個終端窗口,查看容器[root@localhost ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES af40bd07fa0f centos7:7.3.1611 "/sbin/init" 28 seconds ago Up 28 seconds nauseous_shirley然后按照容器的ID進去,這個時候再根據(jù)/bin/bash進入容器(前面加exec -it參數(shù)),接著重啟ssh服務(wù)就ok了 [root@localhost ~]# docker exec -it af40bd07fa0f /bin/bash [root@af40bd07fa0f /]# systemctl restart sshd.service總結(jié)
以上是生活随笔為你收集整理的Docker容器学习梳理--日常操作总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux之使用帮助
- 下一篇: MyBatis学习总结(七)——Myba