如来神掌第四式第一招----Docker基础用法

 

###############################################################################
# Name : Mahavairocana                                                                                                                                           
# Author : Mahavairocana                                                                                                                                         
# QQ : 10353512                                                                                                                                                    
# WeChat : shenlan-qianlan                                                                                                                                      
# Blog : http://www.cnblogs.com/Mahavairocana/                                                                                                       
# Description : You are welcome to reprint, or hyperlinks to indicate the                                                                        
#                    source of the article, as well as author information.                                                                                
###############################################################################

 

 

什么是Docker?

Docker 是世界领先的软件容器平台。开发人员利用 Docker 可以消除协作编码时“在我的机器上可正常工作”的问题。运维人员利用 Docker 可以在隔离容器中并行运行和管理应用,获得更好的计算密度。企业利用 Docker 可以构建敏捷的软件交付管道,以更快的速度、更高的安全性和可靠的信誉为 Linux 和 Windows Server 应用发布新功能。

Docker 属于 Linux 容器的一种封装,提供简单易用的容器使用接口。它是目前最流行的 Linux 容器解决方案。Docker 将应用程序与该程序的依赖,打包在一个文件里面。运行这个文件,就会生成一个虚拟容器。程序在这个虚拟容器里运行,就好像在真实的物理机上运行一样。有了 Docker,就不用担心环境问题。

总体来说,Docker 的接口相当简单,用户可以方便地创建和使用容器,把自己的应用放入容器。容器还可以进行版本管理、复制、分享、修改,就像管理普通的代码一样。

Docker 最初是 dotCloud 公司创始人 Solomon Hykes 在法国期间发起的一个公司内部项目,它是基于 dotCloud 公司多年云服务技术的一次革新,并于 2013 年 3 月以 Apache 2.0 授权协议开源,主要项目代码在 GitHub 上进行维护。Docker 项目后来还加入了 Linux 基金会,并成立推动 开放容器联盟(OCI)。

Docker 自开源后受到广泛的关注和讨论,至今其 GitHub 项目已经超过 4 万 6 千个星标和一万多个 fork。甚至由于 Docker 项目的火爆,在 2013 年底,dotCloud 公司决定改名为 Docker。Docker 最初是在 Ubuntu 12.04 上开发实现的;Red Hat 则从 RHEL 6.5 开始对 Docker 进行支持;Google 也在其 PaaS 产品中广泛应用 Docker。

为什么要使用Docker

容器除了运行其中应用外,基本不消耗额外的系统资源,使得应用的性能很高,同时系统的开销尽量小。传统虚拟机方式运行 10 个不同的应用就要起 10 个虚拟机,而Docker 只需要启动 10 个隔离的应用即可。

具体说来,Docker 在如下几个方面具有较大的优势。

1、更快速的交付和部署

对开发和运维(devop)人员来说,最希望的就是一次创建或配置,可以在任意地方正常运行。

开发者可以使用一个标准的镜像来构建一套开发容器,开发完成之后,运维人员可以直接使用这个容器来部署代码。 Docker 可以快速创建容器,快速迭代应用程序,并让整个过程全程可见,使团队中的其他成员更容易理解应用程序是如何创建和工作的。 Docker 容器很轻很快!容器的启动时间是秒级的,大量地节约开发、测试、部署的时间。

2、更高效的虚拟化

Docker 容器的运行不需要额外的 hypervisor 支持,它是内核级的虚拟化,因此可以实现更高的性能和效率。

3、更轻松的迁移和扩展

Docker 容器几乎可以在任意的平台上运行,包括物理机、虚拟机、公有云、私有云、个人电脑、服务器等。 这种兼容性可以让用户把一个应用程序从一个平台直接迁移到另外一个。

4、更简单的管理

使用 Docker,只需要小小的修改,就可以替代以往大量的更新工作。所有的修改都以增量的方式被分发和更新,从而实现自动化并且高效的管理。

Docker vs VM

