1. 程式人生 > >docker學習(二)——docker的基本概念及基礎使用

docker學習(二)——docker的基本概念及基礎使用

一張圖概括整篇文章內容:

來自:https://medium.com/@nagarwal/lifecycle-of-docker-container-d2da9f85959

âdocker event stateâçå¾çæç´¢ç»æ


lxc->libcontainer->runC

OCI(Open Container Initiative):圍繞容器格式和執行時制定一個開放的工業化標準

OCF(Open Container Format):

docker映象倉庫:https://hub.docker.com

docker:C/S架構:docker client,DOCKER_HOST(執行docker_daemon),docker Registry 

DOCKER_HOST執行Docker_daemon程序,監聽在某個socket上:預設socket為unix socket,只允許本地連線;還有ipv4和ipv6兩種監聽方式。DOCKER_HOST上面執行容器,存放容器執行容器的映象

Registry:DOCKER_HOST的映象來自於Registry

DOCKER_HOST與Registry之間拉取和推送映象採用https協議

docker映象加速:docker伺服器在國外,國內拉取映象很慢

docker有企業版和社群版兩種:docker-ee,docker-ce


docker映象是分層建立的

標識一個映象:  倉庫名:標籤   如:nginx:1.15 nginx:latest nginx:stable  

容器有生命週期


Docker  objects:images,containers,networks,volumes,plugins,other objects


安裝及使用docker

docker安裝環境要求:64位CPU,核心3.10+,cgroups and namespaces

安裝:預設倉庫安裝或者安裝docker源(推薦)

[[email protected] ~]# wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker.repo
[
[email protected]
~]# yum repolist [[email protected] ~]# yum list docker-ce --showduplicates 已載入外掛:fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.aliyun.com * extras: mirrors.aliyun.com * updates: mirrors.aliyun.com 可安裝的軟體包 docker-ce.x86_64 17.03.0.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 17.03.1.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 17.03.2.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 17.03.3.ce-1.el7 docker-ce-stable docker-ce.x86_64 17.06.0.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 17.06.1.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 17.06.2.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 17.09.0.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 17.09.1.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 17.12.0.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 17.12.1.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 18.03.0.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 18.03.1.ce-1.el7.centos docker-ce-stable docker-ce.x86_64 18.06.0.ce-3.el7 docker-ce-stable docker-ce.x86_64 18.06.1.ce-3.el7 docker-ce-stable docker-ce.x86_64 3:18.09.0-3.el7 docker-ce-stable [[email protected] ~]# yum install docker-ce-18.06.1.ce-3.el7 -y

 docker元件:

環境配置檔案:

  • /etc/sysconfig/docker-network
  • /etc/sysconfig/docker-network
  • /etc/sysconfig/docker

unit file:

  • /etc/systemd/system/docker.service

Docker Registry配置檔案:

  • /etc/container/registries.conf

配置檔案:/etc/docker/docker.daemon.json


docker映象加速:

  • docker cn
  • 阿里雲映象加速
  • 中國科技大學
[[email protected] ~]# mkdir -p /etc/docker
[[email protected] ~]# cat >> /etc/docker/daemon.json <<EOF
> {
>   "registry-mirrors": ["https://7f28zkr3.mirror.aliyuncs.com"]
> }
> EOF

啟動容器:

[[email protected] ~]# systemctl start docker.service 
[[email protected] ~]# systemctl enable  docker.service 
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.
[[email protected] ~]# docker version 
Client:
 Version:           18.06.1-ce
 API version:       1.38
 Go version:        go1.10.3
 Git commit:        e68fc7a
 Built:             Tue Aug 21 17:23:03 2018
 OS/Arch:           linux/amd64
 Experimental:      false

Server:
 Engine:
  Version:          18.06.1-ce
  API version:      1.38 (minimum version 1.12)
  Go version:       go1.10.3
  Git commit:       e68fc7a
  Built:            Tue Aug 21 17:25:29 2018
  OS/Arch:          linux/amd64
  Experimental:     false

docker info 檢視docker資訊

[[email protected] ~]# docker info
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 0
Server Version: 18.06.1-ce
Storage Driver: overlay2
 Backing Filesystem: xfs
 Supports d_type: true
 Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 468a545b9edcd5932818eb9de8e72413e616e86e
runc version: 69663f0bd4b60df09991c08812a60108003fa340
init version: fec3683
Security Options:
 seccomp
  Profile: default
