Docker 安裝和基礎用法

理解Docker(1):Docker 安裝和基礎用法

本系列文章將介紹Docker的有關知識:html

(1)Docker 安裝及基本用法node

(2)Docker 鏡像python

(3)Docker 容器的隔離性 - 使用 Linux namespace 隔離容器的運行環境linux

(4)Docker 容器的隔離性 - 使用 cgroups 限制容器使用的資源web

(5)Docker 網絡mongodb

1. 安裝

1.1 在 Ubuntu 14.04 上安裝 Docker

前提要求:docker

  • 內核版本必須是3.10或者以上

依次執行下面的步驟:ubuntu

  1. sudo apt-get update
  2. sudo apt-get install apt-transport-https ca-certificates
  3. sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
  4. 編輯 /etc/apt/sources.list.d/docker.list 文件,添加 deb https://apt.dockerproject.org/repo ubuntu-trusty main
  5. sudo apt-get update
  6. sudo apt-get purge lxc-docker
  7. apt-cache policy docker-engine
  8. apt-get upgrade
  9. sudo apt-get install linux-image-extra-$(uname -r) linux-image-extra-virtual
  10. sudo apt-get install docker-engine

至此,安裝過程完成。api

  1. 運行 sudo service docker start 啓動 Docker 守護進程。
  2. 運行 docker version 查看 Docker 版本
root@devstack:/home/sammy# docker --version
Docker version 1.12.1, build 23cf638

啓動第一個容器:bash

  1. 啓動第一個Docker 容器 docker run hello-world
root@devstack:/home/sammy# docker run hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.

它的運行成功也代表前面的安裝步驟都運行正確了。 

以上內容參考自 Docker 官網:https://docs.docker.com/engine/installation/linux/ubuntulinux/

1.2 Docker 到目前(2016/09/16)爲止的版本歷史

版本號 發佈日期 發佈經理
Docker 1.12.1 08/18/2016  
Docker 1.12.0 07/28/2016  
Docker 1.11.0 04/12/2016 @mlaventure
Docker 1.10.0 02/04/2016 @thaJeztah
Docker 1.9.0 10/29/2015 @tiborvass
Docker 1.8.0 08/11/2015 @calavera

 

2. Docker 的基本操做

2.1 Docker 容器的狀態機

圖片來源

一個容器在某個時刻可能處於如下幾種狀態之一:

  • created:已經被建立 (使用 docker ps -a 命令能夠列出)可是尚未被啓動 (使用 docker ps 命令還沒法列出)
  • running:運行中
  • paused:容器的進程被暫停了
  • restarting:容器的進程正在重啓過程當中
  • exited:上圖中的 stopped 狀態,表示容器以前運行過可是如今處於中止狀態(要區別於 created 狀態,它是指一個新創出的還沒有運行過的容器)。能夠經過 start 命令使其從新進入 running 狀態
  • destroyed:容器被刪除了,不再存在了

你能夠在 docker inspect 命令的輸出中查看其詳細狀態:

複製代碼
"State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 4597,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2016-09-16T08:09:34.53403504Z",
            "FinishedAt": "2016-09-16T08:06:44.365106765Z"
        }
複製代碼

2.2 Docker 命令概述

咱們能夠把Docker 的命令大概地分類以下:

複製代碼
    鏡像操做:
    build     Build an image from a Dockerfile
    commit    Create a new image from a container's changes
    images    List images
    load      Load an image from a tar archive or STDIN
    pull      Pull an image or a repository from a registry
    push      Push an image or a repository to a registry
    rmi       Remove one or more images
    search    Search the Docker Hub for images
    tag       Tag an image into a repository
    save      Save one or more images to a tar archive (streamed to STDOUT by default)
    history   顯示某鏡像的歷史