从下图可以看出,VM是一个运行在宿主机之上的完整的操作系统,VM运行自身操作系统会占用较多的CPU、内存、硬盘资源。Docker不同于VM,只包含应用程序以及依赖库,基于libcontainer运行在宿主机上,并处于一个隔离的环境中,这使得Docker更加轻量高效,启动容器只需几秒钟之内完成。由于Docker轻量、资源占用少,使得Docker可以轻易的应用到构建标准化的应用中。但Docker目前还不够完善,比如隔离效果不如VM,共享宿主机操作系统的一些基础库等;网络配置功能相对简单,主要以桥接方式为主;查看日志也不够方便灵活。

Docker(一):Docker入门教程

Docker 在容器的基础上,进行了进一步的封装,从文件系统、网络互联到进程隔离等等,极大的简化了容器的创建和维护。使得 Docker 技术比虚拟机技术更为轻便、快捷。

作为一种新兴的虚拟化方式,Docker 跟传统的虚拟化方式相比具有众多的优势。Docker 容器的启动可以在秒级实现,这相比传统的虚拟机方式要快得多;Docker 对系统资源的利用率很高,一台主机上可以同时运行数千个 Docker 容器。

相关概念

Docker是CS架构,主要有两个概念:

  • Docker daemon: 运行在宿主机上,Docker守护进程,用户通过Docker client(Docker命令)与Docker daemon交互
  • Docker client: Docker 命令行工具,是用户使用Docker的主要方式,Docker client与Docker daemon通信并将结果返回给用户,Docker client也可以通过socket或者RESTful api访问远程的Docker daemon

Docker(一):Docker入门教程

了解了Docker的组成,再来了解一下Docker的三个主要概念:

  • Docker image:镜像是只读的,镜像中包含有需要运行的文件。镜像用来创建container,一个镜像可以运行多个container;镜像可以通过Dockerfile创建,也可以从Docker hub/registry上下载。
  • Docker container:容器是Docker的运行组件,启动一个镜像就是一个容器,容器是一个隔离环境,多个容器之间不会相互影响,保证容器中的程序运行在一个相对安全的环境中。
  • Docker hub/registry: 共享和管理Docker镜像,用户可以上传或者下载上面的镜像,官方地址为https://registry.hub.docker.com/,也可以搭建自己私有的Docker registry。

镜像就相当于打包好的版本,镜像启动之后运行在容器中,仓库就是装存储镜像的地方。

 

Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源。

Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级、可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。

容器是完全使用沙箱机制,相互之间不会有任何接口(类似 iPhone 的 app),更重要的是容器性能开销极低。

 

Docker-ce:
    Docker CE是免费的Docker产品的新名称,Docker CE包含了完整的Docker平台,非常适合开发人员和运维团队构建容器APP。事实上,Docker CE 17.03,可理解为Docker 1.13.1的Bug修复版本。因此,从Docker 1.13升级到Docker CE 17.03风险相对是较小的。
    大家可前往Docker的RELEASE log查看详情https://github.com/docker/docker/releases 。
    Docker公司认为,Docker CE和EE版本的推出为Docker的生命周期、可维护性以及可升级性带来了巨大的改进。
    
Containers:启动容器:基于镜像启动,在镜像基础上,为一个容器创建一个专用可写层。
Images: 需要加载到本地,(通过HTTP,HTTPS加载),下载速度,取决于网速,dockerhub存放在国外,国内有阿里云(需要注册专用加速账号) 、中科大、清华等。

Docker 组成部分

 

Docker 对象:

  Docker Objects:
When you use docker, you are creating and using images containers, networks, volumes,plugins, and other objects.
    IMAGES:
        An imagesis a read-only template with instructions for creating a docker container.
        Often,an image is based on another image ,with some additional custimaization.
        You might create your own images or you might only use those created by others and published in a registry.
    CONTAINERS:
        A container is a runnable insance of an image.
        You cancreate, run ,stop move or delete a container using the docker apii or cli.
You can connect a container to one or more networks, attach storage to It ,or even create a new image based on its current state.

