docker命令讲解与核心原理_02

一、安装docker

1.0、系统环境 

#系统版本
[root@docker ~]# cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 

#download iso
iso: CentOS-7.2-x86_64-Minimal-1511.iso

#close iptables
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
setenforce 0

#install software
 yum install wget net-tools vim lrzsz screen lsof tcpdump nc mtr nmap -y

#更改yum源
cd /etc/yum.repos.d/
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

#重新缓存
yum clean all
yum makecache

 1.1、安装docker

yum install docker -y

1.2、解决docker启动bug

 [root@docker ~]# vi /etc/sysconfig/docker

# /etc/sysconfig/docker

# Modify these options if you want to change the way the docker daemon runs
OPTIONS='--selinux-enabled=false --log-driver=journald --signature-verification=false'
if [ -z "${DOCKER_CERT_PATH}" ]; then
    DOCKER_CERT_PATH=/etc/docker
fi

1.3、配置docker阿里镜像加速

[root@docker ~]# cat /usr/lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.com
After=network.target rhel-push-plugin.socket registries.service
Wants=docker-storage-setup.service
Requires=docker-cleanup.timer

[Service]
Type=notify
NotifyAccess=all
EnvironmentFile=-/run/containers/registries.conf
EnvironmentFile=-/etc/sysconfig/docker
EnvironmentFile=-/etc/sysconfig/docker-storage
EnvironmentFile=-/etc/sysconfig/docker-network
Environment=GOTRACEBACK=crash
Environment=DOCKER_HTTP_HOST_COMPAT=1
Environment=PATH=/usr/libexec/docker:/usr/bin:/usr/sbin
ExecStart=/usr/bin/dockerd-current --registry-mirror=https://alzgoonw.mirror.aliyuncs.com \
          --add-runtime docker-runc=/usr/libexec/docker/docker-runc-current \
          --default-runtime=docker-runc \
          --exec-opt native.cgroupdriver=systemd \
          --userland-proxy-path=/usr/libexec/docker/docker-proxy-current \
          --init-path=/usr/libexec/docker/docker-init-current \
          --seccomp-profile=/etc/docker/seccomp.json \
          $OPTIONS \
          $DOCKER_STORAGE_OPTIONS \
          $DOCKER_NETWORK_OPTIONS \
          $ADD_REGISTRY \
          $BLOCK_REGISTRY \
          $INSECURE_REGISTRY \
	  $REGISTRIES
ExecReload=/bin/kill -s HUP $MAINPID
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
TimeoutStartSec=0
Restart=on-abnormal
KillMode=process

[Install]
WantedBy=multi-user.target

#启动系统服务

systemctl daemon-reload
systemctl enable docker
systemctl restart docker

 1.4、安装docker-ce版本

参考官网

https://docs.docker.com/install/linux/docker-ce/centos/#upgrade-docker-ce-1

 

二、docker使用方法

2.0、docker基础命令

[root@docker ~]# docker --help

Usage:
docker [OPTIONS] COMMAND [arg...]

       docker daemon [ --help | ... ]

       docker [ --help | -v | --version ]

A
self-sufficient runtime for containers.