inspect 獲取鏡像的詳細信息
容器及其中應用的生命週期操做: create Create a new container (建立一個容器) kill Kill one or more running containers inspect Return low-level information on a container, image or task pause Pause all processes within one or more containers ps List containers rm Remove one or more containers (刪除一個或者多個容器) rename Rename a container restart Restart a container run Run a command in a new container (建立並啓動一個容器) start Start one or more stopped containers (啓動一個處於中止狀態的容器) stats Display a live stream of container(s) resource usage statistics (顯示容器實時的資源消耗信息) stop Stop one or more running containers (中止一個處於運行狀態的容器) top Display the running processes of a container unpause Unpause all processes within one or more containers update Update configuration of one or more containers wait Block until a container stops, then print its exit code attach Attach to a running container exec Run a command in a running container port List port mappings or a specific mapping for the container
logs 獲取容器的日誌 容器文件系統操做: cp Copy files/folders between a container and the local filesystem diff Inspect changes on a container's filesystem export Export a container's filesystem as a tar archive import Import the contents from a tarball to create a filesystem image Docker registry 操做: login Log in to a Docker registry. logout Log out from a Docker registry. Volume 操做 volume Manage Docker volumes 網絡操做 network Manage Docker networks Swarm 相關操做 swarm Manage Docker Swarm service Manage Docker services node Manage Docker Swarm nodes 系統操做: version Show the Docker version information
events Get real time events from the server (持續返回docker 事件)
info Display system-wide information (顯示Docker 主機系統範圍內的信息)
 
  
複製代碼

比較有意思的幾個命令:

(1)容器從生到死整個生命週期

複製代碼
root@devstack:/home/sammy# docker create --name web31 training/webapp python app.py  #建立名字爲 web31 的容器
7465f4cb7c49555af32929bd1bc4213f5e72643c0116450e495b71c7ec128502
root@devstack:/home/sammy# docker inspect --format='{{.State.Status}}' web31 #其狀態爲 created
created
root@devstack:/home/sammy# docker start web31 #啓動容器
web31
root@devstack:/home/sammy# docker exec -it web31 /bin/bash #在容器中運行 bash 命令
root@devstack:/home/sammy# docker inspect --format='{{.State.Status}}' web31 #其狀態爲 running running root@devstack:/home/sammy# docker pause web31 #暫停容器 web31 root@devstack:/home/sammy# docker inspect --format='{{.State.Status}}' web31 paused root@devstack:/home/sammy# docker unpause web31 #繼續容器 web31 root@devstack:/home/sammy# docker inspect --format='{{.State.Status}}' web31 running root@devstack:/home/sammy# docker rename web31 newweb31 #重命名 root@devstack:/home/sammy# docker inspect --format='{{.State.Status}}' newweb31 running root@devstack:/home/sammy# docker top newweb31 #在容器中運行 top 命令 UID PID PPID C STIME TTY TIME CMD root 5009 4979 0 16:28 ? 00:00:00 python app.py root@devstack:/home/sammy# docker logs newweb31 #獲取容器的日誌 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) root@devstack:/home/sammy# docker stop newweb31 #中止容器 newweb31 root@devstack:/home/sammy# docker inspect --format='{{.State.Status}}' newweb31 exited root@devstack:/home/sammy# docker rm newweb31 #刪除容器 newweb31 root@devstack:/home/sammy# docker inspect --format='{{.State.Status}}' newweb31 Error: No such image, container or task: newweb31
複製代碼

(2) docker stop 和 docker kill

在docker stop 命令執行的時候,會先向容器中PID爲1的進程發送系統信號 SIGTERM,而後等待容器中的應用程序終止執行,若是等待時間達到設定的超時時間(默認爲 10秒,用戶能夠指定特定超時時長),會繼續發送SIGKILL的系統信號強行kill掉進程。在容器中的應用程序,能夠選擇忽略和不處理SIGTERM信號,不過一旦達到超時時間,程序就會被系統強行kill掉,由於SIGKILL信號是直接發往系統內核的,應用程序沒有機會去處理它。

好比運行 docker stop web5 -t 20 命令後:

2016-09-16T16:01:18.206540853+08:00 container kill b3256ef1400a7f6a6f242e377a77af5e25d3b12237c4ee7c2e9b31a5f6437868 (image=training/webapp, name=web5, signal=15)
2016-09-16T16:01:38.212352224+08:00 container kill b3256ef1400a7f6a6f242e377a77af5e25d3b12237c4ee7c2e9b31a5f6437868 (image=training/webapp, name=web5, signal=9)
2016-09-16T16:01:38.235021315+08:00 container die b3256ef1400a7f6a6f242e377a77af5e25d3b12237c4ee7c2e9b31a5f6437868 (exitCode=137, image=training/webapp, name=web5)

