docker 知识点

docker 官网

docker cli reference

  • windows10 安装
    不要同时安装virtual box和window docker , 只需安装windows docker即可, 否则需要删除环境变量里面的docker变量

  • 配置国内镜像
    推荐使用阿里云镜像加速器, 方法: 注册阿里云账号,=>容器镜像服务=>镜像加速器=>操作文档=>windows, 将加速器地址复制后打开docker 的setting=>daemon=>registry mirrors 粘贴复制的加速器地址 apply即可.

  • docker 整体流程


    docker
  • Shared drives 容器可访问的共享文件夹
    需要本地计算机的用户名密码
    如果没开启的话,挂载本地volume 会报错:
    docker: Error response from daemon: Drive has not been shared

Docker命令与 Git 和 GitHub比较类似。总的来说分为以下几种:

容器生命周期管理 — docker [run|start|stop|restart|kill|rm|pause|unpause]
容器操作运维 — docker [ps|inspect|top|attach|events|logs|wait|export|port]
容器rootfs命令 — docker [commit|cp|diff]
镜像仓库 — docker [login|pull|push|search]
本地镜像管理 — docker [images|rmi|tag|build|history|save|import]
其他命令 — docker [info|version]

  • 展示docker信息
docker version
docker info
docker -D info #The global -D option tells all docker comands to output debug information.

  • 执行构建命令
