Dcoker3-核心命令

Docker 命令大全

1. 系统命令

  • docker version
[root@bogon ~]# docker version
Client version: 1.7.1
Client API version: 1.19
Go version (client): go1.4.2
Git commit (client): 786b29d
OS/Arch (client): linux/amd64
Server version: 1.7.1
Server API version: 1.19
Go version (server): go1.4.2
Git commit (server): 786b29d
OS/Arch (server): linux/amd64
  • docker info
[root@bogon ~]# docker info
Containers: 2
Images: 2
Storage Driver: devicemapper
 Pool Name: docker-8:2-651635-pool
 Pool Blocksize: 65.54 kB
 Backing Filesystem: extfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 308.5 MB
 Data Space Total: 107.4 GB
 Data Space Available: 12.13 GB
 Metadata Space Used: 864.3 kB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.147 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.117-RHEL6 (2016-12-13)
Execution Driver: native-0.2
Logging Driver: json-file
Kernel Version: 2.6.32-642.3.1.el6.x86_64
Operating System: <unknown>
CPUs: 1
Total Memory: 988.4 MiB
Name: bogon
ID: L6FZ:U7LS:P2PQ:UN43:DJO6:4ZTV:B6KI:XZOK:CVWF:L5BZ:VEKZ:MH54
[root@bogon ~]# 
  • docker --help
[root@bogon ~]# docker --help;
Usage: docker [OPTIONS] COMMAND [arg...]

A self-sufficient runtime for linux containers.

Options:

  --api-cors-header=                   Set CORS headers in the remote API
  -b, --bridge=                        Attach containers to a network bridge
  --bip=                               Specify network bridge IP
  -D, --debug=false                    Enable debug mode
  -d, --daemon=false                   Enable daemon mode
  --default-gateway=                   Container default gateway IPv4 address
  --default-gateway-v6=                Container default gateway IPv6 address
  --default-ulimit=[]                  Set default ulimits for containers
  --dns=[]                             DNS server to use
  --dns-search=[]                      DNS search domains to use
  -e, --exec-driver=native             Exec driver to use
  --exec-opt=[]                        Set exec driver options
  --exec-root=/var/run/docker          Root of the Docker execdriver
  --fixed-cidr=                        IPv4 subnet for fixed IPs
  --fixed-cidr-v6=                     IPv6 subnet for fixed IPs
  -G, --group=docker                   Group for the unix socket
  -g, --graph=/var/lib/docker          Root of the Docker runtime
  -H, --host=[]                        Daemon socket(s) to connect to
  -h, --help=false                     Print usage
  --icc=true                           Enable inter-container communication
  --insecure-registry=[]               Enable insecure registry communication
  --ip=0.0.0.0                         Default IP when binding container ports
  --ip-forward=true                    Enable net.ipv4.ip_forward
  --ip-masq=true                       Enable IP masquerading
  --iptables=true                      Enable addition of iptables rules
  --ipv6=false                         Enable IPv6 networking
  -l, --log-level=info                 Set the logging level
  --label=[]                           Set key=value labels to the daemon
  --log-driver=json-file               Default driver for container logs
  --log-opt=map[]                      Set log driver options
  --mtu=0                              Set the containers network MTU
  -p, --pidfile=/var/run/docker.pid    Path to use for daemon PID file
  --registry-mirror=[]                 Preferred Docker registry mirror
  -s, --storage-driver=                Storage driver to use
  --selinux-enabled=false              Enable selinux support
  --storage-opt=[]                     Set storage driver options
  --tls=false                          Use TLS; implied by --tlsverify
  --tlscacert=~/.docker/ca.pem         Trust certs signed only by this CA
  --tlscert=~/.docker/cert.pem         Path to TLS certificate file
  --tlskey=~/.docker/key.pem           Path to TLS key file
  --tlsverify=false                    Use TLS and verify the remote
  --userland-proxy=true                Use userland proxy for loopback traffic
  -v, --version=false                  Print version information and quit