Docker 的优点

    • 1、简化程序:
      Docker 让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,便可以实现虚拟化。Docker改变了虚拟化的方式,使开发者可以直接将自己的成果放入Docker中进行管理。方便快捷已经是 Docker的最大优势,过去需要用数天乃至数周的 任务,在Docker容器的处理下,只需要数秒就能完成。

    • 2、避免选择恐惧症:
      如果你有选择恐惧症,还是资深患者。Docker 帮你 打包你的纠结!比如 Docker 镜像;Docker 镜像中包含了运行环境和配置,所以 Docker 可以简化部署多种应用实例工作。比如 Web 应用、后台应用、数据库应用、大数据应用比如 Hadoop 集群、消息队列等等都可以打包成一个镜像部署。

    • 3、节省开支:
      一方面,云计算时代到来,使开发者不必为了追求效果而配置高额的硬件,Docker 改变了高性能必然高价格的思维定势。Docker 与云的结合,让云空间得到更充分的利用。不仅解决了硬件管理的问题,也改变了虚拟化的方式。

namespace 对内核要求(centos7系列基本满足需求)

 

 

 

安装

1、修改默认站点,加快安装速度

[root@docker--0001 yum.repos.d]# yum -y install wget
[root@docker--0001 yum.repos.d]# wget https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
[root@docker--0001 yum.repos.d]# sed -i s@https://download.docker.com/@https://mirrors.tuna.tsinghua.edu.cn/docker-ce/@g /etc/yum.repos.d/docker-ce.repo    ### 替换清华的加速站点。
2、查看是否正常加载
[root@docker--0001 yum.repos.d]# yum repolist
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
repo id                                                                               repo name                                                                               status
docker-ce-stable/x86_64                                                               Docker CE Stable - x86_64                                                               33
repolist: 33
3、查看安装包
[root@docker--0001 yum.repos.d]# yum install docker-ce
Installed:
  docker-ce.x86_64 3:18.09.2-3.el7                                                                                                                                                  

Dependency Installed:
  container-selinux.noarch 2:2.55-1.el7         containerd.io.x86_64 0:1.2.2-3.3.el7         docker-ce-cli.x86_64 1:18.09.2-3.el7         libseccomp.x86_64 0:2.3.1-3.el7        
  libtool-ltdl.x86_64 0:2.4.2-22.el7_3         

Dependency Updated:
  libselinux.x86_64 0:2.5-12.el7              libselinux-python.x86_64 0:2.5-12.el7                libselinux-utils.x86_64 0:2.5-12.el7  libsemanage.x86_64 0:2.5-11.el7            
  libsemanage-python.x86_64 0:2.5-11.el7      libsepol.x86_64 0:2.5-8.1.el7                        policycoreutils.x86_64 0:2.5-22.el7   policycoreutils-python.x86_64 0:2.5-22.el7 
  selinux-policy.noarch 0:3.13.1-192.el7_5.3  selinux-policy-targeted.noarch 0:3.13.1-192.el7_5.3  setools-libs.x86_64 0:3.3.8-2.el7    

Complete!
ocker默认配置文件/etc/docker/daemon.json ##需要自己创建
[root@docker--0001 docker]# ls
daemon.json  
添加加速器
[root@docker--0001 docker]# vim daemon.json 
{
        "registry-mirrors": ["https://registry.docker-cn.com"]
}