Options:

  --config=~/.docker              Location of client config files  #客户端配置文件的位置

  -D, --debug=false               Enable debug mode  #启用Debug调试模式

  -H, --host=[]                   Daemon socket(s) to connect to  #守护进程的套接字(Socket)连接

  -h, --help=false                Print usage  #打印使用

  -l, --log-level=info            Set the logging level  #设置日志级别

  --tls=false                     Use TLS; implied by--tlsverify  #

  --tlscacert=~/.docker/ca.pem    Trust certs signed only by this CA  #信任证书签名CA

  --tlscert=~/.docker/cert.pem    Path to TLS certificate file  #TLS证书文件路径

  --tlskey=~/.docker/key.pem      Path to TLS key file  #TLS密钥文件路径

  --tlsverify=false               Use TLS and verify the remote  #使用TLS验证远程

  -v, --version=false             Print version information and quit  #打印版本信息并退出

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 a container to a HOSTDIR or to STDOUT  #从容器中拷贝指定文件或者目录到宿主机中

    create    Create a new container  #创建一个新的容器,同run 但不启动容器

    diff    Inspect changes on a container's filesystem  #查看docker容器变化

    events    Get real time events from the server#从docker服务获取容器实时事件

    exec    Run a command in a running container#在已存在的容器上运行命令

    export    Export a container's filesystem as a tar archive  #导出容器的内容流作为一个tar归档文件(对应import)

    history    Show the history of an image  #展示一个镜像形成历史

    images    List images  #列出系统当前镜像

    import    Import the contents from a tarball to create a filesystem image  #从tar包中的内容创建一个新的文件系统映像(对应export)

    info    Display system-wide information  #显示系统相关信息

    inspect    Return low-level information on a container or image  #查看容器详细信息

    kill    Kill a running container  #kill指定docker容器

    load    Load an image from a tar archive or STDIN  #从一个tar包中加载一个镜像(对应save)

    login    Register or log in to a Docker registry#注册或者登陆一个docker源服务器

    logout    Log out from a Docker registry  #从当前Docker registry退出

    logs    Fetch the logs of a container  #输出当前容器日志信息

    pause    Pause all processes within a container#暂停容器

    port    List port mappings or a specific mapping for the CONTAINER  #查看映射端口对应的容器内部源端口

    ps    List containers  #列出容器列表

    pull    Pull an image or a repository from a registry  #从docker镜像源服务器拉取指定镜像或者库镜像

    push    Push an image or a repository to a registry  #推送指定镜像或者库镜像至docker源服务器

    rename    Rename a container  #重命名容器

    restart    Restart a running container  #重启运行的容器

    rm    Remove one or more containers  #移除一个或者多个容器

    rmi    Remove one or more images  #移除一个或多个镜像(无容器使用该镜像才可以删除,否则需要删除相关容器才可以继续或者-f强制删除)

    run    Run a command in a new container  #创建一个新的容器并运行一个命令

    save    Save an image(s) to a tar archive#保存一个镜像为一个tar包(对应load)

    search    Search the Docker Hub for images  #在docker
hub中搜索镜像

    start    Start one or more stopped containers#启动容器

    stats    Display a live stream of container(s) resource usage statistics  #统计容器使用资源

    stop    Stop a running container  #停止容器

    tag         Tag an image into a repository  #给源中镜像打标签

    top       Display the running processes of a container #查看容器中运行的进程信息

    unpause    Unpause all processes within a container  #取消暂停容器

    version    Show the Docker version information#查看容器版本号

    wait         Block until a container stops, then print its exit code  #截取容器停止时的退出状态值

    Run 'docker COMMAND --help' for more information on a command.  #运行docker命令在帮助可以获取更多信息

2.1查看docker版本

[root@docker ~]# docker version
Client:
 Version:         1.13.1
 API version:     1.26
 Package version: docker-1.13.1-63.git94f4240.el7.centos.x86_64
 Go version:      go1.9.4
 Git commit:      94f4240/1.13.1
 Built:           Fri May 18 15:44:33 2018
 OS/Arch:         linux/amd64

Server:
 Version:         1.13.1
 API version:     1.26 (minimum version 1.12)
 Package version: docker-1.13.1-63.git94f4240.el7.centos.x86_64
 Go version:      go1.9.4
 Git commit:      94f4240/1.13.1
 Built:           Fri May 18 15:44:33 2018
 OS/Arch:         linux/amd64
 Experimental:    false

2.2、获取docker镜像

[root@docker ~]# docker pull alpine
Using default tag: latest
Trying to pull repository docker.io/library/alpine ... 
latest: Pulling from docker.io/library/alpine
ff3a5c916c92: Pull complete 
Digest: sha256:e1871801d30885a610511c867de0d6baca7ed4e6a2573d506bbec7fd3b03873f
Status: Downloaded newer image for docker.io/alpine:latest

# #完成后可以使用该镜像创建一个容器
[root@docker ~]# docker run -it alpine
/ # exit   (备注:退出容器)

2.3、搜索docker镜像