Commands:
    attach    Attach to a running container
    build     Build an image from a Dockerfile
    commit    Create a new image from a container's changes
    cp        Copy files/folders from a container's filesystem to the host path
    create    Create a new container
    diff      Inspect changes on a container's filesystem
    events    Get real time events from the server
    exec      Run a command in a running container
    export    Stream the contents of a container as a tar archive
    history   Show the history of an image
    images    List images
    import    Create a new filesystem image from the contents of a tarball
    info      Display system-wide information
    inspect   Return low-level information on a container or image
    kill      Kill a running container
    load      Load an image from a tar archive
    login     Register or log in to a Docker registry server
    logout    Log out from a Docker registry server
    logs      Fetch the logs of a container
    pause     Pause all processes within a container
    port      Lookup the public-facing port that is NAT-ed to PRIVATE_PORT
    ps        List containers
    pull      Pull an image or a repository from a Docker registry server
    push      Push an image or a repository to a Docker registry server
    rename    Rename an existing container
    restart   Restart a running container
    rm        Remove one or more containers
    rmi       Remove one or more images
    run       Run a command in a new container
    save      Save an image to a tar archive
    search    Search for an image on the Docker Hub
    start     Start a stopped container
    stats     Display a stream of a containers' resource usage statistics
    stop      Stop a running container
    tag       Tag an image into a repository
    top       Lookup the running processes of a container
    unpause   Unpause a paused 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.
[root@bogon ~]# 

2. 镜像Image命令

2.1 docker images

  • docker images 当前镜像列表