启动docker
[root@docker--0001 docker]# systemctl start docker.service
[root@docker--0001 docker]# systemctl status docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: active (running) since Sat 2019-02-23 14:25:49 CST; 11s ago
     Docs: https://docs.docker.com
 Main PID: 13466 (dockerd)
   Memory: 51.6M
   CGroup: /system.slice/docker.service
           ├─13466 /usr/bin/dockerd -H fd://
           └─13488 containerd --config /var/run/docker/containerd/containerd.toml --log-level info

Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.728771457+08:00" level=info msg="pickfirstBalancer: HandleSubConnStateChange: 0xc42016...odule=grpc
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.758203345+08:00" level=info msg="Graph migration to content-addressability took 0.00 seconds"
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.758658814+08:00" level=info msg="Loading containers: start."
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.853024184+08:00" level=info msg="Default bridge (docker0) is assigned with an IP addre...P address"
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.887691637+08:00" level=info msg="Loading containers: done."
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.904029319+08:00" level=warning msg="Not using native diff for overlay2, this may cause...r=overlay2
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.904179876+08:00" level=info msg="Docker daemon" commit=6247962 graphdriver(s)=overlay2...on=18.09.2
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.904286929+08:00" level=info msg="Daemon has completed initialization"
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.921887529+08:00" level=info msg="API listen on /var/run/docker.sock"
Feb 23 14:25:49 docker--0001.novalocal systemd[1]: Started Docker Application Container Engine.
Hint: Some lines were ellipsized, use -l to show in full.


Docker 命令

[root@docker--0001 docker]# docker version   #查询版本信息
Client:
 Version:           18.09.2
 API version:       1.39
 Go version:        go1.10.6
 Git commit:        6247962
 Built:             Sun Feb 10 04:13:27 2019
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.2
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.6
  Git commit:       6247962
  Built:            Sun Feb 10 03:47:25 2019
  OS/Arch:          linux/amd64
  Experimental:     false


[root@docker--0001 docker]# docker info  #查询详细信息
Containers: 0  #容器数量
 Running: 0        #运行状态数量
 Paused: 0        #暂停状态数量
 Stopped: 0        #停止状态数量
Images: 0        #镜像个数
Server Version: 18.09.2
Storage Driver: overlay2  ##存储文件系统
 Backing Filesystem: extfs
 Supports d_type: true
 Native Overlay Diff: false
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:   #支持插件
 Volume: local  #存储插件
 Network: bridge host macvlan null overlay  #网络插件
 Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog  #日志插件
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 9754871865f7fe2f4e74d43e2fc7ccd237edcbce
runc version: 09c8266bf2fcf9519a651b04ae54c967b9ab86ec
init version: fec3683
Security Options:
 seccomp
  Profile: default
Kernel Version: 3.10.0-514.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 7.639GiB
Name: docker--0001.novalocal
ID: 34DE:NHPU:BAYB:UZAR:ZDZX:T73W:7DZQ:J4YD:AMVR:NUNY:UCSL:JL2W
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://registry.docker-cn.com/  #自己配置加速镜像地址
Live Restore Enabled: false
Product License: Community Engine

常用操作:
docker search: 根据名称搜索自己需要的镜像
docker pull:根据名称下载自己需要的镜像
docker push:根据名称上传自己需要的镜像
docker create: 创建容器
docker start/stop/restart :启动一个或者多个容器
docker run: 运行一个或者多个容器
docker attach:连接到一个运行的容器
docker ps:列车当前容器
docker kill:杀掉一个或者多个容器,强制关闭
docker logs:获取容器日志
docker rm :删除一个或者多个容器
docker rmi: 删除镜像  == docker image rm 
docker pause(unpause):挂起或者取消挂起容器

三个命令可以替换为docker image search pull push