[root@docker ~]# docker search nginx
INDEX       NAME                                                             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
docker.io   docker.io/nginx                                                  Official build of Nginx.                        8785      [OK]       
docker.io   docker.io/jwilder/nginx-proxy                                    Automated Nginx reverse proxy for docker c...   1348                 [OK]
docker.io   docker.io/richarvey/nginx-php-fpm                                Container running Nginx + PHP-FPM capable ...   547                  [OK]
docker.io   docker.io/jrcs/letsencrypt-nginx-proxy-companion                 LetsEncrypt container to use with nginx as...   378                  [OK]
docker.io   docker.io/kong                                                   Open-source Microservice & API Management ...   194       [OK]       
docker.io   docker.io/webdevops/php-nginx                                    Nginx with PHP-FPM                              106                  [OK]
docker.io   docker.io/kitematic/hello-world-nginx                            A light-weight nginx container that demons...   99                   
docker.io   docker.io/zabbix/zabbix-web-nginx-mysql                          Zabbix frontend based on Nginx web-server ...   54                   [OK]
docker.io   docker.io/bitnami/nginx                                          Bitnami nginx Docker Image                      53                   [OK]
docker.io   docker.io/1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5   ubuntu-16-nginx-php-phpmyadmin-mysql-5          36                   [OK]
docker.io   docker.io/linuxserver/nginx                                      An Nginx container, brought to you by Linu...   36                   
docker.io   docker.io/tobi312/rpi-nginx                                      NGINX on Raspberry Pi / armhf                   19                   [OK]
docker.io   docker.io/nginxdemos/nginx-ingress                               NGINX Ingress Controller for Kubernetes . ...   11                   
docker.io   docker.io/blacklabelops/nginx                                    Dockerized Nginx Reverse Proxy Server.          9                    [OK]
docker.io   docker.io/wodby/drupal-nginx                                     Nginx for Drupal container image                9                    [OK]
docker.io   docker.io/webdevops/nginx                                        Nginx container                                 8                    [OK]
docker.io   docker.io/centos/nginx-18-centos7                                Platform for running nginx 1.8 or building...   6                    
docker.io   docker.io/nginxdemos/hello                                       NGINX webserver that serves a simple page ...   6                    [OK]
docker.io   docker.io/1science/nginx                                         Nginx Docker images that include Consul Te...   4                    [OK]
docker.io   docker.io/centos/nginx-112-centos7                               Platform for running nginx 1.12 or buildin...   3                    
docker.io   docker.io/pebbletech/nginx-proxy                                 nginx-proxy sets up a container running ng...   2                    [OK]
docker.io   docker.io/toccoag/openshift-nginx                                Nginx reverse proxy for Nice running on sa...   1                    [OK]
docker.io   docker.io/travix/nginx                                           NGinx reverse proxy                             1                    [OK]
docker.io   docker.io/ansibleplaybookbundle/nginx-apb                        An APB to deploy NGINX                          0                    [OK]
docker.io   docker.io/mailu/nginx                                            Mailu nginx frontend                            0                    [OK]

2.4、获取nginx镜像

[root@docker ~]# docker pull nginx
Using default tag: latest
Trying to pull repository docker.io/library/nginx ... 
latest: Pulling from docker.io/library/nginx
f2aa67a397c4: Pull complete 
1cd0975d4f45: Pull complete 
72fd2d3be09a: Pull complete 
Digest: sha256:3e2ffcf0edca2a4e9b24ca442d227baea7b7f0e33ad654ef1eb806fbd9bedcf0
Status: Downloaded newer image for docker.io/nginx:latest

2.5、查看docker镜像

