docker--常用命令

前戏

我们使用docker --help来查看下都有哪些命令

[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命令在帮助可以获取更多信息
View Code

搜索镜像

docker search jenkins  # 搜索所有的jenkins的docker镜像
[root@HH ~]# docker search jenkins 
NAME                                   DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
jenkins                                Official Jenkins Docker image                   4453                [OK]                
jenkins/jenkins                        The leading open source automation server       1706                                    
jenkinsci/blueocean                    https://jenkins.io/projects/blueocean           442                                     
jenkinsci/jenkins                      Jenkins Continuous Integration and Delivery …   371                                     
jenkinsci/jnlp-slave                   A Jenkins slave using JNLP to establish conn…   114                                     [OK]
jenkins/jnlp-slave                     a Jenkins agent (FKA "slave") using JNLP to …   96                                      [OK]
jenkinsci/slave                        Base Jenkins slave docker image                 57                                      [OK]
jenkinsci/ssh-slave                    A Jenkins SSH Slave docker image                39                                      [OK]
cloudbees/jenkins-enterprise           CloudBees Jenkins Enterprise (Rolling releas…   34                                      [OK]
jenkins/slave                          base image for a Jenkins Agent, which includ…   32        

NAME:名称。DESCRIPTION:描述。STARS:点赞数。OFFICIAL:官方。AUTOMATED:自动化

搜索镜像且过滤是非官方的

docker search --filter "is-official=true" centos

获取镜像

从docker registry获取镜像的命令是docker pull。命令格式是:

docker pull [选项][docker registry地址] 仓库名:标签

docker是把应用程序和其依赖打包在image文件里面,只有通过这个镜像文件才能生成docker容器。

一个image文件可以生成多个容器实例。

可以使用docker pull命令来从仓库获取所需要的镜像,比如下载一个jenkins的镜像

docker pull jenkins  # 获取jenkins镜像
[root@HH ~]# docker pull jenkins
Using default tag: latest
latest: Pulling from library/jenkins
55cbf04beb70: Pull complete 
1607093a898c: Pull complete 
9a8ea045c926: Pull complete 
d4eee24d4dac: Pull complete 
c58988e753d7: Pull complete 
794a04897db9: Pull complete 
70fcfa476f73: Pull complete 
0539c80a02be: Pull complete 
54fefc6dcf80: Pull complete 
911bc90e47a8: Pull complete 
38430d93efed: Pull complete 
7e46ccda148a: Pull complete 
c0cbcb5ac747: Pull complete 
35ade7a86a8e: Pull complete 
aa433a6a56b1: Pull complete 
841c1dd38d62: Pull complete 
b865dcb08714: Pull complete 
5a3779030005: Pull complete 
12b47c68955c: Pull complete 
1322ea3e7bfd: Pull complete 
Digest: sha256:eeb4850eb65f2d92500e421b430ed1ec58a7ac909e91f518926e02473904f668
Status: Downloaded newer image for jenkins:latest
docker.io/library/jenkins:latest

拉取指定版本,用:

docker pull jenkins:1.12  # 获取jenkins1.12的镜像

下载过程可以看出镜像是由多层存储构成的。下载也是一层一层,并非单一的文件。

下载过程中给出每一层的前12位ID。下载结束后会给出sha246的文件一致性校验值

查看docker镜像

docker images  # 查看docker镜像

 删除docker镜像

如果要移除本地的镜像,可以使用docker rmi命令(在删除镜像之前先用docker rm删除依赖于这个镜像的所有容器)。注意docker rm 命令是移除容器。

docker rmi imageID  #删除docker镜像
或者
docker rmi 镜像名字

删除所有的镜像

docker rmi `docker images -aq`   #一次性删除所有镜像记录,反单引号

导出docker镜像

有时候我们的镜像,别人也要使用,我们可以把我们的镜像导出给别人使用,使用docker save命令

docker save jenkins > /tmp/jenkins.tar.gz  # 导出docker镜像到本地的tmp目录下

导入docker镜像

上面别人给我们导出了他的镜像,那我们就要导入了,删除自己的docker镜像在导入

docker load < /tmp/jenkins.tar.gz  # 导入本地镜像到docker镜像库

导入完之后查看docker镜像库

# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
jenkins             latest              cd14cecfdb3a        14 months ago       696MB

启动docker容器

启动容器有两种方式,一种是基于镜像新建一个容器并启动,另外一个是将在终止状态(stopped)的容器重新启动。

因为Docker的容器实在太轻量级了,很多时候用户都是随时删除和新创建容器。

新建容器并启动

使用docker run启动容器

[root@HH ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
jenkins             latest              cd14cecfdb3a        14 months ago       696MB
[root@HH ~]# docker run cd14

这样就启动了一个容器,但这样有缺点,我们关掉窗口或者ctrl+c就终止了,所以在启动的时候我们可以加上参数-d,表示后台启动

[root@HH ~]# docker run -d jenkins  也可以通过id启动
4ee88fb080c7718fd68bc5dfbea01e10048df8fd00e461cdec166be594064293

docker run就是运行容器的命令。
参数

  • -it : -i 是交互式操作,-t是终端
  • -rm : 容器退出后将其删除。也可以不指定参数,手动docker rm,使用-rm可以避免浪费空间。
  • bash : 指定用交互式的shell,因此需要bash命令

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

  • 检查本地是否存在指定的镜像,不存在就从公有仓库下载
  • 利用镜像创建并启动一个容器
  • 分配一个文件系统,并在只读的镜像层外面挂在一层 可读写层
  • 从宿主机配置的网桥接口桥接一个虚拟 接口到容器中去
  • 从地址池配置一个 ip地址给容器
  • 执行用户指定的 应用程序
  • 执行完毕后容器被终止

查看正在运行的容器

通过docker ps就可以查看运行的容器

[root@HH ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
4ee88fb080c7        jenkins             "/bin/tini -- /usr/l…"   4 minutes ago       Up 4 minutes        8080/tcp, 50000/tcp   brave_wilson

后面的NAMES参数是docker给我们生成的,我们也可以自定义,在启动的时候加上--name参数

[root@HH ~]# docker run -d --name MyJenkins jenkins
1603ebfad9aaff6c2ec1bfa6e5300ac711a716d8bea3b0fed37c6bbc38b354b1
[root@HH ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1603ebfad9aa        jenkins             "/bin/tini -- /usr/l…"   9 seconds ago       Up 8 seconds        8080/tcp, 50000/tcp   MyJenkins

停止正在运行的容器

通过docker stop 容器id/names都可以停止容器

[root@HH ~]#  docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
4ee88fb080c7        jenkins             "/bin/tini -- /usr/l…"   7 minutes ago       Up 7 minutes        8080/tcp, 50000/tcp   brave_wilson
[root@HH ~]# 
[root@HH ~]# docker stop brave_wilson
brave_wilson
[root@HH ~]# docker stop 40db
40db

查看所有的容器

docker ps -a 可以查看停止和运行的容器

[root@HH ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                            PORTS               NAMES
40db302d030b        jenkins             "/bin/tini -- /usr/l…"   2 minutes ago       Exited (143) About a minute ago                       admiring_morse
4ee88fb080c7        jenkins             "/bin/tini -- /usr/l…"   9 minutes ago       Exited (143) 2 minutes ago                            brave_wilson
d6e046c9d2ff        cd14                "/bin/tini -- /usr/l…"   12 minutes ago      Exited (130) 11 minutes ago                           vigorous_greider

查看容器详细信息

docker inspect 容器名/容器id

[root@WC ~]# docker inspect mycentos 
[
    {
        "Id": "ee872f6751c5e0a63533fb15062fc8036d7ca5a6f13bf82a7d8795798a25f4a2",
        "Created": "2020-01-01T13:37:01.861619293Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 10565,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-01-01T13:37:02.225034856Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5e35e350aded98340bc8fcb0ba392d809c807bc3eb5c618d4a0674d98d88bccd",
        "ResolvConfPath": "/var/lib/docker/containers/ee872f6751c5e0a63533fb15062fc8036d7ca5a6f13bf82a7d8795798a25f4a2/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/ee872f6751c5e0a63533fb15062fc8036d7ca5a6f13bf82a7d8795798a25f4a2/hostname",
        "HostsPath": "/var/lib/docker/containers/ee872f6751c5e0a63533fb15062fc8036d7ca5a6f13bf82a7d8795798a25f4a2/hosts",
        "LogPath": "/var/lib/docker/containers/ee872f6751c5e0a63533fb15062fc8036d7ca5a6f13bf82a7d8795798a25f4a2/ee872f6751c5e0a63533fb15062fc8036d7ca5a6f13bf82a7d8795798a25f4a2-json.log",
        "Name": "/mycentos",
        "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,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "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,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "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/a3390c678d8864c4ffa895efb69333ae282b2a785148c527cf9fc0bca1f1f40b-init/diff:/var/lib/docker/overlay2/a13612fab2121263cf245c26c99b9d6adf148c00c133fd57220f49974d3148ef/diff",
                "MergedDir": "/var/lib/docker/overlay2/a3390c678d8864c4ffa895efb69333ae282b2a785148c527cf9fc0bca1f1f40b/merged",
                "UpperDir": "/var/lib/docker/overlay2/a3390c678d8864c4ffa895efb69333ae282b2a785148c527cf9fc0bca1f1f40b/diff",
                "WorkDir": "/var/lib/docker/overlay2/a3390c678d8864c4ffa895efb69333ae282b2a785148c527cf9fc0bca1f1f40b/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "ee872f6751c5",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "centos:7",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20191001",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "7e35649f4e95a897fb98128e71c85f9f1b318447e46d6eb6fc4dccad29664f45",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/7e35649f4e95",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "56e20fe4cb4d41416e3a2edff898011755881cce820719ef0492ccdcb804ed5d",
            "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": "ef6e04bfaaeda6de0ff3727f17024da2347dc9ac821948fb1c700bab10827d15",
                    "EndpointID": "56e20fe4cb4d41416e3a2edff898011755881cce820719ef0492ccdcb804ed5d",
                    "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
                }
            }
        }
    }
]
结果

删除容器记录

通过docker rm 容器ID来删除

[root@dce88 ~]# docker rm -h
Flag shorthand -h has been deprecated, please use --help

Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers # 删除一个或多个容器

Options:
  -f, --force     Force the removal of a running container (uses SIGKILL) # 强制删除一个正在运行的容器(使用SIGKILL)。
  -l, --link      Remove the specified link  # 删除指定的链接
  -v, --volumes   Remove anonymous volumes associated with the container # 删除与容器相关的匿名卷

基本使用

[root@HH ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                           PORTS               NAMES
40db302d030b        jenkins             "/bin/tini -- /usr/l…"   About an hour ago   Exited (143) About an hour ago                       admiring_morse
4ee88fb080c7        jenkins             "/bin/tini -- /usr/l…"   2 hours ago         Exited (143) About an hour ago                       brave_wilson
d6e046c9d2ff        cd14                "/bin/tini -- /usr/l…"   2 hours ago         Exited (130) 2 hours ago                             vigorous_greider
[root@HH ~]# docker rm 40db     删除容器记录
40db
[root@HH ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                           PORTS               NAMES
4ee88fb080c7        jenkins             "/bin/tini -- /usr/l…"   2 hours ago         Exited (143) About an hour ago                       brave_wilson
d6e046c9d2ff        cd14                "/bin/tini -- /usr/l…"   2 hours ago         Exited (130) 2 hours ago                             vigorous_greider

通过rm删除的是已停止的,如果是正在运行的会报错

[root@HH ~]# docker rm 00436
Error response from daemon: You cannot remove a running container 00436eade5368cad1f93e9e1ef9c3cc5da3738a0f17a7e1b6e2669e7c379ca54. Stop the container before attempting removal or force remove

可以通过-f参数强制删除

[root@HH ~]# docker rm -f 00436
00436
[root@HH ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
3c4cb6a23761        jenkins             "/bin/tini -- /usr/l…"   30 minutes ago      Up 30 minutes       50000/tcp, 0.0.0.0:8000->8080/tcp   myjenkins

一次性删除所有容器记录

docker rm `docker ps -aq` # 一次性删除所有容器id记录

` ` #反引号是取命令的运行结果

启动终止状态的容器

通过docker start 容器ID来启动

[root@HH ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                           PORTS               NAMES
4ee88fb080c7        jenkins             "/bin/tini -- /usr/l…"   2 hours ago         Exited (143) About an hour ago                       brave_wilson
d6e046c9d2ff        cd14                "/bin/tini -- /usr/l…"   2 hours ago         Exited (130) 2 hours ago                             vigorous_greider
[root@HH ~]# docker start 4ee8   启动停止的容器
4ee8
[root@HH ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                 NAMES
4ee88fb080c7        jenkins             "/bin/tini -- /usr/l…"   2 hours ago         Up 3 seconds               8080/tcp, 50000/tcp   brave_wilson
d6e046c9d2ff        cd14                "/bin/tini -- /usr/l…"   2 hours ago         Exited (130) 2 hours ago                         vigorous_greider

进入容器

使用-d参数时,容器启动后会进入后台。某些时候需要进入容器进行操作,有很多种方法,包括使用docker attach命令或nsenter工具等。

docker  exec -it 容器id /bin/bash
docker attach 容器id

提交创建自定义的镜像

#1.我们进入交互式的centos容器中,发现没有vim命令
docker run -it centos
#2.在当前容器中,安装一个vim yum install -y vim
#3.安装好vim之后,exit退出容器 exit
#4.查看刚才安装好vim的容器记录 docker container ls -a
#5.提交这个容器,创建新的image docker commit 059fdea031ba chaoyu/centos-vim
#6.查看镜像文件 [root@master /home]docker images REPOSITORY TAG IMAGE ID CREATED SIZE chaoyu/centos-vim latest fd2685ae25fe 5 minutes ago 348MB

外网访问容器

上面我们使用-d参数后台启动了jenkins,但是还不能访问它,如果想访问,还需要加-p或者-P参数,返回的是容器ID

[root@HH ~]# docker run -d --name myjenkins -p 8000:8080 jenkins
3c4cb6a2376121fdc71303232cd3e68ffb6683c2c24aeba544c3d65e17c0e9be
[root@HH ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
3c4cb6a23761        jenkins             "/bin/tini -- /usr/l…"   5 seconds ago       Up 4 seconds        50000/tcp, 0.0.0.0:8000->8080/tcp   myjenkins

-p 8000:8080表示将本机的8000端口映射到容器的8080端口,浏览器访问8000端口就是访问容器的8080端口

设置成功后,我们在浏览器输入如下的地址就能看到jenkins的页面了

http://49.235.160.132:8000

-P  参数会随机映射端口到容器开放的网络端口

[root@HH ~]# docker run -d -P jenkins
00436eade5368cad1f93e9e1ef9c3cc5da3738a0f17a7e1b6e2669e7c379ca54
[root@HH ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                               NAMES
00436eade536        jenkins             "/bin/tini -- /usr/l…"   5 seconds ago       Up 3 seconds        0.0.0.0:32769->8080/tcp, 0.0.0.0:32768->50000/tcp   angry_curran
3c4cb6a23761        jenkins             "/bin/tini -- /usr/l…"   3 minutes ago       Up 3 minutes        50000/tcp, 0.0.0.0:8000->8080/tcp                   myjenkins

上面会将宿主机的32769端口映射到容器的8080端口,访问下面地址也是一样的

http://49.235.160.132:8000

温馨提示:如果访问失败的话,请检查自己的防火墙,以及云服务器的安全组 

查看容器日志

不间断显示log:docker logs -f 容器ID

[root@HH ~]# docker logs -f 00436
Running from: /usr/share/jenkins/jenkins.war
webroot: EnvVars.masterEnvVars.get("JENKINS_HOME")
Sep 28, 2019 2:37:31 PM Main deleteWinstoneTempContents
WARNING: Failed to delete the temporary Winstone file /tmp/winstone/jenkins.war
Sep 28, 2019 2:37:31 PM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: Logging initialized @1325ms
Sep 28, 2019 2:37:31 PM winstone.Logger logInternal
INFO: Beginning extraction from war file
Sep 28, 2019 2:37:33 PM org.eclipse.jetty.util.log.JavaUtilLog warn
WARNING: Empty contextPath
Sep 28, 2019 2:37:33 PM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: jetty-9.2.z-SNAPSHOT

查看指定容器的端口映射

现在我们已经映射了两个端口,一个是32769,一个是8000,如下

[root@HH ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                               NAMES
00436eade536        jenkins             "/bin/tini -- /usr/l…"   8 minutes ago       Up 8 minutes        0.0.0.0:32769->8080/tcp, 0.0.0.0:32768->50000/tcp   angry_curran
3c4cb6a23761        jenkins             "/bin/tini -- /usr/l…"   12 minutes ago      Up 12 minutes       50000/tcp, 0.0.0.0:8000->8080/tcp                   myjenkins

使用docker port 容器ID就可以查看端口映射

[root@HH ~]# docker port 00436
50000/tcp -> 0.0.0.0:32768
8080/tcp -> 0.0.0.0:32769

 docker info

查看docker的xinx

[root@HH ~]# docker info
Client:
 Debug Mode: false

Server:
 Containers: 4      # 容器总数
  Running: 1        # 运行的容器个数
  Paused: 0         # 暂停的容器个数
  Stopped: 3        # 停止的容器个数
 Images: 1          # 镜像个数
 Server Version: 19.03.2
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Plugins:
  Volume: local
  Network: bridge host ipvlan 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: 894b81a4b802e4eb2a91d1ce216b8817763c29fb
 runc version: 425e105d5a03fabd737a126ad93d62a9eeede87f
 init version: fec3683
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-957.21.3.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 991.2MiB
 Name: HH
 ID: YNAQ:DAQM:U3EC:6DQS:HL5N:PVME:5KST:I3VD:K4VK:AZJ4:NJIY:AEHW
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled

 总结

镜像
docker image ls         # 查看所有镜像
docker images           # 查看所有镜像
docker pull 镜像名       # docker仓库,dockerhub
docker push 镜像名       # 把本地的镜像推送到 dockerhub仓库
docker search 镜像名     # 搜索镜像
docker rmi  容器ID       # 删除镜像
docker version           # 查看docker版本,查看到server 和client两个端
systemctl start docker   # 启动docker
docker save  镜像名  >  /data/centos.tar.gz  # 导出镜像
docker load  <  /data/centos.tar.gz  # 导入镜像    
docker run  镜像名       # 运行镜像文件,产生一个容器实例


容器
docker start 容器id          # 启动容器
docker stop 容器id           # 停止容器
docker exec -it   容器id     # 进入正在运行的容器
    -i 交互式操作
    -t  开启一个终端

docker run 镜像名            # 创建容器实例
docker rm  容器id            # 删除容器记录,必须提前docker stop 容器id ,只能杀死已经停止的容器
docker rm -f 容器id          # 可以删除运行中的容器
docker ps                    # 查看容器正在运行记录
docker ps -aq               # 显示所有容器记录的id号
    -a  显示所有容器记录
    -q     显示容器id
    
docker rm  `docker ps -aq`  # 一次性删除所有容器记录

docker container ls         # 查看容器正在运行记录
docker commit  容器id记录     # 提交这个容器,创建一个新的镜像
docker logs                 # 查看容器运行日志 
    -f    #不间断打印容器日志
    
docker port   #查看容器的端口映射关系(外部访问到容器内的端口)
docker run -d  centos  -P  
-d 后台运行
-P   随机映射端口  
-p  9000(宿主机):5000(容器内) 
--name   给创建的容器记录,添加别名
posted @ 2019-11-01 18:56  邹邹很busy。  阅读(574)  评论(0编辑  收藏  举报