能看到:

  1. 首先 docker 向容器發出 SIGTERM 信號(signal=15)
  2. 等待20秒 (01:18 到 01:38)
  3. 再發送 SIGKILL 系統信號 (signal = 9)
  4. 而後容器被殺掉了 (die)

而 docker kill 命令會直接發出SIGKILL的系統信號,以強行終止容器中程序的運行。運行 docker kill web5 命令後:

2016-09-16T16:06:44.351086471+08:00 container kill b3256ef1400a7f6a6f242e377a77af5e25d3b12237c4ee7c2e9b31a5f6437868 (image=training/webapp, name=web5, signal=9)
2016-09-16T16:06:44.365116100+08:00 container die b3256ef1400a7f6a6f242e377a77af5e25d3b12237c4ee7c2e9b31a5f6437868 (exitCode=137, image=training/webapp, name=web5)

可見直接發出的是 SIGKILL 信號,容器立馬就被殺掉了。

(3)使用 docker cp 在 host 和 container 之間拷貝文件或者目錄

root@devstack:/home/sammy# docker cp /home/sammy/mydockerbuild/Dockerfile web5:/webapp #從 host 拷貝文件到 container 裏面
root@devstack:/home/sammy#
root@devstack:/home/sammy# docker cp web5:/webapp/Dockerfile /home/sammy/Dockerfile #從 container 裏面拷貝文件到 host 上
root@devstack:/home/sammy# ls /home/sammy
chroot  devstack  Dockerfile  mongodbdocker  mydockerbuild  webapp

(4)docker export 和 import

docker export:將一個容器的文件系統打包爲一個壓縮文件

root@devstack:/home/sammy# docker export web5 -o ./web5
root@devstack:/home/sammy# ls
chroot  devstack  Dockerfile  mongodbdocker  mydockerbuild  web5  webapp

docker import:從一個壓縮文件建立一個鏡像

root@devstack:/home/sammy# docker import web5 web5img -m "imported on 0916"
sha256:745bb258be0a69a517367667646148bb2f662565bb3d222b50c0c22e5274a926
root@devstack:/home/sammy# docker history web5img
IMAGE               CREATED             CREATED BY          SIZE                COMMENT
745bb258be0a        6 seconds ago                           324 MB              imported on 0916

(5) 當在 docker 中執行某 bash 命令時,可能會返回 command not found。其緣由是你所使用的鏡像每每是最小鏡像,未安裝你所須要的命令。好比基於 ubuntu 鏡像啓動一個容器,運行 ping 命令會提示該錯誤。此時,須要手工安裝該工具。

apt-get update
apt-get install iputils-ping  #會安裝 ping 命令
apt-get install net-tools #會安裝 ifconfig 命令

 

 2.3 docker run 命令

docker run 命令會建立一個容器並啓動它,它也是包含不少的參數,按照用途將它們分類以下:

複製代碼
   cgroups 和 namespace 相關:
      --blkio-weight value          Block IO (relative weight), between 10 and 1000
      --blkio-weight-device value   Block IO weight (relative device weight) (default [])
      --cgroup-parent string        Optional parent cgroup for the container
      --cpu-percent int             CPU percent (Windows only)
      --cpu-period int              Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int               Limit CPU CFS (Completely Fair Scheduler) quota
  -c, --cpu-shares int              CPU shares (relative weight)
      --cpuset-cpus string          CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string          MEMs in which to allow execution (0-3, 0,1)
      --device-read-bps value       Limit read rate (bytes per second) from a device (default [])
      --device-read-iops value      Limit read rate (IO per second) from a device (default [])
      --device-write-bps value      Limit write rate (bytes per second) to a device (default [])
      --device-write-iops value     Limit write rate (IO per second) to a device (default [])
      --ipc string                  IPC namespace to use
  -m, --memory string               Memory limit
      --memory-reservation string   Memory soft limit
      --memory-swap string          Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int       Tune container memory swappiness (0 to 100) (default -1)
      --kernel-memory string        Kernel memory limit
  -u, --user string                 Username or UID (format: <name|uid>[:<group|gid>])
      --userns string               User namespace to use
      --uts string                  UTS namespace to use
  -h, --hostname string             Container host name
      --pid string                  PID namespace to use
      --pids-limit int              Tune container pids limit (set -1 for unlimited)
      --isolation string            Container isolation technology
      --io-maxbandwidth string      Maximum IO bandwidth limit for the system drive (Windows only)
      --io-maxiops uint             Maximum IOps limit for the system drive (Windows only)
    
    linux process capabilities 相關參數:
      --cap-add value               Add Linux capabilities (default [])
      --cap-drop value              Drop Linux capabilities (default [])
    
    容器運行模式和環境相關:
  -d, --detach                      Run container in background and print container ID
  -e, --env value                   Set environment variables (default [])
      --env-file value              Read in a file of environment variables (default [])
    
    DNS 相關:
      --dns value                   Set custom DNS servers (default [])
      --dns-opt value               Set DNS options (default [])
      --dns-search value            Set custom DNS search domains (default [])
    
    健康檢查相關:
      --health-cmd string           Command to run to check health
      --health-interval duration    Time between running the check
      --health-retries int          Consecutive failures needed to report unhealthy
      --health-timeout duration     Maximum time to allow one check to run
      --no-healthcheck              Disable any container-specified HEALTHCHECK
      
    IP 和端口:
      --ip string                   Container IPv4 address (e.g. 172.30.100.104)
      --ip6 string                  Container IPv6 address (e.g. 2001:db8::33)
  -p, --publish value               Publish a container's port(s) to the host (default [])
  -P, --publish-all                 Publish all exposed ports to random ports
      --expose value                Expose a port or a range of ports (default [])
      --mac-address string          Container MAC address (e.g. 92:d0:c6:0a:29:33)
      --add-host value              Add a custom host-to-IP mapping (host:ip) (default [])
      
    Volume 相關:
  -v, --volume value                Bind mount a volume (default [])
      --volume-driver string        Optional volume driver for the container
      --volumes-from value          Mount volumes from the specified container(s) (default [])
      --storage-opt value           Storage driver options for the container (default [])
  
    Network 有關:
      --network string              Connect a container to a network (default "default")
      --network-alias value         Add network-scoped alias for the container (default [])
      --link value                  Add link to another container (default [])
      --link-local-ip value         Container IPv4/IPv6 link-local addresses (default [])
    
    日誌有關:
      --log-driver string           Logging driver for the container
      --log-opt value               Log driver options (default [])
    
    交互性有關:
  -a, --attach value                Attach to STDIN, STDOUT or STDERR (default [])
  -i, --interactive                 Keep STDIN open even if not attached
   
    OOM 有關:   
      --oom-kill-disable            Disable OOM Killer
      --oom-score-adj int           Tune host's OOM preferences (-1000 to 1000)
    
    其它(待更進一步分類):
      --cidfile string              Write the container ID to the file
      --detach-keys string          Override the key sequence for detaching a container
      --device value                Add a host device to the container (default [])
      --disable-content-trust       Skip image verification (default true)
      --entrypoint string           Overwrite the default ENTRYPOINT of the image
      --group-add value             Add additional groups to join (default [])
      --help                        Print usage
  -l, --label value                 Set meta data on a container (default [])
      --label-file value            Read in a line delimited file of labels (default [])
      --name string                 Assign a name to the container
      --privileged                  Give extended privileges to this container
      --read-only                   Mount the container's root filesystem as read only
      --restart string              Restart policy to apply when a container exits (default "no")
      --rm                          Automatically remove the container when it exits
      --runtime string              Runtime to use for this container
      --security-opt value          Security Options (default [])
      --shm-size string             Size of /dev/shm, default value is 64MB
      --sig-proxy                   Proxy received signals to the process (default true)
      --stop-signal string          Signal to stop a container, SIGTERM by default (default "SIGTERM")
      --sysctl value                Sysctl options (default map[])
      --tmpfs value                 Mount a tmpfs directory (default [])
  -t, --tty                         Allocate a pseudo-TTY
      --ulimit value                Ulimit options (default [])
  -w, --workdir string              Working directory inside the container
複製代碼

具體的內容之後會有專門文件分析。

3. Doker 平臺的基本構成

Docker 平臺基本上由三部分組成:

  1. 客戶端:用戶使用 Docker 提供的工具(CLI 以及 API 等)來構建,上傳鏡像併發布命令來建立和啓動容器
  2. Docker 主機:從 Docker registry 上下載鏡像並啓動容器
  3. Docker registry:Docker 鏡像倉庫,用於保存鏡像,並提供鏡像上傳和下載

後面的文章會具體分析。

相關文章
相關標籤/搜索