Kernel Version: 3.10.0-862.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 974.6MiB
Name: docker2
ID: R4C5:VHVN:YWXB:SFH5:EZJP:I3SJ:7QFG:43PY:344D:3JHJ:DHF4:WSJ5
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
 127.0.0.0/8
Registry Mirrors:
 https://7f28zkr3.mirror.aliyuncs.com/
Live Restore Enabled: false

docker對映象的操作:

[[email protected] ~]# docker image --help

Usage:	docker image COMMAND

Manage images

Commands:
  build       Build an image from a Dockerfile
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  inspect     Display detailed information on one or more images
  load        Load an image from a tar archive or STDIN
  ls          List images
  prune       Remove unused images
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rm          Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

Run 'docker image COMMAND --help' for more information on a command.

docker search搜尋映象:

[[email protected] ~]# docker search nginx
NAME                                                   DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
nginx                                                  Official build of Nginx.                        10645               [OK]                
jwilder/nginx-proxy                                    Automated Nginx reverse proxy for docker con…   1497                                    [OK]
richarvey/nginx-php-fpm                                Container running Nginx + PHP-FPM capable of…   671                                     [OK]
jrcs/letsencrypt-nginx-proxy-companion                 LetsEncrypt container to use with nginx as p…   457                                     [OK]
kong                                                   Open-source Microservice & API Management la…   271                 [OK]                
webdevops/php-nginx                                    Nginx with PHP-FPM                              119                                     [OK]
kitematic/hello-world-nginx                            A light-weight nginx container that demonstr…   116                            

docker image 拉取映象:

[[email protected] ~]# docker image pull nginx:1.15-alpine
1.15-alpine: Pulling from library/nginx
cd784148e348: Pull complete 
6e3058b2db8a: Pull complete 
7ca4d29669c1: Pull complete 
a14cf6997716: Pull complete 
Digest: sha256:385fbcf0f04621981df6c6f1abd896101eb61a439746ee2921b26abc78f45571
Status: Downloaded newer image for nginx:1.15-alpine
[[email protected] ~]# docker image pull busybox
Using default tag: latest
latest: Pulling from library/busybox
b4a6e23922dd: Pull complete 
Digest: sha256:8ccbac733d19c0dd4d70b4f0c1e12245b5fa3ad24758a11035ee505c629c0796
Status: Downloaded newer image for busybox:latest

檢視映象:docker image ls

[[email protected] ~]# docker image ls --help

Usage:	docker image ls [OPTIONS] [REPOSITORY[:TAG]]

List images

Aliases:
  ls, images, list

Options:
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           Only show numeric IDs
[[email protected] ~]# docker image ls --no-trunc
REPOSITORY          TAG                 IMAGE ID                                                                  CREATED             SIZE
nginx               1.15-alpine         sha256:315798907716a51610bb3c270c191e0e61112b19aae9a3bb0c2a60c53d074750   3 days ago          17.8MB
busybox             latest              sha256:758ec7f3a1ee85f8f08399b55641bfb13e8c1109287ddc5e22b68c3d653152ee   3 days ago          

對docker容器的操作:

[[email protected] ~]# docker container --help

Usage:	docker container COMMAND

Manage containers

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  inspect     Display detailed information on one or more containers
  kill        Kill one or more running containers
  logs        Fetch the logs of a container
  ls          List containers
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  prune       Remove all stopped containers
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  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 one or more containers stop, then print their exit codes

Run 'docker container COMMAND --help' for more information on a command.

執行一個容器:docker container run

[[email protected] ~]# docker container run --help

