• docker镜像、容器使用、安装部署nginx


    1.docker镜像

      这里需要用到两条命令。

    1.拉取镜像命令 

    C:UsersAdministrator>docker pull --help
    
    Usage:  docker pull [OPTIONS] NAME[:TAG|@DIGEST]
    
    Pull an image or a repository from a registry
    
    Options:
      -a, --all-tags                Download all tagged images in the repository
          --disable-content-trust   Skip image verification (default true)

      这条命令用来从仓库拉取镜像

    比如我们从docker默认仓库拉取第一个镜像。这个镜像的名称可以在docker仓库搜索。

    C:UsersAdministrator>docker pull hello-world
    Using default tag: latest
    latest: Pulling from library/hello-world
    1b930d010525: Pull complete
    Digest: sha256:9572f7cdcee8591948c2963463447a53466950b3fc15a247fcad1917ca215a2f
    Status: Downloaded newer image for hello-world:latest

    2.查看本地镜像命令

    C:UsersAdministrator>docker images --help
    
    Usage:  docker images [OPTIONS] [REPOSITORY[:TAG]]
    
    List images
    
    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

    例如:列出本地的镜像列表

    C:UsersAdministrator>docker images
    REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
    hello-world         latest              fce289e99eb9        13 months ago       1.84kB

    REPOSITORY:表示镜像的仓库源。镜像名称
    TAG:镜像的标签
    IMAGE ID:镜像ID
    CREATED:镜像创建时间
    SIZE:镜像大小

      同一仓库源可以有多个 TAG,代表这个仓库源的不同个版本,如 ubuntu 仓库源里,有 15.10、14.04 等多个不同的版本,我们使用 REPOSITORY:TAG 来定义不同的镜像。

    3.查找镜像

    C:UsersAdministrator>docker search java
    NAME                                     DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
    node                                     Node.js is a JavaScript-based platform for s…   8439                [OK]
    tomcat                                   Apache Tomcat is an open source implementati…   2638                [OK]
    openjdk                                  OpenJDK is an open-source implementation of …   2112                [OK]
    java                                     Java is a concurrent, class-based, and objec…   1976                [OK]
    ghost                                    Ghost is a free and open source blogging pla…   1102                [OK]
    couchdb                                  CouchDB is a database that uses JSON for doc…   324                 [OK]
    jetty                                    Jetty provides a Web server and javax.servle…   322                 [OK]
    groovy                                   Apache Groovy is a multi-faceted language fo…   84                  [OK]
    lwieske/java-8                           Oracle Java 8 Container - Full + Slim - Base…   46                                      [OK]
    nimmis/java-centos                       This is docker images of CentOS 7 with diffe…   42                                      [OK]
    fabric8/java-jboss-openjdk8-jdk          Fabric8 Java Base Image (JBoss, OpenJDK 8)      28                                      [OK]
    frekele/java                             docker run --rm --name java frekele/java        12                                      [OK]
    blacklabelops/java                       Java Base Images.                               8                                       [OK]
    bitnami/java                             Bitnami Java Docker Image                       5                                       [OK]
    cloudbees/java-with-docker-client        Java image with Docker client installed, use…   4                                       [OK]
    rightctrl/java                           Oracle Java                                     3                                       [OK]
    cfje/java-test-applications              Java Test Applications CI Image                 2
    zoran/java10-sjre                        Slim Docker image based on AlpineLinux with …   2                                       [OK]

    NAME: 镜像仓库源的名称
    DESCRIPTION: 镜像的描述
    OFFICIAL: 是否 docker 官方发布
    stars: 类似 Github 里面的 star,表示点赞、喜欢的意思。
    AUTOMATED: 自动构建。

    4.删除镜像

    C:UsersAdministrator>docker rmi hello-world
    Error response from daemon: conflict: unable to remove repository reference "hello-world" (must force) - container fd680c09ec41 is using its referenced image fce289e99eb9

      运行中的镜像不能删除,需要先停止镜像后删除。

    C:UsersAdministrator>docker ps -a
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
    fd680c09ec41        hello-world         "/hello"            25 minutes ago      Exited (0) 25 minutes ago                       elegant_chaum
    
    C:UsersAdministrator>docker rm fd680c09ec41 #删除容器(可以加-f参数强制删除)
    fd680c09ec41
    
    C:UsersAdministrator>docker ps -a
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    
    C:UsersAdministrator>docker rmi hello-world
    Untagged: hello-world:latest
    Untagged: hello-world@sha256:9572f7cdcee8591948c2963463447a53466950b3fc15a247fcad1917ca215a2f
    Deleted: sha256:fce289e99eb9bca977dae136fbe2a82b6b7d4c372474c9235adc1741675f587e
    Deleted: sha256:af0b15c8625bb1938f1d7b17081031f649fd14e6b233688eea3c5483994a66a3
    
    C:UsersAdministrator>docker images
    REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

    5.构建镜像

      参考:https://www.cnblogs.com/qlqwjy/p/12322861.html

    2.docker容器

      docker镜像运行起来就是docker容器。

    0.创建一个容器但是不启动

    docker create :创建一个新的容器但不启动它。用法同docker run

    语法:

    docker create [OPTIONS] IMAGE [COMMAND] [ARG...]

    1.启动容器

    运行docker镜像需要用到docker run命令,语法如下:

    C:UsersAdministrator>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 "15")
          --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

    例如:运行上面的hello-world镜像。

    C:UsersAdministrator>docker run hello-world
    
    Hello from Docker!
    This message shows that your installation appears to be working correctly.
    
    To generate this message, Docker took the following steps:
     1. The Docker client contacted the Docker daemon.
     2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
        (amd64)
     3. The Docker daemon created a new container from that image which runs the
        executable that produces the output you are currently reading.
     4. The Docker daemon streamed that output to the Docker client, which sent it
        to your terminal.
    
    To try something more ambitious, you can run an Ubuntu container with:
     $ docker run -it ubuntu bash
    
    Share images, automate workflows, and more with a free Docker ID:
     https://hub.docker.com/
    
    For more examples and ideas, visit:
     https://docs.docker.com/get-started/

    2.查看所有启动的容器

    C:UsersAdministrator>docker ps -a
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
    fd680c09ec41        hello-world         "/hello"            19 minutes ago      Exited (0) 19 minutes ago                       elegant_chaum

      加-a查看所有容器,包括已经停止的容器,不加-a是查看启动的容器。

    3.启动已停止运行的容器

    docker start 6f834248b43f

    4.后台运行容器

    C:UsersAdministrator>docker run -d hello-world
    338d2e090bcc658618f8ea85dccfdfc3565ddbbd30c2a4178f6f749e153aa333

    5.进入容器

      在使用 -d 参数时,容器启动后会进入后台。此时想要进入容器,可以通过以下指令进入:

    docker attach

    docker exec:推荐大家使用 docker exec 命令,因为此退出容器终端,不会导致容器的停止

    (1)attach 命令

    docker attach 1e560fca3906

       注意: 如果从这个容器退出,会导致容器的停止。

    (2)exec命令

    docker exec -it 243c32535da7 /bin/bash

      -i表示交互式的,-t表示开启一个虚拟终端。

       注意: 如果从这个容器退出,不会导致容器的停止

    补充:有时候进不去容器,报错:  starting container process caused "exec: "/bin/bash": stat /bin/bash: no such file or directory"

    上述错误说没有此类文件或目录/bin/bash,那么使用下面的命令.

    docker exec -it <containter_id | containter_name> sh

    6.停止一个容器

    语法:

    docker stop <容器 ID>

    7.重启容器

    停止的容器可以通过 docker restart 重启:

    docker restart <容器 ID>

    8.删除容器

    C:UsersAdministrator>docker rm -f 1ef79f1c7da6
    1ef79f1c7da6

    3.执行图如下:

    docker pull:向docker守护进程(服务)发送请求,先在本机检查镜像是否存在,如果存在并且是你要的版本就不做操作;如果不存在从仓库拉取镜像保存到本地。

    docker run:向docker守护进程(服务)发送请求,先在本机检查镜像是否存在,如果不存在执行一次docker pull操作;之后运行镜像。

    4.安装nginx镜像

    nginx镜像与之前的hello-world镜像的区别:

    (1)持久运行的容器

    (2)前台挂起&后台运行

    (3)后台运行的需要进入容器内部。

    1.下载nginx镜像 

    https://c.163.com/hub#/library/search?keyword=nginx网易docker仓库搜索nginx,如下:

       可以看到有两个nginx,第一个带的是docker的图标,代表是从docker仓库同步过来的镜像。第二个是网易自己的,在这里下载docker自带的。我们点击第一个library/nginx

     复制下载地址之后docker pull,如下:

    C:UsersAdministrator>docker pull hub.c.163.com/library/nginx:latest
    latest: Pulling from library/nginx
    5de4b4d551f8: Pull complete
    d4b36a5e9443: Pull complete
    0af1f0713557: Pull complete
    Digest: sha256:f84932f738583e0169f94af9b2d5201be2dbacc1578de73b09a6dfaaa07801d6
    Status: Downloaded newer image for hub.c.163.com/library/nginx:latest

    查看本地所有镜像:

    C:UsersAdministrator>docker images
    REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE
    hello-world                   latest              fce289e99eb9        13 months ago       1.84kB
    hub.c.163.com/library/nginx   latest              46102226f2fd        2 years ago         109MB

    2.启动nginx

    如下:这种方式启动我们不能占用窗口,否则会停掉

    C:UsersAdministrator>docker run hub.c.163.com/library/nginx

    新开窗口查看容器:

    C:UsersAdministrator>docker ps
    CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS               NAMES
    17da2264a64c        hub.c.163.com/library/nginx   "nginx -g 'daemon of…"   49 seconds ago      Up 46 seconds       80/tcp              musing_clarke

    3.后台启动nginx(-d参数)

    C:UsersAdministrator>docker run -d hub.c.163.com/library/nginx
    29d978bb4001613e3a4777b2c8ce2b30b68b9a7ecf5a629bfb3a9e62f0b7261e
    
    C:UsersAdministrator>docker ps -a
    CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS               NAMES
    29d978bb4001        hub.c.163.com/library/nginx   "nginx -g 'daemon of…"   5 seconds ago       Up 2 seconds        80/tcp

      返回的是容器的ID。

    如果需要进入后台运行的nginx,可以用exec。

    C:UsersAdministrator>docker ps
    CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS               NAMES
    29d978bb4001        hub.c.163.com/library/nginx   "nginx -g 'daemon of…"   4 minutes ago       Up 4 minutes        80/tcp              romantic_lumiere
    
    C:UsersAdministrator>docker exec --help
    
    Usage:  docker 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
    
    C:UsersAdministrator>docker exec -it 29d bash
    root@29d978bb4001:/#

      注意:上面containerid只输入了29d,因为我们本地只有一个docker容器,所以输入简单的也可以找到。i参数表示交互式,t表示开启一个虚拟终端。后面的bash是执行的命令。发现进入一个虚拟的linux环境,可以执行linux命令,如下:(nginx本身就是运行在linux的服务,所以我们进入容器相当于进了一个linux系统)

    root@29d978bb4001:/# ls
    bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
    root@29d978bb4001:/# which nginx
    /usr/sbin/nginx

    在容器内查看下容器内的进程:(发现pid为1的是nginx进程,还有nginxworker进程)

    root@f402157f746c:/# ps -ef
    UID        PID  PPID  C STIME TTY          TIME CMD
    root         1     0  0 02:26 ?        00:00:00 nginx: master process nginx -g daemon off;
    nginx        6     1  0 02:26 ?        00:00:00 nginx: worker process
    root         7     0  0 02:29 pts/0    00:00:00 bash
    root       600     7  0 02:34 pts/0    00:00:00 ps -ef

     4.通过宿主机访问docker容器nginx

    1. docker网络:

    host模式:容器和宿主机共享Network namespace。也就是共享同一个IP和端口。

    bridge模式:有独立的network namespace,可以通过端口映射将端口映射到宿主机中。(默认)

    none模式:容器有独立的Network namespace,但并没有对其进行任何网络设置,如分配veth pair 和网桥连接,配置IP等。

    如下图:

     2.启动nginx的时候进行端口映射

    C:UsersAdministrator>docker ps
    CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS               NAMES
    29d978bb4001        hub.c.163.com/library/nginx   "nginx -g 'daemon of…"   About an hour ago   Up 47 minutes       80/tcp              romantic_lumiere
    
    C:UsersAdministrator>docker stop 29  #停掉上面的nginx,因为只有一个容器,所以输入简写ID也可以
    29
    
    C:UsersAdministrator>docker ps
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    
    C:UsersAdministrator>docker images
    REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE
    hello-world                   latest              fce289e99eb9        13 months ago       1.84kB
    hub.c.163.com/library/nginx   latest              46102226f2fd        2 years ago         109MB
    
    C:UsersAdministrator>docker run -p 8080:80 -d hub.c.163.com/library/nginx #启动nginx,-p是端口映射,本地的8080映射到docker的80端口,80是nginx的端口。
    d742f7199bb6ce10508fddcf647520f88267492b458584c81b0c789658b3f4b3
    
    C:UsersAdministrator>docker ps
    CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                  NAMES
    d742f7199bb6        hub.c.163.com/library/nginx   "nginx -g 'daemon of…"   4 seconds ago       Up 3 seconds        0.0.0.0:8080->80/tcp   sweet_elion
    
    C:UsersAdministrator>netstat -ano | findstr 8080
      TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       14768
      TCP    [::]:8080              [::]:0                 LISTENING       14768

    浏览器访问:

    注意:由于我这里是windows虚拟机访问,因为docker是运行在Linux上的,在Windows中运行docker,实际上还是在Windows下先安装了一个Linux环境,然后在这个系统中运行的docker。也就是说,所有的东西都是在虚拟的linux环境中,而不是我们的宿主环境Windows。所以我们也不能通过localhost直接访问。需要先查看linux虚拟环境的IP,如下:

    C:UsersAdministrator>docker-machine ls #查看可以使用的机器,可以看到目前只有这里默认的 default 虚拟机。
    NAME      ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER     ERRORS
    default   *        virtualbox   Running   tcp://192.168.99.100:2376           v19.03.5
    
    C:UsersAdministrator>docker-machine ip default  #查看默认虚拟机的IP地址
    192.168.99.100

    访问linux虚拟环境的IP地址:

    另一种是-P(大写的P,这种是随机分配一个本地端口),如下:

    C:UsersAdministrator>docker run -d -P hub.c.163.com/library/nginx
    2eeabee88ff42f611702a6239c9689e254e2ca449f065c7bdb423304cada3a78
    
    C:UsersAdministrator>docker ps
    CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                   NAMES
    2eeabee88ff4        hub.c.163.com/library/nginx   "nginx -g 'daemon of…"   2 seconds ago       Up 1 second         0.0.0.0:32769->80/tcp   tender_grothendieck

      访问的时候同样是用linux虚拟环境的IP地址访问。 

    补充:docker进入容器内没有vim,ps,top支持

    解决办法:

    (1)下载vim

    apt-get update
    apt-get install vim

    (2)下载ps、top

    apt-get install procps

    补充:docker port  列出指定的容器的端口映射,或者查找将PRIVATE_PORT NAT到面向公众的端口。

    C:UsersAdministrator>docker ps -a
    CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                   NAMES
    19244d42aaf3        hub.c.163.com/library/nginx   "nginx -g 'daemon of…"   5 minutes ago       Up 5 minutes        0.0.0.0:32772->80/tcp   competent_agnesi
    36c135e9890c        hub.c.163.com/library/nginx   "nginx -g 'daemon of…"   9 minutes ago       Up 9 minutes        0.0.0.0:8080->80/tcp    elastic_cerf
    
    C:UsersAdministrator>docker port --help
    
    Usage:  docker port CONTAINER [PRIVATE_PORT[/PROTO]]
    
    List port mappings or a specific mapping for the container
    
    Options:
    
    
    C:UsersAdministrator>docker port 19244d42aaf3
    80/tcp -> 0.0.0.0:32772
    
    C:UsersAdministrator>docker port 36
    80/tcp -> 0.0.0.0:8080

    补充:下载和运行不同版本镜像的时候只需要在镜像名称后面加上版本号就可以,比如 

    C:UsersAdministrator>docker pull hub.c.163.com/library/nginx:1.9
    C:UsersAdministrator>docker run hub.c.163.com/library/nginx:1.9

    补充: Detached模式 vs foreground  模式

    1. Detached模式 vs foreground  模式

     当要启动一个docker容器时,首先必须决定是以detached模式在后台运行容器还是以默认的foreground模式运行。

    (1)Detached (-d) detached:分离的模式  

        要在detached模式启动一个容器,必须使用-d=true或仅-d选项。docker是这样设计的,当运行在容器的根进程退出时,以detached模式启动的容器也退出。以detached模式运行的容器当它停止时无法自动删除,需要docker rm containerID 手动删除。 (此模式不能加--rm参数)

    (2)Foreground 模式:

       在forgroud模式[当-d不指定时],docker run能够在容器启动进程并附着控制台到进程的标准输入,输出和标准错误。此模式运行的容器当它停止时默认也无法自动删除,需要docker rm containerID 手动删除。如果加了 --rm 参数会自动删除。

    2.docker run --rm 解释

    官方解释如下:

     --rm  Automatically remove the container when it exits

      执行docker run命令带--rm命令选项,等价于在容器退出后自动移除容器,执行docker rm -v。注意,--rm选项也会清理容器的匿名data volumes。

      显然,--rm选项不能与-d同时使用,即只能自动清理foreground容器,不能自动清理detached容器

    3.测试:

    (1)foreground模式,不加--rm自动停止后容易停止但不删除

    Administrator@MicroWin10-1535 MINGW64 ~/Desktop/dockertest
    $ docker run ubuntu echo "hello"
    hello
    
    Administrator@MicroWin10-1535 MINGW64 ~/Desktop/dockertest
    $ docker ps -a
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
    d4dab01786b2        ubuntu              "echo hello"        3 seconds ago       Exited (0) 3 seconds ago                       frosty_               herschel

    (2)foreground模式,加--rm自动停止后容易停止且删除容器

    Administrator@MicroWin10-1535 MINGW64 ~/Desktop/dockertest
    $ docker run --rm ubuntu echo "hello"
    hello
    
    Administrator@MicroWin10-1535 MINGW64 ~/Desktop/dockertest
    $ docker ps -a
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    
    Administrator@MicroWin10-1535 MINGW64 ~/Desktop/dockertest

    补充:docker run --rm imagename cmd 经常用于执行一次容器内的命令并且关闭容器,如果需要获取文件可以加-v参数指定容器内部和外部映射路径。例如镜像内有个sh脚本,内容如下:

    #!/bin/bash
    echo "this is test"

    外部调用容器内命令,执行完关闭容器

    C:UsersAdministrator>docker run --rm myubuntu sh /test.sh
    this is test

    总结:

      -d 就是以守护进程的方式启动(detached模式);不加-d就是占用命令行的方式运行(foreground模式)。不加-d的情况(foreground)可以加 --rm 参数在停止的时候自动删除容器。

    补充:docker命令大全

    (1)容器生命周期管理
      run 创建一个新的容器并运行一个名令
      start/stop/restart 启动/停止/重启容器
      kill 杀掉一个运行中的容器
      rm 删除一个或多个容器
      pause/unpause 暂停/恢复容器中的所有进程
      create 创建一个新的容器但不启动它
      exec 进入容器
    (2)容器操作
      ps 列出容器
      inspect 获取容器/镜像的元数据。
      top 查看容器中运行的进程信息,支持 ps 命令参数
      attach 连接到正在运行中的容器(退出时容器关闭,不建议使用)
      events 从服务器获取实时事件
      logs 获取容器的日志
      wait 阻塞运行直到容器停止,然后打印出它的退出代码
      export 将文件系统作为一个tar归档文件导出到STDOUT
      port 列出指定的容器的端口映射,或者查找将PRIVATE_PORT NAT到面向公众的端口
    (3)容器rootfs命令
      commit 从容器创建一个新的镜像
      cp 用于容器与主机之间的数据拷贝
      diff 检查容器里文件结构的更改
    (4)镜像仓库
      login 登陆到一个Docker镜像仓库,如果未指定镜像仓库地址,默认为官方仓库 Docker Hub
      logout 登出一个Docker镜像仓库,如果未指定镜像仓库地址,默认为官方仓库 Docker Hub
      pull 从镜像仓库中拉取或者更新指定镜像
      push 将本地的镜像上传到镜像仓库,要先登陆到镜像仓库
      search 从Docker Hub查找镜像
    (5)本地镜像管理
      images 列出本地镜像
      rmi 删除镜像
      tag 标记本地镜像,将其归入某一仓库
      build 命令用于使用 Dockerfile 创建镜像
      history 查看指定镜像的创建历史
      save 将指定镜像保存成 tar 归档文件
      load 导入使用 docker save 命令导出的镜像
      import 从归档文件中创建镜像
    (6)info|version
      info 显示 Docker 系统信息,包括镜像和容器数
      version 显示 Docker 版本信息

  • 相关阅读:
    js以字符串方式创建DOM(原生js,jquery,extjs)
    gallery3
    检测标准类型和内置对象类型
    js数据类型和类型检测
    gallery2
    gallery
    如何使用Git上传项目代码到github
    sublime EMMET
    模糊搜索
    导出表格
  • 原文地址:https://www.cnblogs.com/qlqwjy/p/12303948.html
Copyright © 2020-2023  润新知