运行docker:
[root@docker--0001 docker]# docker search nginx
NAME                                                   DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
nginx   ##顶级仓库 一般为官方                                                Official build of Nginx.                        10956               [OK]                
jwilder/nginx-proxy      ##用户仓库、项目仓库                              Automated Nginx reverse proxy for docker con…   1538                                    [OK]
richarvey/nginx-php-fpm                                Container running Nginx + PHP-FPM capable of…   685                                     [OK]
jrcs/letsencrypt-nginx-proxy-companion                 LetsEncrypt container to use with nginx as p…   485                                     [OK]
webdevops/php-nginx                                    Nginx with PHP-FPM                              123                                     [OK]
kitematic/hello-world-nginx                            A light-weight nginx container that demonstr…   121                                     
zabbix/zabbix-web-nginx-mysql                          Zabbix frontend based on Nginx web-server wi…   91                                      [OK]
bitnami/nginx                                          Bitnami nginx Docker Image                      62                                      [OK]
linuxserver/nginx                                      An Nginx container, brought to you by LinuxS…   55                                      
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5   ubuntu-16-nginx-php-phpmyadmin-mysql-5          49                                      [OK]
zabbix/zabbix-web-nginx-pgsql                          Zabbix frontend based on Nginx with PostgreS…   28                                      [OK]
tobi312/rpi-nginx                                      NGINX on Raspberry Pi / armhf                   24                                      [OK]
nginx/nginx-ingress                                    NGINX Ingress Controller for Kubernetes         17                                      
blacklabelops/nginx                                    Dockerized Nginx Reverse Proxy Server.          12                                      [OK]
wodby/drupal-nginx                                     Nginx for Drupal container image                12                                      [OK]
nginxdemos/hello                                       NGINX webserver that serves a simple page co…   11                                      [OK]
schmunk42/nginx-redirect                               A very simple container to redirect HTTP tra…   11                                      [OK]
centos/nginx-18-centos7                                Platform for running nginx 1.8 or building n…   10                                      
centos/nginx-112-centos7                               Platform for running nginx 1.12 or building …   7                                       
1science/nginx                                         Nginx Docker images that include Consul Temp…   4                                       [OK]
mailu/nginx                                            Mailu nginx frontend                            3                                       [OK]
travix/nginx                                           NGinx reverse proxy                             2                                       [OK]
toccoag/openshift-nginx                                Nginx reverse proxy for Nice running on same…   1                                       [OK]
wodby/nginx                                            Generic nginx                                   0                                       [OK]
ansibleplaybookbundle/nginx-apb                        An APB to deploy NGINX                          0                                       [OK]
You have new mail in /var/spool/mail/root


alpine 版本:体积小,能够提供基础环境,下载内容量比较小,缺点:缺少调试工具
建议自己做镜像,添加相关调试工具,dockerhub做法不一定能满足我们需要。

下载镜像
[root@docker--0001 docker]# docker image pull nginx:1.14-alpine 
1.14-alpine: Pulling from library/nginx
6c40cc604d8e: Pull complete 
76679ad9f124: Pull complete 
389a52582f93: Pull complete 
496e2dd2b91a: Pull complete 
Digest: sha256:b96aeeb1687703c49096f4969358d44f8520b671da94848309a3ba5be5b4c632
Status: Downloaded newer image for nginx:1.14-alpine

[root@docker--0001 docker]# docker pull busybox
Using default tag: latest
latest: Pulling from library/busybox
697743189b6d: Pull complete 
Digest: sha256:061ca9704a714ee3e8b80523ec720c64f6209ad3f97c0ff7cb9ec7d19f15149f
Status: Downloaded newer image for busybox:latest

列出当前镜像
[root@docker--0001 docker]# docker image ls
REPOSITORY仓库名称 TAG 标签             IMAGE ID 镜像ID    CREATED创建时间      SIZE 大小
busybox             latest              d8233ab899d4        8 days ago          1.2MB
nginx               1.14-alpine         66952fd0a8ef        3 weeks ago         16MB