[root@bogon ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
hello-world         latest              fd74c3615f76        4 months ago        13.34 kB

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

-a :列出本地所有的镜像(含中间映像层)
-q :只显示镜像ID。
--digests :显示镜像的摘要信息
--no-trunc :显示完整的镜像信息

2.2 docker search

  • docker search 查仓库image
[root@bogon ~]# docker search redis
NAME                             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
redis                            Redis is an open source key-value store th...   8097      [OK]       
bitnami/redis                    Bitnami Redis Docker Image                      143                  [OK]
sameersbn/redis                                                                  79                   [OK]
grokzen/redis-cluster            Redis cluster 3.0, 3.2, 4.0 & 5.0               67                   
rediscommander/redis-commander   Alpine image for redis-commander - Redis m...   38                   [OK]
kubeguide/redis-master           redis-master with "Hello World!"                31                   
redislabs/redis                  Clustered in-memory database engine compat...   24                   
arm32v7/redis                    Redis is an open source key-value store th...   21                   
oliver006/redis_exporter          Prometheus Exporter for Redis Metrics. Su...   21                   
redislabs/redisearch             Redis With the RedisSearch module pre-load...   21                   
bitnami/redis-sentinel           Bitnami Docker Image for Redis Sentinel         13                   [OK]
redislabs/redisgraph             A graph database module for Redis               11                   [OK]
webhippie/redis                  Docker images for Redis                         11                   [OK]
s7anley/redis-sentinel-docker    Redis Sentinel                                  10                   [OK]
insready/redis-stat              Docker image for the real-time Redis monit...   9                    [OK]
arm64v8/redis                    Redis is an open source key-value store th...   9                    
redislabs/redismod               An automated build of redismod - latest Re...   7                    [OK]
centos/redis-32-centos7          Redis in-memory data structure store, used...   5                    
redislabs/redisinsight           RedisInsight - The GUI for Redis                5                    
circleci/redis                   CircleCI images for Redis                       4                    [OK]
clearlinux/redis                 Redis key-value data structure server with...   2                    
tiredofit/redis                  Redis Server w/ Zabbix monitoring and S6 O...   1                    [OK]
wodby/redis                      Redis container image with orchestration        1                    [OK]
runnable/redis-stunnel           stunnel to redis provided by linking conta...   1                    [OK]
xetamus/redis-resource           forked redis-resource                           0                    [OK]
[root@bogon ~]# 


列项含义:
OFFICIAL 是否官方

OPTIONS说明:
-s : 列出收藏数不小于指定值的镜像
--no-trunc : 显示完整的镜像描述
--automated : 只列出 automated build类型的镜像;

https://hub.docker.com
  • docker search -s 100
[root@bogon ~]# docker search -s 100 redis
NAME            DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
redis           Redis is an open source key-value store th...   8097      [OK]       
bitnami/redis   Bitnami Redis Docker Image                      143                  [OK]
[root@bogon ~]# 

  • docker search --no-trunc redis
[root@bogon ~]# docker search  --no-trunc redis
NAME                             DESCRIPTION                                                                            STARS     OFFICIAL   AUTOMATED
redis                            Redis is an open source key-value store that functions as a data structure server.     8097      [OK]       
bitnami/redis                    Bitnami Redis Docker Image                                                             143                  [OK]
sameersbn/redis                                                                                                         79                   [OK]
grokzen/redis-cluster            Redis cluster 3.0, 3.2, 4.0 & 5.0                                                      67                   
rediscommander/redis-commander   Alpine image for redis-commander - Redis management tool.                              38                   [OK]
kubeguide/redis-master           redis-master with "Hello World!"                                                       31                   
redislabs/redis                  Clustered in-memory database engine compatible with open source Redis by Redis Labs    24                   
arm32v7/redis                    Redis is an open source key-value store that functions as a data structure server.     21                   
oliver006/redis_exporter          Prometheus Exporter for Redis Metrics. Supports Redis 2.x, 3.x, 4.x and 5.x           21                   
redislabs/redisearch             Redis With the RedisSearch module pre-loaded. See http://redisearch.io                 21                   
bitnami/redis-sentinel           Bitnami Docker Image for Redis Sentinel                                                13                   [OK]
webhippie/redis                  Docker images for Redis                                                                11                   [OK]
redislabs/redisgraph             A graph database module for Redis                                                      11                   [OK]
s7anley/redis-sentinel-docker    Redis Sentinel                                                                         10                   [OK]
insready/redis-stat              Docker image for the real-time Redis monitoring tool redis-stat                        9                    [OK]
arm64v8/redis                    Redis is an open source key-value store that functions as a data structure server.     9                    
redislabs/redismod               An automated build of redismod - latest Redis with select modules.                     7                    [OK]
redislabs/redisinsight           RedisInsight - The GUI for Redis                                                       5                    
centos/redis-32-centos7          Redis in-memory data structure store, used as database, cache and message broker       5                    
circleci/redis                   CircleCI images for Redis                                                              4                    [OK]
clearlinux/redis                 Redis key-value data structure server with the benefits of Clear Linux OS              2                    
tiredofit/redis                  Redis Server w/ Zabbix monitoring and S6 Overlay based on Alpine                       1                    [OK]
runnable/redis-stunnel           stunnel to redis provided by linking containers                                        1                    [OK]
wodby/redis                      Redis container image with orchestration                                               1                    [OK]
xetamus/redis-resource           forked redis-resource                                                                  0                    [OK]
[root@bogon ~]# 

  • docker search --automated
[root@bogon ~]# docker search --automated redis
NAME                             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
bitnami/redis                    Bitnami Redis Docker Image                      143                  [OK]
sameersbn/redis                                                                  79                   [OK]
rediscommander/redis-commander   Alpine image for redis-commander - Redis m...   38                   [OK]
bitnami/redis-sentinel           Bitnami Docker Image for Redis Sentinel         13                   [OK]
webhippie/redis                  Docker images for Redis                         11                   [OK]
redislabs/redisgraph             A graph database module for Redis               11                   [OK]
s7anley/redis-sentinel-docker    Redis Sentinel                                  10                   [OK]
insready/redis-stat              Docker image for the real-time Redis monit...   9                    [OK]
redislabs/redismod               An automated build of redismod - latest Re...   7                    [OK]
circleci/redis                   CircleCI images for Redis                       4                    [OK]
tiredofit/redis                  Redis Server w/ Zabbix monitoring and S6 O...   1                    [OK]
runnable/redis-stunnel           stunnel to redis provided by linking conta...   1                    [OK]
wodby/redis                      Redis container image with orchestration        1                    [OK]
xetamus/redis-resource           forked redis-resource                           0                    [OK]
[root@bogon ~]# 

2.3 docker pull

  • docker pull
[root@bogon ~]# docker pull redis
latest: Pulling from redis
e621dc7f5dcb: Pull complete 
6cb216111959: Pull complete 
d2a28d16dda1: Pull complete 
54608bf51701: Pull complete 
bdb3ccfce7c3: Pull complete 
733c5a73f928: Pull complete 
0e30f6cd8bd1: Pull complete 
88c2a75767e5: Pull complete 
823034f5b5bc: Pull complete 
c47c92aafd2d: Pull complete 
e88c19da87df: Pull complete 
bf0bfb23d972: Pull complete 
314c172b90b8: Pull complete 
0474d2370250: Pull complete 
78e6917b1def: Pull complete 
0967c4304dd8: Pull complete 
Digest: sha256:ee90e44e1b03e5dc78e7bde0a0f257c782a3d890fda19c817b7595f309027a88
Status: Downloaded newer image for redis:latest



[root@bogon ~]# docker images;
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
redis               latest              0967c4304dd8        2 hours ago         104.1 MB
hello-world         latest              fd74c3615f76        4 months ago        13.34 kB
[root@bogon ~]# 

2.4 docker rmi 删除镜像

  • docker rmi
root@bogon ~]# docker rmi hello-world
Error response from daemon: Conflict, cannot delete fd74c3615f76 because the container 708bcd87ef5e is using it, use -f to force
Error: failed to remove images: [hello-world]

  • docker rmi -f hello-world 强制删除镜像
