安裝好docker環境並啓動docker服務後,咱們就能夠跑一個「hello world!」試試了docker
命令以下:centos
[root@localhost ~]# docker run centos echo "Docker,hello world"
Unable to find image 'centos:latest' locally
latest: Pulling from centos
47d44cb6f252: Pull complete
168a69b62202: Pull complete
812e9d9d677f: Pull complete
4234bfdd88f8: Pull complete
ce20c473cd8a: Pull complete
centos:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security.
Digest: sha256:3aaab9f1297db9b013063c781cfe901e2aa6e7e334c1d1f4df12f25ce356f2e5
Status: Downloaded newer image for centos:latest
Docker,hello worldbash
命令說明:ide
docker run :標準容器啓動命令測試
centos :鏡像名稱spa
echo及後面的內容 :容器啓動後執行的命令日誌
固然咱們也能夠再複雜一點,增長-it參數,能夠啓動一個bash,實現與容器的交互,並向操做虛擬機同樣操做容器:進程
[root@localhost ~]# docker run -it centos /bin/bash
[root@110baabc10bc /]# echo "Docker,hello world"
Docker,hello world字符串
*注:-t標示在心容器內指定一個僞終端或終端,-i標示容許咱們對容器內的STDIN進行交互虛擬機
咱們在容器中執行一個ps命令,能夠看到容器與虛擬機最大的不一樣,容器僅容許了一個須要容許的進程,無內核相關的其餘進程,以下:
[root@110baabc10bc /]# ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 02:05 ? 00:00:00 /bin/bash
root 17 1 0 02:06 ? 00:00:00 ps -ef
2.3 以服務方式啓動一個docker容器
若是你實際測試,估計也發現了,第一個「hello world」容器啓動後執行完echo命令就退出了,而第二個交互式的容器,只要用戶退出當前容器的bash,容器也退出了。這明顯不能知足一個服務長時間運行的要求,好找docker run提供了‘-d’參數,能夠實現將容器以守護進程方式啓動。
演示以下:
[root@localhost ~]# docker run -d centos /bin/bash -c "while true; do echo Docker,hello world; sleep 2; done"
5ff7a2ac73469a4ff30d3709ceaa4d9ee14a87bf075fdf5ba4cb751b7077edf3
[root@localhost ~]# docker logs 5ff7a2ac73469a4ff30d3709ceaa4d9ee14a87bf075fdf5ba4cb751b7077edf3
Docker,hello world
Docker,hello world
Docker,hello world
Docker,hello world
Docker,hello world[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5ff7a2ac7346 centos "/bin/bash -c 'while 21 seconds ago Up 20 seconds elegant_jang
這是一個荒謬的hello word進程:一個腳本會一直輸出"Docker,hello world"
爲何不是咱們看到的一大堆的"hello word"?而是docker返回的一個很長的字符串:
5ff7a2ac73469a4ff30d3709ceaa4d9ee14a87bf075fdf5ba4cb751b7077edf3
這個長的字符串叫作容器ID。它是容器的惟一標識,因此咱們能夠使用它來操做容器,好比查看日誌、中止或刪除容器等。
而爲何使用一個死循環來輸出呢?
由於若是不是死循環,一次輸出後,容器中的進程就結束了。容器的惟一進程都結束了,容器就中止了。所以若是要在容器中運行具體的服務,這項服務自己在容器中也必須是已守護進程方式運行的。
容器的操做是否是很簡單的呢?下文咱們將探討docker鏡像。