[root@docker ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
docker.io/nginx     latest              cd5239a0906a        10 days ago         109 MB
docker.io/alpine    latest              3fd9065eaf02        5 months ago        4.15 MB

2.6、导出docker镜像

[root@docker ~]# docker save nginx >/tmp/nginx.tar.gz
[root@docker ~]# cd /tmp/
[root@docker tmp]# ll
total 110068
-rwx------. 1 root root       827 Jun 16 18:21 ks-script-ZH7W_7
-rw-r--r--. 1 root root 112701952 Jun 16 20:27 nginx.tar.gz
drwx------. 2 root root         6 Jun 16 19:16 tmp.25hSDuIH13
drwx------. 2 root root         6 Jun 16 19:00 tmp.a1GZJm8gWJ
drwx------. 2 root root         6 Jun 16 18:48 tmp.Bj9KekX5N2
drwx------. 2 root root         6 Jun 16 19:19 tmp.KbvCptOmFY
drwx------. 2 root root         6 Jun 16 19:18 tmp.l6xSr9LM8Z
drwx------. 2 root root         6 Jun 16 18:39 tmp.LZWQIDBD6x
drwx------. 2 root root         6 Jun 16 18:47 tmp.Pp5lBj4iok
drwx------. 2 root root         6 Jun 16 18:45 tmp.uolCiG0Je0
drwx------. 2 root root         6 Jun 16 18:52 tmp.X3JdR3Kn5w
drwx------. 2 root root         6 Jun 16 18:46 tmp.z46rJXY8Zl
-rw-------. 1 root root         0 Jun 16 18:18 yum.log

[root@docker tmp]# tar xf nginx.tar.gz 
tar: manifest.json: implausibly old time stamp 1970-01-01 08:00:00
tar: repositories: implausibly old time stamp 1970-01-01 08:00:00

[root@docker tmp]# ls
0cd9d7ef134f96804474f8aa2ed3dcd1d145f9abb74edbf0f35443aeacce0f91       repositories    tmp.Pp5lBj4iok
81c31ee0fa7f70bd3946f096d67c77c3f0a6e32190383a4e0956457d478e5b69       tmp.25hSDuIH13  tmp.uolCiG0Je0
947aff29e5c884eddbdcbf6bbd5b9a6cfd6c280deedd2c34da8dd125415a6f95       tmp.a1GZJm8gWJ  tmp.X3JdR3Kn5w
cd5239a0906a6ccf0562354852fae04bc5b52d72a2aff9a871ddb6bd57553569.json  tmp.Bj9KekX5N2  tmp.z46rJXY8Zl
ks-script-ZH7W_7                                                       tmp.KbvCptOmFY  yum.log
manifest.json                                                          tmp.l6xSr9LM8Z
nginx.tar.gz 

#查看镜像的配置信息

[root@docker tmp]# cat manifest.json 
[{"Config":"cd5239a0906a6ccf0562354852fae04bc5b52d72a2aff9a871ddb6bd57553569.json","RepoTags":["docker.io/nginx:latest"],"Layers":["947aff29e5c884eddbdcbf6bbd5b9a6cfd6c280deed
d2c34da8dd125415a6f95/layer.tar","81c31ee0fa7f70bd3946f096d67c77c3f0a6e32190383a4e0956457d478e5b69/layer.tar","0cd9d7ef134f96804474f8aa2ed3dcd1d145f9abb74edbf0f35443aeacce0f
91/layer.tar"]}]

2.7、删除nginx镜像

#查看docker镜像
[root@docker ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
docker.io/nginx     latest              cd5239a0906a        10 days ago         109 MB
docker.io/alpine    latest              3fd9065eaf02        5 months ago        4.15 MB

#删除nginx镜像
[root@docker ~]# docker rmi nginx
Untagged: nginx:latest
Untagged: docker.io/nginx@sha256:3e2ffcf0edca2a4e9b24ca442d227baea7b7f0e33ad654ef1eb806fbd9bedcf0
Deleted: sha256:cd5239a0906a6ccf0562354852fae04bc5b52d72a2aff9a871ddb6bd57553569
Deleted: sha256:530991fd6d0f08206190b1bf71ef51b4534365669785cb461c24d62083f67bb3
Deleted: sha256:725a91602941a09ec4a9ff02dcfde78c2ada44b28780aecd0dfd64d2b2817509
Deleted: sha256:d626a8ad97a1f9c1f2c4db3814751ada64f60aed927764a3f994fcd88363b659

#再查看发现没有了nginx镜像
[root@docker ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
docker.io/alpine    latest              3fd9065eaf02        5 months ago        4.15 MB

3.8、导入docker镜像

#nginx镜像包
[root@docker ~]# cd /tmp/
[root@docker tmp]# ll
-rw-r--r--. 1 root root 112701952 Jun 16 20:27 nginx.tar.gz

#导入nginx镜像
[root@docker tmp]# docker load < /tmp/nginx.tar.gz 
d626a8ad97a1: Loading layer [==================================================>] 58.46 MB/58.46 MB
24ee0a3fd4b9: Loading layer [==================================================>] 54.22 MB/54.22 MB
3ff93588120e: Loading layer [==================================================>] 3.584 kB/3.584 kB
Loaded image: docker.io/nginx:latest

#查看nginx镜像
[root@docker tmp]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
docker.io/nginx     latest              cd5239a0906a        10 days ago         109 MB
docker.io/alpine    latest              3fd9065eaf02        5 months ago        4.15 MB

3.9、docker默认配置文件路径

#docker默认配置文件路径:
cd/var/lib/docker
[root@docker layerdb]# cd/var/lib/docker/image/overlay2/layerdb

[root@docker layerdb]# ll
total 4
drwxr-xr-x. 3 root root   77 Jun 16 19:54 mounts
drwxr-xr-x. 6 root root 4096 Jun 16 20:35 sha256
drwxr-xr-x. 2 root root    6 Jun 16 20:35 tmp

4.1、更换存储目录

vi /usr/lib/systemd/system/docker.service
--graph=/opt/docker
dns服务
默认docker是采用宿主机的dns
可以采用--dns=xxx的方式指定

4.0 查看帮助

[root@docker ~]# docker daemon --help
Command "daemon" is deprecated, and will be removed in Docker 1.16. Please run `dockerd` directly.

Usage: dockerd COMMAND

A self-sufficient runtime for containers.

Options:
--add-registry list Registry to query before a public one (default [])
--add-runtime runtime Register an additional OCI compatible runtime (default [])
--api-cors-header string Set CORS headers in the Engine API
--authorization-plugin list Authorization plugins to load (default [])
--bind-mount-prefix string Specify a prefix to prepend to the source of a bind mount
--bip string Specify network bridge IP
--block-registry list Don't contact given registry (default [])
-b, --bridge string Attach containers to a network bridge
--cgroup-parent string Set parent cgroup for all containers
--cluster-advertise string Address or interface name to advertise
--cluster-store string URL of the distributed storage backend
--cluster-store-opt map Set cluster store options (default map[])
--config-file string Daemon configuration file (default "/etc/docker/daemon.json")
--containerd string Path to containerd socket
--cpu-rt-period int Limit the CPU real-time period in microseconds
--cpu-rt-runtime int Limit the CPU real-time runtime in microseconds
-D, --debug Enable debug mode
--default-gateway ip Container default gateway IPv4 address
--default-gateway-v6 ip Container default gateway IPv6 address
--default-runtime string Default OCI runtime for containers (default "runc")
--default-ulimit ulimit Default ulimits for containers (default [])
--disable-legacy-registry Disable contacting legacy registries
--dns list DNS server to use (default [])
--dns-opt list DNS options to use (default [])
--dns-search list DNS search domains to use (default [])
--enable-secrets Enable Secrets (default true)
--exec-opt list Runtime execution options (default [])
--exec-root string Root directory for execution state files (default "/var/run/docker")
--experimental Enable experimental features
--fixed-cidr string IPv4 subnet for fixed IPs
--fixed-cidr-v6 string IPv6 subnet for fixed IPs
-g, --graph string Root of the Docker runtime (default "/var/lib/docker")
-G, --group string Group for the unix socket (default "docker")
--help Print usage
-H, --host list Daemon socket(s) to connect to (default [])
--icc Enable inter-container communication (default true)
--init Run an init in the container to forward signals and reap processes
--init-path string Path to the docker-init binary
--insecure-registry list Enable insecure registry communication (default [])
--ip ip Default IP when binding container ports (default 0.0.0.0)
--ip-forward Enable net.ipv4.ip_forward (default true)
--ip-masq Enable IP masquerading (default true)
--iptables Enable addition of iptables rules (default true)
--ipv6 Enable IPv6 networking
--label list Set key=value labels to the daemon (default [])
--live-restore Enable live restore of docker when containers are still running
--log-driver string Default driver for container logs (default "json-file")
-l, --log-level string Set the logging level ("debug", "info", "warn", "error", "fatal") (default "info")
--log-opt map Default log driver options for containers (default map[])
--max-concurrent-downloads int Set the max concurrent downloads for each pull (default 3)
--max-concurrent-uploads int Set the max concurrent uploads for each push (default 5)
--metrics-addr string Set default address and port to serve the metrics api on
--mtu int Set the containers network MTU
--oom-score-adjust int Set the oom_score_adj for the daemon (default -500)
-p, --pidfile string Path to use for daemon PID file (default "/var/run/docker.pid")
--raw-logs Full timestamps without ANSI coloring
--registry-mirror list Preferred Docker registry mirror (default [])
--seccomp-profile string Path to seccomp profile
--selinux-enabled Enable selinux support
--shutdown-timeout int Set the default shutdown timeout (default 15)
--signature-verification Check image's signatures on pull (default true)
--skip-schema2-push override push behavior to push only schema1 manifests
-s, --storage-driver string Storage driver to use
--storage-opt list Storage driver options (default [])
--swarm-default-advertise-addr string Set default address or interface for swarm advertised address
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/root/.docker/key.pem")
--tlsverify Use TLS and verify the remote
--userland-proxy Use userland proxy for loopback traffic (default true)
--userland-proxy-path string Path to the userland proxy binary
--userns-remap string User/Group setting for user namespaces
-v, --version Print version information and quit

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

4.1、启动docker容器

#进入容器,按住ctrl不放手,再按p 与 q 

[root@docker ~]# docker run -it alpine sh
/ #

#就会退出容器,容器会在后台运行
 [root@docker ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
12c1c302c454        alpine              "sh"                24 seconds ago      Up 23 seconds                           sharp_swanson

4.2、查看所有容器

[root@docker ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                         PORTS               NAMES
12c1c302c454        alpine              "sh"                About an hour ago   Up About an hour                                   sharp_swanson
3c9d94304a06        alpine              "sh"                About an hour ago   Exited (0) About an hour ago                       laughing_albattani
b1d6f94ed6ee        alpine              "/bin/sh"           2 hours ago         Exited (0) 2 hours ago                             practical_panini

4.3、删除一个正在运行的容器 ,加参数-f  强制删除

[root@docker ~]# docker rm -f 12c1c302c454 
12c1c302c454

4.4、新建容器并启动

所需要的命令主要为docker run

例如,下面的命令输出一个hehe,之后终止容器。

[root@docker ~]# docker run centos /bin/echo "hehe"  #这跟在本地直接执行 /bin/echo'nulige' 

nulige

 
[root@docker ~]# docker run --name mydocker -it centos /bin/bash#启动一个bash终端,允许用户进行交互。

[root@1c6c3f38ea07 /]# pwd

/

[root@1c6c3f38ea07 /]# ls

anaconda-post.log  bindev  etc  homelib  lib64  lost+foundmedia  mnt  optproc  root  runsbin  srv  systmp  usr  var

 
--name:给容器定义一个名称

-i:则让容器的标准输入保持打开。

-t:让Docker分配一个伪终端,并绑定到容器的标准输入上

/bin/bash:执行一个命令

当利用docker run来创建容器时,Docker在后台运行的标准操作包括:

#检查本地是否存在指定的镜像,不存在就从公有仓库下载

#利用镜像创建并启动一个容器

#分配一个文件系统,并在只读的镜像层外面挂在一层可读写层

#从宿主主机配置的网桥接口中桥接一个虚拟接口到容器中去

#从地址池配置一个ip地址给容器

#执行用户指定的应用程序

#执行完毕后容器被终止

#进入容器示例:

    [root@docker ~]# docker run --name mynginx -it nginx /bin/bash
    root@333e614edc8d:/# exit
    exit

4.5、查看容器详细信息

[root@docker ~]# docker inspect b43e19cbd3c4 
[
    {
        "Id": "b43e19cbd3c44e1f51f84ac6ebfa614566efdcd9a374cd4d7fcb06f3d2f28701",
        "Created": "2018-06-16T14:23:17.81844968Z",
        "Path": "nginx",
        "Args": [
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "exited",
            "Running": false,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 0,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2018-06-16T14:23:18.128095349Z",
            "FinishedAt": "2018-06-16T14:27:16.046964575Z"
        },

#省略部分。。。。。 

 #启动容器

[root@docker ~]# docker start 333e614edc8d 
333e614edc8d
[root@docker ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                      PORTS               NAM
333e614edc8d        nginx               "/bin/bash"         About a minute ago   Up 1 second                 80/tcp              myn
2f845a48fd4b        centos              "/bin/bash"         24 minutes ago       Exited (0) 23 minutes ago                       myc
3c9d94304a06        alpine              "sh"                2 hours ago          Exited (0) 2 hours ago 

4.6、attach命令

格式:docker attach 容器名/ID

docker attach是Docker自带的命令。下面示例如何使用该命令。

[root@docker ~]# docker ps -a

CONTAINER
ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES

867e6627a194        centos              "/bin/bash"         10 minutes ago      Exited (127) 47 seconds ago                       mydocker

[root@docker ~]# docker start 867e6627a194  #启动已经停止的容器

867e6627a194

[root@docker ~]# docker attach 867e6627a194  #通过docker attach进入

[root@867e6627a194 /]#    

备注:使用attach命令有时候并不方便。当多个窗口同时attach到同一个容器的时候,所有的窗口都会同步显示,当某个窗口因命令阻塞时,其他窗口也无法执行操作了。

 4.7 exec命令

[root@docker ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
333e614edc8d        nginx               "/bin/bash"         9 minutes ago       Exited (0) 7 seconds ago                        mynginx
2f845a48fd4b        centos              "/bin/bash"         31 minutes ago      Exited (0) 31 minutes ago                       mycentos
3c9d94304a06        alpine              "sh"                2 hours ago         Exited (0) 2 hours ago                          laughing_albattani

#必须先启动容器,要不然就会报错。
[root@docker ~]# docker exec -it mynginx sh
Error response from daemon: Container 333e614edc8d7a3b7c1a3b88231095349885d961d900ada4ce59876484100585 is not running

#启动容器
[root@docker ~]# docker start 333e614edc8d
333e614edc8d

#再用exec命令进入容器中
[root@docker ~]# docker exec -it mynginx sh
# pwd
/

4.8、nsenter命令

nsenter命令

nsenter可以访问另一个进程的名字空间。nsenter需要有root权限。

[root@docker ~]# yum install -y util-linux   #安装包中有需要用到的nsenter

[root@docker ~]# docker ps -a

CONTAINER
ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES

867e6627a194        centos              "/bin/bash"         10 minutes ago      Exited (127) 47 seconds ago                       mydocker

[root@docker ~]# docker start 867e6627a194  #启动已经关闭的容器

867e6627a194

[root@docker ~]# docker inspect --format "{{.State.Pid}}" 867e6627a194  #找到容器的第一个进程PID

20012

[root@docker ~]# nsenter -t 20012 -u -i -n -p  #通过这个PID连接到容器

[root@867e6627a194 ~]# exit

[root@docker ~]# docker ps

CONTAINER
ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

867e6627a194        centos              "/bin/bash"         13 minutes ago      Up 2 minutes                            mydocker


[root@docker ~]# cat in.sh   #编写成脚本快速进入容器空间

#!/bin/sh

PID=$(docker inspect --format "{{.State.Pid}}" $1)

nsenter -t $PID -u -i -n -p


[root@docker ~]# docker ps

CONTAINER
ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

867e6627a194        centos              "/bin/bash"         15 minutes ago      Up 4 minutes                            mydocker

[root@docker ~]# ./in.sh 867e6627a194  #执行脚本跟上容器ID快速进入

[root@867e6627a194 ~]

或
[root@docker ~]# cat docker_init.sh 
#!/bin/sh

PID=$(docker inspect --format "{{.State.Pid}}" $1)

nsenter -t $PID -u -i -n -p

[root@docker ~]# docker ps 
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
333e614edc8d nginx "/bin/bash" 20 minutes ago Up 10 minutes 80/tcp mynginx

[root@docker ~]# sh docker_init.sh mynginx

[root@333e614edc8d ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host 
valid_lft forever preferred_lft forever
20: eth0@if21: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP 
link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.0.2/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::42:acff:fe11:2/64 scope link 
valid_lft forever preferred_lft forever

[root@333e614edc8d ~]# exit
logout

4.9、docker 加-d参数,作用:在后台运行容器

[root@docker ~]# docker run -it -d --name mynginx nginx
c06a7131feab300dd8bdafa102c76a19eb4f74f9e8c3b315934337b0d91e252e
[root@docker ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
c06a7131feab        nginx               "nginx -g 'daemon ..."   15 seconds ago      Up 15 seconds               80/tcp              mynginx
2f845a48fd4b        centos              "/bin/bash"              51 minutes ago      Exited (0) 51 minutes ago                       mycentos
3c9d94304a06        alpine              "sh"                     2 hours ago         Exited (0) 2 hours ago                          laughing_albattani

#如果名称已存在,则需先删除容器 (生产环境需慎用,换个名称再创建就OK了,注意容器名称不能相同。)

[root@docker ~]# docker run -it -d --name mynginx nginx
/usr/bin/docker-current: Error response from daemon: Conflict. The container name "/mynginx" is already in use by container 333e614edc8d7a3b7c1a3b88231095349885d961d900ada4ce59876484100585. You have to remove (or rename) that container to be able to reuse that name..

#删除容器
[root@docker ~]# docker rm -f 333e614edc8d 
333e614edc8d

5.0、停止容器

可以使用docker stop来终止一个运行中的容器。

此外,当Docker容器中指定的应用终结时,容器也自动终止。例如启动一个终端的容器,用户通过exit命令或者ctrl+d来退出终端时,所创建的容器立刻终止。

终止状态的容器可以用docker ps -a命令看到,也可以通过docker start ID 命令来启动容器。

[root@docker ~]# docker ps -a #查看所有容器的情况

CONTAINER
ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS         NAMES

961fd1162c2f        centos              "/bin/bash -c 'while
"   30 minutes ago      Up 30 minutes                           agitated_raman

[root@docker ~]# docker stop 961fd1162c2f  #停止容器

961fd1162c2f

[root@docker ~]# docker ps -a

CONTAINER
ID        IMAGE               COMMAND                  CREATED             STATUS                        PORTS               NAMES

961fd1162c2f        centos              "/bin/bash -c 'while"   31 minutes ago      Exited (137) 27 seconds ago                agitated_raman

#极端方式停止容器(不推荐)

[root@867e6627a194 ~]# docker ps -a -q   #列出所有启动容器的ID

867e6627a194

[root@867e6627a194 ~]# docker kill $(docker ps -a -q)  #批量杀掉启动的容器

./in.sh: 行 4: 20078 已杀死               nsenter -t $PID -u -i -n -p

5.1、查看docker 容器日志

#前提条件,docker容器已启动

[root@docker ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
c06a7131feab        nginx               "nginx -g 'daemon ..."   7 minutes ago       Up About a minute           80/tcp              mynginx
2f845a48fd4b        centos              "/bin/bash"              59 minutes ago      Exited (0) 58 minutes ago                       mycentos
3c9d94304a06        alpine              "sh"                     2 hours ago         Exited (0) 2 hours ago                          laughing_albattani

#进入容器
[root@docker ~]# docker exec -it mynginx sh
# exit

#查看容器详细信息
[root@docker ~]# docker inspect c06a7131feab
#上面省略部分..............
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "a7e1f14866e804866e8424c041f96e2361daf55cc70307c8523082c60227e461",
                    "EndpointID": "2df73a720f5a0a1808281ba0505c12a23c9fd76fbbe28ba1f46fe00d77ec8547",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02"
                }
            }
        }
    }
]

#访问容器
[root@docker ~]# curl 172.17.0.2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

#查看容器日志
[root@docker ~]# docker logs mynginx
172.17.0.1 - - [16/Jun/2018:15:36:25 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

#查看连续日志 (备注:操作方法:再开一个终端,不停的访问:curl 172.17.0.2)

    [root@docker ~]# docker logs -f mynginx
    172.17.0.1 - - [16/Jun/2018:15:36:25 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
    172.17.0.1 - - [16/Jun/2018:15:40:53 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
    172.17.0.1 - - [16/Jun/2018:15:40:55 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
    172.17.0.1 - - [16/Jun/2018:15:40:56 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
    172.17.0.1 - - [16/Jun/2018:15:40:57 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

 

三、docker核心原理

 

 

 

 

 

  

 

posted @ 2018-06-16 10:50  努力哥  阅读(994)  评论(0编辑  收藏  举报