[root@bogon ~]# docker rmi -f hello-world
Untagged: hello-world:latest
Deleted: fd74c3615f76e548000499194419d582abcb4d037e28f302da98e09fe6082b07
Deleted: 482c215f2373801ac5205df8397741792cc3a1f2f8e8a13e042463d93b3b8364


[root@bogon ~]# docker images;
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
redis               latest              0967c4304dd8        2 hours ago         104.1 MB
[root@bogon ~]# 

docker pull centos:centos7
  • docker rmi -f dockerA:1.1 dockerB 强制删除多个镜像

  • docker rmi -f $(docker images -qa) 删除全部

2.5 docker login/logout

docker login : 登陆到一个Docker镜像仓库,如果未指定镜像仓库地址,默认为官方仓库 Docker Hub

docker logout : 登出一个Docker镜像仓库,如果未指定镜像仓库地址,默认为官方仓库 Docker Hub


docker login [OPTIONS] [SERVER]
docker logout [OPTIONS] [SERVER]
OPTIONS说明:
-u :登陆的用户名
-p :登陆的密码

如果登陆阿里云

docker login --username ****.aliyuncs.com

2.6 docker push

docker push : 将本地的镜像上传到镜像仓库,要先登陆到镜像仓库
首先要docker login,如果登陆阿里云后,进入镜像列表,确定命令空间和仓库名称

docker push [OPTIONS] NAME[:TAG]
OPTIONS说明:
--disable-content-trust :忽略镜像的校验,默认开启

docker push myapache:v1

3.容器Container命令

3.1 docker run imageId运行某镜像

  • docker run -it imageId 运行镜像容器
  • docker run -it --name MyImageName imageId 运行镜像容器运行的名称为MyImageName
  • docker run -it -p 9090:8080 tomcat 指定端口映射关系启动 //如果本地没有tomcat:latest,则会自动下载镜像

如果运行时报错: FATAL: kernel too old 参考如下文章:https://blog.csdn.net/qq_34430649/article/details/103603294

OPTIONS说明(常用):有些是一个减号,有些是两个减号

--name="容器新名字": 为容器指定一个名称;
-d: 后台运行容器,并返回容器ID,也即启动守护式容器;
-i:以交互模式运行容器,通常与 -t 同时使用;
-t:为容器重新分配一个伪输入终端,通常与 -i 同时使用;
-P: 随机端口映射;
-p: 指定端口映射,有以下四种格式
    ip:hostPort:containerPort
    ip::containerPort
    hostPort:containerPort
    containerPort
[root@bogon ~]# docker pull centos:centos7
centos7: Pulling from centos
eb005c722abd: Pull complete 
8da6d29be907: Pull complete 
cedef0cc26e8: Pull complete 
Digest: sha256:09b9aeb75503921851eb0cf27045e20e4e0a62cad6a2dd57434cdc9ee9da8490
Status: Downloaded newer image for centos:centos7