Usage:	docker container run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --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)
  -d, --detach                         Run container in background and print container ID
      --detach-keys string             Override the key sequence for detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown
                                       (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network string                 Connect a container to a network (default "default")
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --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 list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop a container (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container
[[email protected] ~]# docker container run --name b1 -it busybox:latest 
/ # ls /
bin   dev   etc   home  proc  root  sys   tmp   usr   var

在b1容器上跑一個httpd

容器內執行httpd

/ # httpd -h
httpd: option requires an argument -- h
BusyBox v1.29.3 (2018-12-24 21:25:20 UTC) multi-call binary.

Usage: httpd [-ifv[v]] [-c CONFFILE] [-p [IP:]PORT] [-u USER[:GRP]] [-r REALM] [-h HOME]
or httpd -d/-e/-m STRING

Listen for incoming HTTP requests

	-i		Inetd mode
	-f		Don't daemonize
	-v[v]		Verbose
	-p [IP:]PORT	Bind to IP:PORT (default *:80)
	-u USER[:GRP]	Set uid/gid after binding to port
	-r REALM	Authentication Realm for Basic Authentication
	-h HOME		Home directory (default .)
	-c FILE		Configuration file (default {/etc,HOME}/httpd.conf)
	-m STRING	MD5 crypt STRING
	-e STRING	HTML encode STRING
	-d STRING	URL decode STRING
/ # mkdir /data/html -p
/ # echo "busybox" >> /data/html/index.html
/ # httpd -f -h /data/html 

新開shell,檢視b1容器的詳情,IP,

[root[email protected] ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
4b046064f896        busybox:latest      "sh"                23 minutes ago      Up 23 minutes                           b1
[[email protected] ~]# docker inspect b1 | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

通過IP訪問該容器的服務:

[[email protected] ~]# curl 172.17.0.2
busybox

 


退出容器再檢視:(docker ps 與docker container ls一樣)

/ # httpd -f -h /data/html 
^C
/ # exit
[[email protected] ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[[email protected] ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES
4b046064f896        busybox:latest      "sh"                25 minutes ago      Exited (130) 16 seconds ago                       b1
[[email protected] ~]# docker container ls 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[[email protected] ~]# docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES
4b046064f896        busybox:latest      "sh"                26 minutes ago      Exited (130) 36 seconds ago                       b1

啟動停止的容器:

[[email protected] ~]# docker start -a -i b1
/ # 

新開shell檢視:

[[email protected] ~]# docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
4b046064f896        busybox:latest      "sh"                30 minutes ago      Up 37 seconds                           b1

使用kill強行停掉容器(測試):

[[email protected] ~]# docker kill b1
b1
[[email protected] ~]# docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

執行一個容器,指定容器名字為web1,後臺執行,使用nginx:1.15-alpine映象

[[email protected] ~]# docker container run --name web1 -d nginx:1.15-alpine 
aa7f935730ed5404a1ac81709ccf02d99bdbab8314a27e48884012ce23627ae3
[[email protected] ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
aa7f935730ed        nginx:1.15-alpine   "nginx -g 'daemon of…"   5 seconds ago       Up 4 seconds        80/tcp              web1

檢視該容器詳細資訊:

[[email protected] ~]# docker inspect web1
[[email protected] ~]# docker inspect web1 | grep -i ipaddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",
[[email protected] ~]# curl -s 172.17.0.2 | grep -i welcome
<title>Welcome to nginx!</title>
<h1>Welcome to nginx!</h1>

執行一個容器,名字為kvstor1,後臺執行,使用redis:5映象

[[email protected] ~]# docker container run --name kvstor1 -d redis:5
Unable to find image 'redis:5' locally
5: Pulling from library/redis
177e7ef0df69: Pull complete 
66ec699db42d: Pull complete 
9af6d87fd347: Pull complete 
de9172cdb09c: Pull complete 
27733a222e28: Pull complete 
ef1ae1903ba4: Pull complete 
Digest: sha256:86654d77602cbfeb873191488d176b215067549b7491364c3f84046f5753f0a0
Status: Downloaded newer image for redis:5
b2a481f1fde0e1ec517ed01684fdd2b1fa7d51d8738aee46342b0ea2ced8c54e
[[email protected] ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
b2a481f1fde0        redis:5             "docker-entrypoint.s…"   5 seconds ago       Up 4 seconds        6379/tcp            kvstor1
aa7f935730ed        nginx:1.15-alpine   "nginx -g 'daemon of…"   8 minutes ago       Up 8 minutes        80/tcp              web1

在執行的容器中執行命令:

[[email protected] ~]# docker container exec --help

Usage:	docker container exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container
[[email protected] ~]# docker container exec -it kvstor1 /bin/sh
# ls /
bin  boot  data  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
# redis-cli 
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> SELECT 1
OK
127.0.0.1:6379[1]> exit
# exit

檢視一個容器的日誌,docker container logs

[[email protected] ~]# docker container logs --help

Usage:	docker container logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
[[email protected] ~]# docker container logs web1
172.17.0.1 - - [30/Dec/2018:06:40:19 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
172.17.0.1 - - [30/Dec/2018:06:40:41 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
172.17.0.1 - - [30/Dec/2018:06:40:48 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

對docker網路的操作:

[[email protected] ~]# docker network --help

Usage:	docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  prune       Remove all unused networks
  rm          Remove one or more networks

Run 'docker network COMMAND --help' for more information on a command.
[[email protected] ~]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
1f1d3b3c2f74        bridge              bridge              local
76bea4912e96        host                host                local
a33261fb3dc7        none                null                local