docker build -t webname . 
  • dockerfile
    ` [from maintainer run cmd label expose env add copy entrypoint volume user workdir arg onbuild stopsignal healthcheck shell]

  • .dockerignore

     # comment 
        */temp*
        */*/temp*
        temp?
        ~*
    
  • 查看镜像文件

docker images [options] [name]
-a, --all=false      Show all images (by default filter out the intermediate image layers)
-f, --filter=[]      Provide filter values (i.e. 'dangling=true')
--no-trunc=false     Don't truncate output
-q, --quiet=false    Only show numeric IDs
  • 删除镜像
docker rmi image [imageid ...] 
docker rmi $(docker images | grep "none" | awk '{print $3}')
  • 运行容器
docker run [options] [image] [command][agr...]
docker run -d -p 5000:80
-a,--attach=[]Attach to STDIN, STDOUT or STDERR.-c,--cpu-shares=0         CPU shares (relative weight)--cidfile=""Write the container ID to the file
--cpuset=""CPUsin which to allow execution (0-3,0,1)-d,--detach=falseDetached mode: run container in the background andprintnew container ID
--dns=[]Set custom DNS servers
--dns-search=[]Set custom DNS search domains
-e,--env=[]Set environment variables
--entrypoint=""Overwrite the default ENTRYPOINT of the image
--env-file=[]Readin a line delimited file of environment variables
--expose=[]Expose a port from the container without publishing it to your host
-h,--hostname=""Container host name
-i,--interactive=falseKeep STDIN open even ifnot attached
--link=[]Add link to another container in the form of name:alias--lxc-conf=[](lxc exec-driver only)Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"-m,--memory=""Memory limit (format:,where unit = b, k, m or g)--name=""Assign a name to the container
--net="bridge"Set the Network mode for the container
                               'bridge': creates a new network stack for the container on the docker bridge
                               'none':no networking forthis container
                               'container:': reuses another container network stack
                               'host':use the host network stack inside the container.Note: the host mode gives the container full access to local system services such as D-bus andis therefore considered insecure.-P,--publish-all=falsePublish all exposed ports to the host interfaces
-p,--publish=[]Publish a container's port to the host
                               format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort
                               (use 'docker port' to see the actual mapping)
--privileged=false         Give extended privileges to this container
--rm=false                 Automatically remove the container when it exits (incompatible with -d)
--sig-proxy=true           Proxy received signals to the process (even in non-TTY mode). SIGCHLD, SIGSTOP, and SIGKILL are not proxied.
-t, --tty=false            Allocate a pseudo-TTY
-u, --user=""              Username or UID
-v, --volume=[]            Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container)
--volumes-from=[]          Mount volumes from the specified container(s)
-w, --workdir=""           Working directory inside the container
  • 查看所有容器
docker ps -a
  • 查看运行中容器
docker ps
  • 查看所有容器ID
docker ps -a -q
  • 启动容器(已停止的容器)
docker start [containerid ...]
-a,--attach=false Attach container's STDOUT and STDERR and forward all signals to the process
-i, --interactive=false    Attach container's STDIN
  • 重启一个容器或多个容器
docker restart [options] [container ...]
-t,--time=10Number of seconds to try to stop for before killing the container.Once killed it will then be restarted.Defaultis10 seconds.
  • 停止容器
docker stop [containerid ...]
  • 停止所有容器
docker stop $(docker ps -a -q)
  • 暂停容器
docker pause [container]
  • 取消暂停容器
docker unpause [container]
  • 删除容器
docker rm [options] [containerid ...]
-f,--force=falseForce removal of running container
-l,--link=falseRemove the specified link andnot the underlying container
-v,--volumes=falseRemove the volumes associated with the container
  • 删除所有容器
docker rm $(docker ps -a -q)
docker rm `docker ps -a | grep Exited | awk '{print $1}'`
  • 查看所有volume
docker volume ls
  • 删除指定volume (删除容器时volume会保留,不需要时要删除)
docker volume rm [volume name]
  • 删除所有未使用的volume
docker volume prune
  • 查看volume详细
docker volume inspect [volume name]
  • 安装jenkins (-v 后jenkins是volume名称,也可不命名)
docker run -p 8080:8080 -v jenkins:/var/jenkins_home jenkins
  • 提交一个新的image
docker commit [options] [repository[:tag]]
- options:
-a, --author=""     Author (e.g., "John Hannibal Smith ")
-m, --message=""    Commit message
-p, --pause=true    Pause container during commit
  • 提交一个存在的容器
$ docker ps
ID                  IMAGE               COMMAND             CREATED             STATUS              PORTS
c3f279d17e0a        ubuntu:12.04/bin/bash           7 days ago          Up25 hours
197387f1b436        ubuntu:12.04/bin/bash           7 days ago          Up25 
$ docker commit c3f279d17e0a  SvenDowideit/testimage:version3
f5283438590d
$ docker images | head
REPOSITORY                        TAG                 ID                  CREATED             VIRTUAL SIZE
SvenDowideit/testimage            version3            f5283438590d        16 s
  • 将容器中的文件拷贝到主机上
docker cp [container:path] [hostpath]
  • 进入容器并进行交互
docker exec -it [container] /bin/bash
  • 比较一个容器不同版本提交的文件差异
docker diff [container]
显示中的A D C 含义
A-Add
D-Delete
C-Change
  • 获取server中的实时事件
docker events [options]
--since=""Show all events created since timestamp
--until=""Stream events untilthis timestamp
  • 导入已有的image
docker import url|-[repository[:tag]]
# 支持压缩包 (.tar, .tar.gz, .tgz, .bzip, .tar.xz, or .txz)
例如:
导入远程的包:
docker import http://example.com/exampleimage.tgz
导入本地文件:
$ cat exampleimage.tgz | sudo docker import- exampleimagelocal:new
$ sudo tar -c .| sudo docker import- exampleimagedir
导入本地目录:
  • 导出一个容器
docker export [container] > latest.tar
  • 显示一个image的历史
docker history [options] image
--no-trunc=false   Don't truncate output
-q, --quiet=false    Only show numeric IDs
  • 杀死docker进程
docker kill [options] [container ...]
-s,--signal="KILL"Signal to send to the container
  • 加载image
docker load
i,--input=""Readfrom a tar archive file, instead of STDIN
例如:加载一个打包好的镜像
docker images
docker load < busybox.tar
docker load --input fedora.tar
  • 登陆docker注册服务器
docker login [options][server]
可以使用自己的注册服务器
docker login localhost:8080
  • 获取容器的日志
docker logs [container]
-f,--follow=falseFollow log output
-t,--timestamps=falseShow timestamps
--tail="all"Output the specified number of lines at the end of logs (defaults to all logs)
  • 端口转发
docker port [container] [private_port]
  • 从远端拉取一个image
docker pull [name[:tag]]
例如:
$ docker pull debian
# will pull all the images in the debian repository
$ docker pull debian:testing
# will pull only the image named debian:testing and any intermediate layers# it is based on. (Typically the empty `scratch` image, a MAINTAINERs layer,# and the un-tarred base).
$ docker pull registry.hub.docker.com/debian
# manually specifies the path to the default Docker registry. This could# be replaced with the path to a local regis
  • 推送image到这侧服务器
docker push [name[:tag]]
  • 打包image
docker save [image]
-o,--output=""Write to an file, instead of STDOUT
例如:
$ sudo docker save busybox > busybox.tar
$ ls -sh busybox.tar
2.7M busybox.tar
$ sudo docker save --output busybox.tar busybox
$ ls -sh busybox.tar
2.7M busybox.tar
$ sudo docker save -o fedora-all.tar fedora
$ sudo docker save -o fedora-latest.tar fedora:latest
  • 搜索image
docker search [name]
  • 为image打标签
docker tag [options] [image[:tag][registryhost/][username/]name[:tag]
-f,--force=false Force
  • docker inspect
    检查镜像或者容器的参数,默认返回 JSON 格式。
    -f 指定返回值的模板文件特定值。
docker instpect nginx:latest
docker inspect nginx-container
docker inspect -f {{.Mounts}} nginx-container
  • docker attach
docker attach 

Docker允许使用attach命令与运行中的容器交互,并且可以随时观察容器內进程的运行状况。退出容器可以通过两种方式来完成:
Ctrl+C 直接退出
Ctrl-\ 退出并显示堆栈信息(stack trace)

  • docker stats
    查看和统计容器所占用的资源情况
root@VM-16-14-ubuntu ~# docker stats --no-stream b06d6fc
CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O           PIDS
27811baf9933        lvliang_api         0.14%               94.49MiB / 15.51GiB   0.60%               78.7MB / 73.3MB     0B / 0B             28

b06d6fc为容器id, 这里传递了一个 --no-stream 的参数,是因为 docker stats 命令默认是一个持续的动态流式输出(每秒一次),给它传递 --no-stream 参数后,它就只输出一次便会退出了
接下来我为你介绍下它输出内容的含义:

Container ID:容器的 ID,也是一个容器生命周期内不会变更的信息。
Name:容器的名称,如果没有手动使用 --name 参数指定,则 Docker 会随机生成一个,运行过程中也可以通过命令修改。
CPU %:容器正在使用的 CPU 资源的百分比,这里面涉及了比较多细节,下面会详细说。
Mem Usage/Limit:当前内存的使用及容器可用的最大内存,这里我使用了一台 16G 的电脑进行测试。
Mem %:容器正在使用的内存资源的百分比。
Net I/O:容器通过其网络接口发送和接受到的数据量。
Block I/O:容器通过块设备读取和写入的数据量。
Pids:容器创建的进程或线程数。

  • docker top
    查看容器中的进程
root@VM-16-14-ubuntu ~# docker top --help
Usage:  docker top CONTAINER [ps OPTIONS]
Display the running processes of a container
root@VM-16-14-ubuntu ~# docker top (docker ps -ql)
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                8085                8059                0                   Feb03               ?                   00:18:44            dotnet ll.Api.dll
  • Dockerfile关键字
  1. FROM
    基于哪个镜像
  2. RUN
    安装软件用
  3. MAINTAINER
    镜像创建者
  4. CMD
    container启动时执行的命令,但是一个Dockerfile中只能有一条CMD命令,多条则只执行最后一条CMD。
    CMD主要用于container时启动指定的服务,当docker run command的命令匹配到CMD command时,会替换CMD执行的命令(同时执行)。
  5. ENTRYPOINT
    container启动时执行的命令,但是一个Dockerfile中只能有一条ENTRYPOINT命令,如果多条,则只执行最后一条ENTRYPOINT没有CMD的可替换特性
  6. USER
    使用哪个用户跑container
  7. EXPOSE
    container内部服务开启的端口。主机上要用还得在启动container时,做host-container的端口映射:docker run -d -p 127.0.0.1:33301:22 centos6-ssh
  8. ENV
    用来设置环境变量,比如:
    ENV LANG en_US.UTF-8
    ENV LC_ALL en_US.UTF-8
  9. ADD
    将文件拷贝到container的文件系统对应的路径
    所有拷贝到container中的文件和文件夹权限为0755,uid和gid为0
    如果文件是可识别的压缩格式,则docker会帮忙解压缩,如果要ADD本地文件,则本地文件必须在 docker build ,指定的目录下,如果要ADD远程文件,则远程文件必须在 docker build ,指定的目录下。比如:
    docker build github.com/creack/docker-firefox
    docker-firefox目录下必须有Dockerfile和要ADD的文件
    注意:使用docker build - < somefile方式进行build,是不能直接将本地文件ADD到container中。只能ADD url file。ADD只有在build镜像的时候运行一次,后面运行container的时候不会再重新加载了。
  10. VOLUME
    可以将本地文件夹或者其他container的文件夹挂载到container中。
  11. WORKDIR
    切换目录用,可以多次切换(相当于cd命令),对RUN,CMD,ENTRYPOINT生效
  12. ONBUILD
    ONBUILD 指定的命令在构建镜像时并不执行,而是在它的子镜像中执行
  • docker network ls
    查看网络信息,默认为:bridge none host
  • 自定义网络
    docker 允许我们创建3种类型的自定义网络,bridge,overlay,MACVLAN
#1 bridge 模式
docker network create --driver bridge redis-net
#2 overlay模式 attachable
docker network create --driver=overlay --attachable name=myOverlayNet 
  • docker network inspect
    display detailed information on one or more networks
docker network inspect [options] network [network...]

options:
--format ,-f 格式化输出
-verbose ,-v 诊断详情

  • docker运行dotnet示例
//此处用powershell
docker run -it -p 8080:5000 -v ${PWD}:/app --workdir "/app" --name "dotnet_docker" microsoft/dotnet /bin/bash
-it 参数表示进入交互模式
-p 8080:5001 表示把容器里的5001端口映射给宿主的8080端口。
-v 表示创建volume
${PWD}是指宿主当前的目录。此处也可以用绝对路径,如/c/work/web/
{PWD}:/app就是把容器里的/app文件夹连接到了宿主系统里的当前文件夹,而容器里的/app目录就是应用程序将要运行的位置
 --workdir "/app"表示容器里当前的工作目录是/app。
--name "dotnet_docker"表示容器名称是"dotnet_docker"
然后使用microsoft/dotnet这个镜像。
最后使用/bin/bash返回一个终端,以便让我与容器里进行交互
  • win10 中安装的docker的路径
    本质上docker安装到了hype-v虚拟机中的,该虚拟机路径为
    C:\Users\Public\Documents\Hyper-V\Virtual hard disks

  • docker创建网络net组,桥接网络
    在一个Docker Host里,有许多容器,他们之间需要相互通信。我们可以使用容器名进行通信,尤其是开发的时候。
    但是当容器比较多的时候,你可能就倾向于对一些容器进行隔离,或者叫做分组。
    而我们通过Docker客户端就可以创建这种隔离的网络。每一个隔离网络里的容器可以相互通信,这时也可以使用容器名进行通信。
    有了这种隔离的网络,对容器间的通信管理就方便多了
    1.创建自定义桥接网络
    docker network create --driver bridge 网络名
    2.使容器加入到这个网络
    docker run -d --net=网络名 --name 网络内的容器名 镜像名:tag
    3.查看网络
    docker network ls

PS C:\Users\wweim> docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
cac37f4bf289        bridge              bridge              local
73740e25ac6e        host                host                local
e5ec0ad83aef        my-net              bridge              local
5d3fbea9181c        none                null                local

其中name为my-net即为自定义创建的bridge桥接网络
使用docker insepct my-net查看网络信息

PS C:\Users\wweim> docker inspect my-net
[
    {
        "Name": "my-net",
        "Id": "e5ec0ad83aef0f8be7ef4e1147f28223280ec73a27b5b0b6b31401f9c56185b0",
        "Created": "2020-02-03T13:47:36.5422024Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.18.0.0/16",
                    "Gateway": "172.18.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "62e6d09cfd1afb4552dbb75f2b42ee4ccf80529c1e4a369079bca485577fbd8e": {
                "Name": "lvliang_api",
                "EndpointID": "ba95b83c5f090a67b701a8e6216b9dda553bcbab167f7fd27eab4cfd1313535b",
                "MacAddress": "02:42:ac:12:00:02",
                "IPv4Address": "172.18.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

可以看到containers中已经有一个容器了,再启动容器时使用 --net=网络名参数,就会创建自定义网格内的其他容器,同一个桥接网络的容器可以相互通信
并且其他容器就可以使用host=lvliaing_api作为服务器名连接了(比较常见的就是数据库的连接字符串)

你可能感兴趣的:(docker 知识点)