[root@bogon ~]# docker images;
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
tomcat              latest              052a153114e9        7 days ago          647.2 MB
centos              latest              495a24dc98e8        3 months ago        237.1 MB
centos              centos7             cedef0cc26e8        5 months ago        203 MB
[root@bogon ~]# docker run -it cedef0cc26e8
[root@73bac9b3b58e /]# ls
anaconda-post.log  bin  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@73bac9b3b58e /]# ll
total 56
-rw-r--r--.   1 root root 12123 Oct  1  2019 anaconda-post.log
lrwxrwxrwx.   1 root root     7 Oct  1  2019 bin -> usr/bin
drwxr-xr-x.   5 root root   380 May  2 07:15 dev
drwxr-xr-x.  47 root root  4096 May  2 07:15 etc
drwxr-xr-x.   2 root root  4096 Apr 11  2018 home
lrwxrwxrwx.   1 root root     7 Oct  1  2019 lib -> usr/lib
lrwxrwxrwx.   1 root root     9 Oct  1  2019 lib64 -> usr/lib64
drwxr-xr-x.   2 root root  4096 Apr 11  2018 media
drwxr-xr-x.   2 root root  4096 Apr 11  2018 mnt
drwxr-xr-x.   2 root root  4096 Apr 11  2018 opt
dr-xr-xr-x. 173 root root     0 May  2 07:15 proc
dr-xr-x---.   2 root root  4096 Oct  1  2019 root
drwxr-xr-x.  11 root root  4096 Oct  1  2019 run
lrwxrwxrwx.   1 root root     8 Oct  1  2019 sbin -> usr/sbin
drwxr-xr-x.   2 root root  4096 Apr 11  2018 srv
drwxr-xr-x   13 root root     0 Oct  7  2017 sys
drwxrwxrwt.   7 root root  4096 Oct  1  2019 tmp
drwxr-xr-x.  13 root root  4096 Oct  1  2019 usr
drwxr-xr-x.  18 root root  4096 Oct  1  2019 var
[root@73bac9b3b58e /]# 

[root@bogon ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
7969c8b85f87        cedef0cc26e8        "/bin/bash"         4 seconds ago       Up 3 seconds                            serene_torvalds     
[root@bogon ~]# 


[root@73bac9b3b58e /]# exit;
exit
[root@bogon ~]# 

3.2 运行挂载数据卷/数据卷容器

3.2.1 挂载命令

  • docker run -it -v /hostDir(宿主机绝对路径目录):/containerDir(容器内目录) imageId //挂载数据卷启动
  • docker run -it -v /hostDir(宿主机绝对路径目录):/containerDir(容器内目录):ro imageId //挂载容数据卷启动,容器只读(宿主机可以创建/修改,在容器内只能读取(不能创建/修改))
[root@bogon ~]# docker images;
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
tomcat              7                   f8d0c8917802        9 days ago          529.3 MB
tomcat              8                   5825432eaa9a        9 days ago          529.1 MB
tomcat              latest              052a153114e9        9 days ago          647.2 MB
centos              centos7             cedef0cc26e8        5 months ago        203 MB

//运行挂载数据卷
docker run -it -v /testHostDir:/testContainerDir cedef0cc26e8
 
[root@bogon testHostDir]# docker ps;
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
4a54608599c3        cedef0cc26e8        "/bin/bash"         2 minutes ago       Up 2 minutes                            mad_albattani       
[root@bogon testHostDir]# docker inspect 4a54608599c3


  "Volumes": {
        "/testContainerDir": "/testHostDir"
    },
    "VolumesRW": {
        "/testContainerDir": true
    },



//挂载数据卷
[root@bogon ~]# docker run -it -v /testHostDir2:/testContainerDir2:ro cedef0cc26e8
[root@bogon testHostDir]# docker ps;
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
8974fe687305        cedef0cc26e8        "/bin/bash"         53 seconds ago      Up 52 seconds                           lonely_hoover       
4a54608599c3        cedef0cc26e8        "/bin/bash"         40 minutes ago      Up 40 minutes                           mad_albattani       
[root@bogon testHostDir]# docker inspect 8974fe687305

 "Volumes": {
        "/testContainerDir2": "/testHostDir2"
    },
    "VolumesRW": {
        "/testContainerDir2": false
    },
    "AppArmorProfile": "",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": [
            "/testHostDir2:/testContainerDir2:ro"
        ],

3.2.2 数据卷容器

docker run --volumes-from

docker run -it -v /testHostDir1:/testContainerDir1 centos7 --name  testContainer1 
docker run -it --name testContainer2 --volumes-from  testContainer1 centos7

3.2.3 挂载说明

  • docker inspect 容器ID 中查看挂载数据卷的情况;
  • 挂载数据卷自动创建文件夹,包括宿主机和容器机器都创建;
  • 宿主机和容器数据相互共享,两边都可以添加/修改文件及内容,并且相互都能到修改后的结果;
  • 容器停止后在宿主机修改文件,待容器再次启动后也能看到修改后的结果;
  • 容器数据卷配置信息(-volumes-from )的传递,数据卷的生命周期一直持续到没有容器使用它为止(即使rm了源头容器ID,只要有一个容器使用该容器卷,就一直保留数据卷).