[root@docker--0001 docker]# docker run --name b1 -it busybox:latest   ##运行一个b1名称的容器
/ # hostname 
82dda7c9d5c0  #查看容器名称
/ # httpd -h  #查看httpd命令带的选项
httpd: option requires an argument -- h
BusyBox v1.30.1 (2019-02-14 18:58:02 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
/ # vi /data/html/index.html
/ # httpd  -f -h /data/html/


[root@docker--0001 ~]# docker ps  #查看运行中的容器
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
82dda7c9d5c0        busybox:latest      "sh"                3 minutes ago       Up 3 minutes                            b1
      
[root@docker--0001 ~]# docker inspect b1 查看B1详细信息。
[
    {
        "Id": "82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e",
        "Created": "2019-02-23T07:02:30.424416599Z",
        "Path": "sh",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 14227,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-02-23T07:02:30.694772084Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:d8233ab899d419c58cf3634c0df54ff5d8acc28f8173f09c21df4a07229e1205",
        "ResolvConfPath": "/var/lib/docker/containers/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e/hostname",
        "HostsPath": "/var/lib/docker/containers/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e/hosts",
        "LogPath": "/var/lib/docker/containers/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e-json.log",
        "Name": "/b1",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "shareable",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/867fc50ea1c6c597dcdf504e8ddab221bacb7e31df4b720d54feab66176b0eca-init/diff:/var/lib/docker/overlay2/9e66a9e007a10a0f5816aff408cac730931e31c694fee0ce058441400ddbda4a/diff",
                "MergedDir": "/var/lib/docker/overlay2/867fc50ea1c6c597dcdf504e8ddab221bacb7e31df4b720d54feab66176b0eca/merged",
                "UpperDir": "/var/lib/docker/overlay2/867fc50ea1c6c597dcdf504e8ddab221bacb7e31df4b720d54feab66176b0eca/diff",
                "WorkDir": "/var/lib/docker/overlay2/867fc50ea1c6c597dcdf504e8ddab221bacb7e31df4b720d54feab66176b0eca/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "82dda7c9d5c0",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "sh"
            ],
            "ArgsEscaped": true,
            "Image": "busybox:latest",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "cae35f9169432abe87730bd9027ccbd9e3477bf25a7309878abfed0ab348f117",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/cae35f916943",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "06b5ca3f68c11278b721c2ccf0096c0b038529ca916bbe1d9a3d353be3d4f0f6",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "7cdf0e083ccf918fb3a9832a74ebad24b58f026cfad7f36ecbfec163e895ca8f",
                    "EndpointID": "06b5ca3f68c11278b721c2ccf0096c0b038529ca916bbe1d9a3d353be3d4f0f6",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]
[root@docker--0001 ~]# curl 172.17.0.2
liuqi test

/ # httpd  -f -h /data/html/
^C  ##ctrl 结束运行状态
/ # exit #退出容器
You have new mail in /var/spool/mail/root
[root@docker--0001 docker]# docker ps #查询无运行中的容器,不运行默认不显示
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@docker--0001 docker]# docker ps -a #查看所有状态容器= docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES
82dda7c9d5c0        busybox:latest      "sh"                8 minutes ago       Exited (130) 12 seconds ago                       b1

[root@docker--0001 docker]#docker start -ai b1 ##启动
[root@docker--0001 docker]# docker rm b1 ##删除
b1
[root@docker--0001 docker]# docker ps -a          #删除后查询
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES


[root@docker--0001 docker]# docker run --name web1 -d nginx:1.14-alpine #运行一个nginx容器
48594db2a06ac8a9bf093cb0e44d3141dabf72c6f44310efeb734ae50f98461c
[root@docker--0001 docker]# docker ps 查看运行状态 端口为默认开放
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
48594db2a06a        nginx:1.14-alpine   "nginx -g 'daemon of…"   7 seconds ago       Up 6 seconds        80/tcp              web1
[root@docker--0001 docker]# docker
docker        dockerd       dockerd-ce    docker-init   docker-proxy  


进入docker执行命令
[root@docker--0001 docker]# docker exec -it web1 /bin/sh 
/ # ps
PID   USER     TIME  COMMAND
    1 root      0:00 nginx: master process nginx -g daemon off;
    6 nginx     0:00 nginx: worker process
    7 root      0:00 /bin/sh
   12 root      0:00 ps


获取容器日志:
[root@docker--0001 docker]# docker logs web1
172.17.0.1 - - [23/Feb/2019:07:18:12 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
172.17.0.1 - - [23/Feb/2019:07:19:14 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

 Docker run 参数

[root@docker--0001 docker]# docker run --help

Usage:  docker 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  ##当虚拟机加入一个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

 Docker 生命周期管理

 

posted on 2019-02-23 15:53  Mahavairocana  阅读(662)  评论(0编辑  收藏  举报

导航