3.3 docker ps 查看运行中的镜像容器

  • docker ps 查看运行中的镜像容器
  • docker ps -l 查看运行的上一个镜像容器
  • docker ps -5 查看运行的上5个镜像容器
OPTIONS说明(常用):
 
-a :列出当前所有正在运行的容器+历史上运行过的
-l :显示最近创建的容器。
-n:显示最近n个创建的容器。
-q :静默模式,只显示容器编号。
--no-trunc :不截断输出。

3.4 退出

  • exit 容器停止退出
  • ctrl+P+Q **容器不停止退出 **

3.5 docker start/stop/kill 启动/关闭/强制关闭

docker start 容器ID或者容器名 

docker stop 容器ID或者容器名  

docker kill 容器ID或者容器名

3.6 删除容器

docker rm 容器ID

docker rm -f $(docker ps -a -q) 删除多个容器

docker ps -a -q | xargs docker rm 删除多个容器

3.7 后台运行

docker容器后台运行,就必须有一个前台进程 ,
容器运行的命令如果不是那些一直挂起的命令(比如运行top,tail),就是会自动退出的。
最佳的解决方案是,将你要运行的程序以前台进程的形式运行

#使用镜像centos:latest以后台模式启动一个容器
docker run -d centos

docker ps //会发现没有正在运行的进程
[root@bogon ~]# docker run -d cedef0cc26e8
37435dd951fb937610e5883d052027817942eaa7ebc550d701677fbd6142abbc
[root@bogon ~]# docker ps;
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@bogon ~]# 

3.8 查看容器中日志

docker logs imageId; 
docker logs -t -f --tail 3 imageId;


 -t 是加入时间戳
 -f 跟随最新的日志打印
 --tail n 显示最后N条

3.9 查看容器中的进程

docker top 容器ID


[root@bogon ~]# docker top 9f74500205d1
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                34197               23853               0                   00:55               pts/7               00:00:00            /bin/bash
[root@bogon ~]# 

3.10 查看容器中的细节

docker inspect 容器ID


[root@bogon ~]# docker inspect 9f74500205d1
[
{
    "Id": "9f74500205d1238d2e649579ca3220c82b9923501560fde9016c868439006b5a",
    "Created": "2020-05-03T07:55:10.418414621Z",
    "Path": "/bin/bash",
    "Args": [],
    "State": {
        "Running": true,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 34197,
        "ExitCode": 0,
        "Error": "",
        "StartedAt": "2020-05-03T07:55:10.875841761Z",
        "FinishedAt": "0001-01-01T00:00:00Z"
    },
    "Image": "cedef0cc26e82e678f4b329c5a7813ea3cbf3fc7468631a3f0e2a4e5b07b9c81",
    "NetworkSettings": {
        "Bridge": "",
        "EndpointID": "2059913d8a56cd1e920a0bbb9e0090e03a44dd426eb54621018e880d6690df61",
        "Gateway": "172.17.42.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "HairpinMode": false,
        "IPAddress": "172.17.0.15",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "MacAddress": "02:42:ac:11:00:0f",
        "NetworkID": "5a99a61f8f5947ac03f20bd12082d856b1b8b1e664fce633e802f7864be76cbe",
        "PortMapping": null,
        "Ports": {},
        "SandboxKey": "/var/run/docker/netns/9f74500205d1",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null
    },
    "ResolvConfPath": "/var/lib/docker/containers/9f74500205d1238d2e649579ca3220c82b9923501560fde9016c868439006b5a/resolv.conf",
    "HostnamePath": "/var/lib/docker/containers/9f74500205d1238d2e649579ca3220c82b9923501560fde9016c868439006b5a/hostname",
    "HostsPath": "/var/lib/docker/containers/9f74500205d1238d2e649579ca3220c82b9923501560fde9016c868439006b5a/hosts",
    "LogPath": "/var/lib/docker/containers/9f74500205d1238d2e649579ca3220c82b9923501560fde9016c868439006b5a/9f74500205d1238d2e649579ca3220c82b9923501560fde9016c868439006b5a-json.log",
    "Name": "/silly_leakey",
    "RestartCount": 0,
    "Driver": "devicemapper",
    "ExecDriver": "native-0.2",
    "MountLabel": "",
    "ProcessLabel": "",
    "Volumes": {},
    "VolumesRW": {},
    "AppArmorProfile": "",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": null,
        "ContainerIDFile": "",
        "LxcConf": [],
        "Memory": 0,
        "MemorySwap": 0,
        "CpuShares": 0,
        "CpuPeriod": 0,
        "CpusetCpus": "",
        "CpusetMems": "",
        "CpuQuota": 0,
        "BlkioWeight": 0,
        "OomKillDisable": false,
        "Privileged": false,
        "PortBindings": {},
        "Links": null,
        "PublishAllPorts": false,
        "Dns": null,
        "DnsSearch": null,
        "ExtraHosts": null,
        "VolumesFrom": null,
        "Devices": [],
        "NetworkMode": "bridge",
        "IpcMode": "",
        "PidMode": "",
        "UTSMode": "",
        "CapAdd": null,
        "CapDrop": null,
        "RestartPolicy": {
            "Name": "no",
            "MaximumRetryCount": 0
        },
        "SecurityOpt": null,
        "ReadonlyRootfs": false,
        "Ulimits": null,
        "LogConfig": {
            "Type": "json-file",
            "Config": {}
        },
        "CgroupParent": ""
    },
    "Config": {
        "Hostname": "9f74500205d1",
        "Domainname": "",
        "User": "",
        "AttachStdin": true,
        "AttachStdout": true,
        "AttachStderr": true,
        "PortSpecs": null,
        "ExposedPorts": null,
        "Tty": true,
        "OpenStdin": true,
        "StdinOnce": true,
        "Env": [
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "/bin/bash"
        ],
        "Image": "cedef0cc26e8",
        "Volumes": null,
        "VolumeDriver": "",
        "WorkingDir": "",
        "Entrypoint": null,
        "NetworkDisabled": false,
        "MacAddress": "",
        "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"
        }
    }
}
]
[root@bogon ~]# 

3.11 docker exec -it 容器ID bashShell

通过Ctrl+P+Q退出的可以用该方法执行某命令

exec 是在容器中打开新的终端,并且可以启动新的进程

docker exec -it imageId /bin/bash 进入docker容器命令

docker exec -it 容器ID bashShell

[root@bogon ~]# docker ps 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
9f74500205d1        cedef0cc26e8        "/bin/bash"         5 minutes ago       Up 5 minutes                            silly_leakey  

[root@bogon ~]# docker exec -it 9f74500205d1 /bin/bash
[root@9f74500205d1 /]# 

##进去并执行命令
[root@bogon ~]# docker exec -t 9f74500205d1   ls -a /
.
..
.dockerenv
.dockerinit
anaconda-post.log
bin
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@bogon ~]# 

3.12 docker attach 容器ID

通过Ctrl+P+Q退出的可以用该方法再次进入
attach 直接进入容器启动命令的终端,不会启动新的进程

重新进入 docker attach 容器ID


[root@bogon ~]# docker attach 9f74500205d1
[root@9f74500205d1 /]# 

3.13 docker cp 容器ID:容器内路径 目的主机路径(拷贝容器内文件)

docker cp 容器ID:容器内路径 目的主机路径

docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-

docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

[root@bogon ~]# docker ps;
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
9f74500205d1        cedef0cc26e8        "/bin/bash"         20 minutes ago      Up 20 minutes                           silly_leakey        
[root@bogon ~]# docker cp 9f74500205d1:/usr/local/test.txt /usr/

3.14 docker commit 根据容器生成镜像

docker commit :从容器创建一个新的镜像。

docker commit :从容器创建一个新的镜像。

OPTIONS说明:
-a :提交的镜像作者;
-c :使用Dockerfile指令来创建镜像;
-m :提交时的说明文字;
-p :在commit时,将容器暂停
runoob@runoob:~$ docker commit -a "runoob.com" -m "my apache" a404c6c174a2  mymysql:v1 
sha256:37af1236adef1544e8886be23010b66577647a40bc02c0885a6600b33ee28057
runoob@runoob:~$ docker images mymysql:v1
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mymysql             v1                  37af1236adef        15 seconds ago      329 MB

3.15 总结

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Gh9KM6bq-1602256306880)(https://github.com/bobshute/public/blob/master/imgs/csdn/docker/docker%E5%91%BD%E4%BB%A4%E6%B1%87%E6%80%BB.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hXO6NhFd-1602256306882)(https://github.com/bobshute/public/blob/master/imgs/csdn/docker/docker%E7%BB%93%E6%9E%84%E5%9B%BE.png)]



attach    Attach to a running container                 # 当前 shell 下 attach 连接指定运行镜像
build     Build an image from a Dockerfile              # 通过 Dockerfile 定制镜像
commit    Create a new image from a container changes   # 提交当前容器为新的镜像
cp        Copy files/folders from the containers filesystem to the host path   #从容器中拷贝指定文件或者目录到宿主机中
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 an existing container        # 在已存在的容器上运行命令
export    Stream the contents of a container as a tar archive   # 导出容器的内容流作为一个 tar 归档文件[对应 import ]
history   Show the history of an image                  # 展示一个镜像形成历史
images    List images                                   # 列出系统当前镜像
import    Create a new filesystem image from the contents of a tarball # 从tar包中的内容创建一个新的文件系统映像[对应export]
info      Display system-wide information               # 显示系统相关信息
inspect   Return low-level information on a container   # 查看容器详细信息
kill      Kill a running container                      # kill 指定 docker 容器
load      Load an image from a tar archive              # 从一个 tar 包中加载一个镜像[对应 save]
login     Register or Login to the docker registry server    # 注册或者登陆一个 docker 源服务器
logout    Log out from a Docker registry server          # 从当前 Docker registry 退出
logs      Fetch the logs of a container                 # 输出当前容器日志信息
port      Lookup the public-facing port which is NAT-ed to PRIVATE_PORT    # 查看映射端口对应的容器内部源端口
pause     Pause all processes within a container        # 暂停容器
ps        List containers                               # 列出容器列表
pull      Pull an image or a repository from the docker registry server   # 从docker镜像源服务器拉取指定镜像或者库镜像
push      Push an image or a repository to the docker registry server    # 推送指定镜像或者库镜像至docker源服务器
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 to a tar archive                # 保存一个镜像为一个 tar 包[对应 load]
search    Search for an image on the Docker Hub         # 在 docker hub 中搜索镜像
start     Start a stopped containers                    # 启动容器
stop      Stop a running containers                     # 停止容器
tag       Tag an image into a repository                # 给源中镜像打标签
top       Lookup the running processes of a container   # 查看容器中运行的进程信息
unpause   Unpause a paused container                    # 取消暂停容器
version   Show the docker version information           # 查看 docker 版本号
wait      Block until a container stops, then print its exit code   # 截取容器停止时的退出状态值
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Docker Compose 是一个用于定义和运行多个 Docker 容器的工具。使用 Docker Compose,我们可以将多个容器的配置文件整合到一个 `docker-compose.yml` 文件中,并使用一个命令即可启动、停止、重启这些容器。 在配置 Docker Compose 时,首先需要创建一个名为 `docker-compose.yml` 的文件。在该文件中,我们可以定义多个服务(services),每个服务对应一个容器。通过指定镜像名称、端口映射、环境变量和容器启动命令等参数,我们可以对每个服务进行详细的配置。 在 `docker-compose.yml` 文件中,可以使用以下示例的语法来定义一个服务: ```yaml version: '3' services: web: image: nginx:latest ports: - 80:80 database: image: mysql:latest environment: - MYSQL_ROOT_PASSWORD=secret - MYSQL_DATABASE=mydb ``` 上述例子定义了两个服务,`web` 和 `database`。`web` 服务使用 `nginx:latest` 镜像,并将主机的 80 端口映射到容器的 80 端口。`database` 服务使用 `mysql:latest` 镜像,并指定了两个环境变量。 一旦 `docker-compose.yml` 文件配置完毕,我们可以在命令行中使用以下命令进行容器的管理: - `docker-compose up`:启动所有在 `docker-compose.yml` 文件中定义的容器; - `docker-compose down`:停止并删除所有容器; - `docker-compose start`:启动之前创建过的容器; - `docker-compose stop`:停止正在运行的容器; - `docker-compose restart`:重启正在运行的容器。 通过配置 Docker Compose,我们可以方便地管理和部署多个容器,提高开发和部署的效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值