当前位置:   article > 正文

Docker(二):Docker常用命令

Docker(二):Docker常用命令

在这里插入图片描述

docker

查看docker支持的所有命令和参数。

➜  ~ docker
Management Commands:
  config      Manage Docker configs
  container   Manage containers
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams 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 between a container and the local filesystem
  create      Create a new container
  deploy      Deploy a new stack or update an existing stack
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes


➜  ~ docker -v
Docker version 18.06.1-ce, build e68fc7a

➜  ~ docker info
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

docker COMMAND --help

查看某个具体命令的帮助文档:用途、参数。

➜  ~ docker image --help

Usage:	docker image COMMAND

Manage images

Commands:
  build       Build an image from a Dockerfile
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  inspect     Display detailed information on one or more images
  load        Load an image from a tar archive or STDIN
  ls          List images
  prune       Remove unused images
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rm          Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

Run 'docker image COMMAND --help' for more information on a command.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

查看某个子命令的具体使用文档。

➜  ~ docker image build --help

Usage:	docker image build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Options:
      --add-host list           Add a custom host-to-IP mapping (host:ip)
      --build-arg list          Set build-time variables
      --cache-from strings      Images to consider as cache sources
      --cgroup-parent string    Optional parent cgroup for the container
      --compress                Compress the build context using gzip
      --console                 Show console output (with buildkit only) (true, false, auto) (default auto)
      --cpu-period int          Limit the CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int           Limit the CPU CFS (Completely Fair Scheduler) quota
  -c, --cpu-shares int          CPU shares (relative weight)
      --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)
      --disable-content-trust   Skip image verification (default true)
  -f, --file string             Name of the Dockerfile (Default is 'PATH/Dockerfile')
      --force-rm                Always remove intermediate containers
      --iidfile string          Write the image ID to the file
      --isolation string        Container isolation technology
      --label list              Set metadata for an image
  -m, --memory bytes            Memory limit
      --memory-swap bytes       Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --network string          Set the networking mode for the RUN instructions during build (default "default")
      --no-cache                Do not use cache when building the image
      --platform string         Set platform if server is multi-platform capable
      --pull                    Always attempt to pull a newer version of the image
  -q, --quiet                   Suppress the build output and print image ID on success
      --rm                      Remove intermediate containers after a successful build (default true)
      --security-opt strings    Security options
      --shm-size bytes          Size of /dev/shm
      --squash                  Squash newly built layers into a single new layer
      --stream                  Stream attaches to server to negotiate build context
  -t, --tag list                Name and optionally a tag in the 'name:tag' format
      --target string           Set the target build stage to build.
      --ulimit ulimit           Ulimit options (default [])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

docker search

搜索镜像。

➜  ~ docker search openjdk
NAME                           DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
eclipse-temurin                Official Images for OpenJDK binaries built b…   525                 [OK]
openjdk                        Pre-release / non-production builds of OpenJ…   522                 [OK]
  • 1
  • 2
  • 3
  • 4

Docker Hub ( https://hub.docker.com/ ) Docker官方仓库,用于搜索仓库中的镜像,以及查看镜像中的具体使用文档等,也可以将自己的镜像推送到官方仓库中。
在这里插入图片描述

docker login

登录docker仓库。

➜  ~ docker login -u 用户名 -p 密码
Login Succeeded
  • 1
  • 2

docker pull

docker pull < image_name[:tag] > : 拉取某个镜像如果省略tag默认拉取latest。

➜  ~ docker pull openjdk:11
11: Pulling from library/openjdk
001c52e26ad5: Pull complete
d9d4b9b6e964: Pull complete
2068746827ec: Pull complete
9daef329d350: Pull complete
d85151f15b66: Pull complete
66223a710990: Pull complete
db38d58ec8ab: Pull complete
Digest: sha256:99bac5bf83633e3c7399aed725c8415e7b569b54e03e4599e580fc9cdb7c21ab
Status: Downloaded newer image for openjdk:11

# 拉取centos容器
docker pull centos
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

docker images

列举本地所有镜像。

-a:表示列举所有all镜像
-q:只列举镜像ID字段 IMAGE ID

# 查看本地所有镜像列表。
➜  ~ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
openjdk             11                  47a932d998b7        19 months ago       654MB

# 查看指定镜像
➜  ~ docker images openjdk
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
openjdk             11                  47a932d998b7        19 months ago       654MB
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

当REPOSITORY和TAG都是 < none > 时,称作虚悬镜像dangling image,没什么用,可以删除,造成虚悬镜像的原因是在docker build时出现错误导致的。

# 查找所有虚悬镜像
docker images ls -f dangling=true

# 删除所有虚悬镜像
docker image prune
  • 1
  • 2
  • 3
  • 4
  • 5

docker system

查看镜像、容器、数据卷 所占用空间。

docker system df
  • 1

docker rmi

删除镜像

# -f : 表示强制force删除,默认只能删除未使用的,删除时可以使用容器名:标签,也可以使用容器的id。
➜  ~ docker rmi -f  openjdk:11
➜  ~ docker rmi openjdk:11

# 强制删除所有容器(慎用)
docker rmi -f $(docker images -qa)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

docker save & docker load

导出镜像。docker save : 将本地镜像打成压缩包.tar,docker load:将镜像压缩包加载进来。

# -o:output
➜  ~ docker save -o openjdk11.tar  openjdk:11
# 也可以直接通过拷贝到另一台机器上 scp /root/openjdk11.tar 192.168.0.2:/root

➜  ~ docker rmi openjdk:11
➜  ~ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

# -i: input 输出信息
➜  ~ docker load -i  openjdk11.tar
9c742cd6c7a5: Loading layer [==================================================>]  129.2MB/129.2MB
03127cdb479b: Loading layer [==================================================>]   11.3MB/11.3MB
293d5db30c9f: Loading layer [==================================================>]  19.31MB/19.31MB
9b55156abf26: Loading layer [==================================================>]  156.5MB/156.5MB
b626401ef603: Loading layer [==================================================>]  11.74MB/11.74MB
826c3ddbb29c: Loading layer [==================================================>]  3.584kB/3.584kB
7b7f3078e1db: Loading layer [==================================================>]  337.8MB/337.8MB
Loaded image: openjdk:11


➜  ~ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
openjdk             11                  47a932d998b7        19 months ago       654MB
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

docker export & docker import

导出容器。

# 讲某个容器导出成一个tar包
docker export 容器名  > xxx.tar

# 和docker load不同的是可以指定镜像用户/镜像名:镜像版本号
cat xxx.tar | docker import - 镜像用户名/镜像名:镜像版本号
  • 1
  • 2
  • 3
  • 4
  • 5

docker volume

  • volume 数据卷,用于宿主机目录和容器中的目录的双向绑定,互相映射,达到数据持久化备份 的作用。
  • 映射后可以直接在宿主机上修改容器上的文件,同样在容器中修改文件也会同步修改宿主机上。也可以配置容器中的目录权限,rw:读写,ro:read only只读。
  • 一般都是在docker run 时通过-v参数指定映射,指定后会自动创建映射,一般不需要手动执行数据卷的创建。

数据卷挂载的好处:

  1. 修改查看方便,不需要再登录到容器内部查看,只需要在宿主机上查看即可。
  2. 像配置文件(如conf.d)、数据文件(如mysql的data目录) 是需要持久化的,防止容器出现问题时重要数据丢失。
# 创建数据卷,默认挂载在/var/lib/docker/volumes/目录下
docker volumn create <数据卷名>

# 查看所有数据卷名
docker volumn ls

# 查看数据卷详情
docker volumn inspect <数据卷名>

# 删除指定的数据卷
docker volumn rm <数据卷名>

# 删除所有未使用的数据卷
docker volumn prune
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
➜  ~ docker volume create html
html
➜  ~ docker volume ls
DRIVER              VOLUME NAME
local               html
➜  ~ docker volume inspect html
[
    {
        "CreatedAt": "2024-03-23T14:27:17Z",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/html/_data",
        "Name": "html",
        "Options": {},
        "Scope": "local"
    }
]
➜  ~ docker volume rm html
html

➜  ~ docker volume prune
WARNING! This will remove all local volumes not used by at least one container.
Are you sure you want to continue? [y/N] y
Total reclaimed space: 0B
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

docker run

docker run :如果镜像不存在先下载镜像然后再运行镜像,注意:每次运行都会创建一个新的容器。就像编程中每次new都会生成一个新的实例对象一样。

# -i: 创建一个交互式容器
# -t: --tty tty终端(分配一个终端来操作容器)
# -d: --detach 后台运行
# --name: 容器名称(唯一)
# -p: port 端口映射 宿主机端口:容器内端口,宿主机端口可以自定义指定,容器内端口一般都是默认的不变的, -p可以配置多对,一般像nignx的可能会映射多个端口
# -v:volume, 数据卷目录映射双向绑定,可以使用数据卷名映射容器目录, -v 数据卷名:容器内目录
# 也可以直接使用将宿主机目录映射到容器目录(宿主机目录必须以/或者./开头),-v 本地目录:容器内目录
# 指定了数据卷映射会自动创建数据卷,不需要显式执行docker volumn create命令创建
# 使用-v参数最好增加--privileged=true参数,不加也可以,建议使用
# 数据卷默认是双向映射,容器内容器外都可以读写rw, 也可以设置容器内只读readonly不能写,语法是在容器内后面使用冒号配置读写权限:宿主机目录:容器内目录:ro
# 一个容器的数据卷也可以只从另一个容器来继承,语法:--volumes-from 容器名
# -e:environment 环境参数,镜像内部需要使用到的参数,不同的镜像使用到的环境变量不同 
# 如果省略tag默认为latest,如果拉取的镜像是指定版本的,这里要显式指定版本号
# --restart=always : 表示当docker服务器重启后容器也要跟着重启,就像Linux的开启自动启动应用一样,默认为no
# --network 网络名 : 连接指定网桥

# 创建交互式容器
docker run -itd \
	--name <container name>  \
	-p 宿主机端口:容器内端口 \
	-e 环境变量名=\
	--privileged=true \
	-v 宿主机目录:容器目录 \
	--restart=always
	<image name[:tag]>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
# 关于mysql的所有配置都可以在Docker Hub上查到
➜  ~ docker run -d \
        --name mysql \
        -p 3307:3306 \
        -e TZ=Asia/Shanghai \
        -e MYSQL_ROOT_PASSWORD=123456 \
        -v /root/volumes/mysql/data:/var/lib/mysql \
        -v /root/volumes/mysql/conf:/etc/mysql/conf.d \
        mysql:5.7.34
Unable to find image 'mysql:5.7.34' locally
5.7.34: Pulling from library/mysql   
b4d181a07f80: Pull complete
a462b60610f5: Pull complete
578fafb77ab8: Pull complete
524046006037: Pull complete
d0cbe54c8855: Pull complete
aa18e05cc46d: Pull complete
32ca814c833f: Pull complete
52645b4af634: Pull complete
bca6a5b14385: Pull complete
309f36297c75: Pull complete
7d75cacde0f8: Pull complete
Digest: sha256:1a2f9cd257e75cc80e9118b303d1648366bc2049101449bf2c8d82b022ea86b7
Status: Downloaded newer image for mysql:5.7.34
df4a9dbf3661ee5b14fda3fe3e754d276f1bc2c5b81c68c9d998b74e10c076ff
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
#docker run 后面可以跟 /bin/bash 进入容器,此时可以通过exit退出,此时会停止容器,
# 也可以通过ctrl+p+q退出,此时不会停止容器。

docker urn -it ubuntu /bin/bash
  • 1
  • 2
  • 3
  • 4

查看docker run 时的启动参数

sudo yum -y install epel-release
yum -y install python-pip
pip install runlike

runlike -p 容器名
  • 1
  • 2
  • 3
  • 4
  • 5
[root@localhost ~]# pip
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    load_entry_point('pip==21.1.2', 'console_scripts', 'pip')()
  File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
    return ep.load()
  File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
    entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  File "/usr/lib/python2.7/site-packages/pip/__init__.py", line 1, in <module>
    from typing import List, Optional
ImportError: No module named typing
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

解决方案:

curl -O https://bootstrap.pypa.io/pip/2.7/get-pip.py
python get-pip.py
python -m pip install --upgrade "pip < 21.0
  • 1
  • 2
  • 3

在这里插入图片描述

docker kill

强制停止容器。

docker kill mysql 
  • 1

docker inspect

查看容器的所有配置详情:如数据卷挂载、端口映射、环境变量、网络IP地址 等。

➜  ~ docker inspect mysql
[
    {
        "Id": "4013c283ea9cf2d01f8b51e501296295813cd37646283597adfb0635a0558d27",
        "HostConfig": {
            "Binds": [
                "/Users/mengday/Softwares/Linux/volumes/mysql/data:/var/lib/mysql",
                "/Users/mengday/Softwares/Linux/volumes/mysql/conf:/etc/mysql/conf.d"
            ]
        },
 
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/Users/mengday/Softwares/Linux/volumes/mysql/data",
                "Destination": "/var/lib/mysql"
            },
            {
                "Type": "bind",
                "Source": "/Users/mengday/Softwares/Linux/volumes/mysql/conf",
                "Destination": "/etc/mysql/conf.d" 
            }
        ],
        "Config": {
            "Hostname": "4013c283ea9c",
           
            "Env": [
                "TZ=Asia/Shanghai",
                "MYSQL_ROOT_PASSWORD=123456",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.12",
                "MYSQL_MAJOR=5.7",
                "MYSQL_VERSION=5.7.34-1debian10"
            ],
            "Cmd": [
                "mysqld"
            ],
            "Image": "mysql:5.7.34",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ]
        },
        "NetworkSettings": {
            "Ports": {
                "3306/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "3307"
                    }
                ]
            },
            
            "Gateway": "172.17.0.1",
            "IPAddress": "172.17.0.2"
        }
    }
]

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
# 查看容器的ip地址属性,docker的ip为172.17.0.1,其它容器的依次是172.17.0.2递增
docker inspect -f='{{.NetworkSettings.IPAddress}}' container_name/container_id
  • 1
  • 2

docker network

Docker在安装的是会创建一个docker0网卡,它在内核层连通了其它物理或虚拟网卡,这就是将所有容器和本地主机放在同一个物理网络,让主机和容器之间可以通过网桥相互通信

每个容器都有自己的IP地址,默认情况下所有容器都是以bridge的方式连接到Docker的一个虚拟网桥上 172.17.0.1/16, /16表示IP前两段是固定的,只有后两段式可以变的,在同一个网段的容器之间时可以互相访问的,但是容器在重启的时候IP地址会变,如果IP地址发生了变化那么代码中配置固定的IP就访问不了了,可以通过自定义网络,自定义网络可以通过容器名来互相访问。一旦容器加入了自定义的网络名就不会加入默认的网桥了。如果两个容器(软件)同时加入同一个自定义网络,那么容器之间互访可以直接通过容器名来访问。

yum install net-tools -y
ifconfig
  • 1
  • 2

在这里插入图片描述

# 网络列表,默认的是桥接方式bridge可以和宿主机和外网通信
docker network ls


# 查看使用bridge的容器
docker network inspect bridge

# 创建一个网络
# 自定义网络本身就维护好了 主机名和ip的对应关系(保证通过ip和主机名都能ping通)
docker network create <网络名>

docker network connection <网络名> <容器名>

# 删除某个自定义网络
docker network rm <网络名>
# 删除所有未使用的网络
docker network prune
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
# bridge(默认方式):为每个容器分配设置IP,并将容器连接到docker0网桥上。
# host:容器不会虚拟自己的网卡也不会配置自己的IP,而是统一使用宿主机的IP和端口。
# 启动容器时使用配置 --network host 不需要指定-p端口映射,使用默认的端口,因host使用宿主机的ip所以对应的容器的NetworkSettings.IPAddress和Gateway都为空""
➜  ~ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f18b70eee01c        bridge              bridge              local
bcb18ec1867c        host                host                local
75d5d48759de        none                null                local

➜  ~ docker network inspect bridge
{
"NetworkSettings": {
    "Bridge": "",
    "Gateway": "172.17.0.1",
    "IPAddress": "172.17.0.2",
    "MacAddress": "02:42:ac:11:00:02",
    "Networks": {
        "bridge": {
            "Gateway": "172.17.0.1",
            "IPAddress": "172.17.0.2",
            "MacAddress": "02:42:ac:11:00:02"
        }
    }
}


➜  ~ docker network create mynet
4e710a555792fe1e70f176367051b8797e310a8c448bbcab31bbe3391b02863d
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

将容器加入自定义网络,凡是加入自定义网络的容器间都可以通过容器名相互访问。

# 运行时指定容器
➜  ~ docker run -d \
        --name mysql \
        -p 3307:3306 \
        -e TZ=Asia/Shanghai \
        -e MYSQL_ROOT_PASSWORD=123456 \
        --network mynet \
        -v /Users/mengday/Softwares/Linux/volumes/mysql/data:/var/lib/mysql \
        -v /Users/mengday/Softwares/Linux/volumes/mysql/conf:/etc/mysql/conf.d \
        mysql:5.7.34
2b11fc9977f180129fd2ef92fcc45a6c6286c2c64df8aab0bf5026928deedb67


# 如果mysql和java应用程序都加入了自定义网络 mynet, 那么在java容器中 ping mysql 就能ping通
➜  ~ docker exec -it myweb /bin/bash
# 直接ping容器名就可以ping通,也就是Java中的application.yml中的ip地址可以直接配置成容器名。
ping mysql


➜  ~ docker inspect mysql

[
	{
		"NetworkSettings": {
            # mynet 自定义网络
            "Networks": {
                "mynet": {
                    "NetworkID": "4e710a555792fe1e70f176367051b8797e310a8c448bbcab31bbe3391b02863d",
                    "EndpointID": "40d3dbb19c7260448026b3fa5a6059a12c5e129cff2c1505e006a05e5f100753",
                    "Gateway": "172.18.0.1",
                    "IPAddress": "172.18.0.2",
                    "MacAddress": "02:42:ac:12:00:02"
                }
            }
        }
	}
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

docker top

查看容器的进程信息。

docker top <container_name/container_id>
docker top <container_name/container_id> -eo pid,comm


➜  ~ docker top mysql
PID                 USER                TIME                COMMAND
78460               999                 0:03                mysqld
➜  ~
➜  ~ docker top mysql -eo pid,comm
PID                 COMMAND
78460               mysqld
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

docker ps

查看容器列表。

# 查看启动的容器(不包含停止的容器)
➜  ~ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
2b11fc9977f1        mysql:5.7.34        "docker-entrypoint.s…"   9 minutes ago       Up 9 minutes        33060/tcp, 0.0.0.0:3307->3306/tcp   mysql

# 查看所有容器(包括已经停止的容器) -a=all
➜  ~ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
2b11fc9977f1        mysql:5.7.34        "docker-entrypoint.s…"   9 minutes ago       Up 9 minutes        33060/tcp, 0.0.0.0:3307->3306/tcp   mysql


# 查看最后一次运行的容器
docker ps -l

# 查询返回最近n个
docker ps -n 2

# 查看容器的CONTAINER ID
docker ps -q

# -f指定输出特定的列
docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Ports}}\t{{.Status}}\t{{.Names}}"

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

docker stop & docker attach &docker start & docker restart

停止、启动、重启 容器。

➜  ~ docker stop mysql
mysql

# 后台启动一个容器后,使用该命令进入这个容器
# 启动并进入一个容器
docker attach container_name/container_id
# 启动容器
docker start container_name/container_id
# 重启容器
docker restart container_name/container_id
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

docker rm

删除容器。

# 只能删除未启动点的容器
➜  ~ docker rm mysql
mysql

# 强制删除容器
➜  ~ docker rm -f mysql


# 删除所有停止的容器(慎用)
# -a: all 显示所有容器
# -q: quiet 只显式容器id这列的值
# -f: force 强制删除(容器启动也会删除)
docker rm -f $(docker ps -a -q)

# 将前一个命令的结果传递xargs变量上,删除所有容器
docker ps -a -q | xargs docker rm
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

docker network connect & docker network disconnect

加入到自定义网络。

# 将某个容器加入到自定义的网络
docker network connect <网络名> <容器名>


# 断开某个网络
docker network disconnect <网络名> <容器名>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

docker exec & docker attach & exit

docker exec

docker exec 进入容器执行和容器相关的命令。工作中一般使用exec。
exec是在容器中打开新的终端,并且可以启动新的进程,用exit退出,不会导致容器的停止。

# 进入镜像
docker exec -it <image_name> /bin/bash
docker exec -it <image_name> bash

# 可以直接跟具体的命令
docker exec -it <image_name> 应用命令
docker exec -it mysql mysql -root -p
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
# 交互式容器:exit会停止运行容器
# 守护式容器:exit会退出容器,并不会停止运行容器
exit
  • 1
  • 2
  • 3
# 进入容器
➜  ~ docker exec -it mysql /bin/bash
root@2b11fc9977f1:/# pwd
/
# 登录mysql
root@2b11fc9977f1:/# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.34 MySQL Community Server (GPL)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.13 sec)

# 退出mysql
mysql> quit;
Bye

# 退出容器
root@2b11fc9977f1:/# exit
exit

➜  ~
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

docker attach

重新进入容器。
直接进入容器启动命令的终端,不会启动新的进程,用exit退出会导致容器的停止。

docker attach <容器名|Id>

# 退出后容器停止了
docker ps
  • 1
  • 2
  • 3
  • 4

docker attach 和 docker exec 的区别:

  • docker attach启动后就立即进入容器,exit后直接停止容器。
  • docker run后,使用docker exec进入容器,exit后不会停止容器。

docker cp

宿主机与容器内目录的文件拷贝。

# 将宿主机中的文件拷贝到某个容器的某个目录下
docker cp 文件名 容器名:/目录

# 将某个容器中的某个文件拷贝到宿主机中
docker cp 容器名:/文件绝对路径 宿主机目录

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

docker logs

查看容器日志,常用于查看Java输出的日志。

# 查看容器日志
docker logs container_name/container_id
# 查看容器日志:-f:持续输出 flow
docker logs -f container_name/container_id 

  • 1
  • 2
  • 3
  • 4
  • 5

docker build

根据Dockerfile文件构建镜像,常用于构建Java镜像。

# 编译镜像
# -f = --file Dockerfile的路径
# -t = --tag 'name:tag'格式, 标签就是版本号,可以为数字如1.0.0也可以是字母如latest
# build-content-path Dockerfile所在的目录 . 表示当前目录
docker build -t <name:tag> <build-content-path>
  • 1
  • 2
  • 3
  • 4
  • 5

docker tag

给镜像打标签。

# 打标签
docker tag <image_name:tag> <仓库地址/仓库名:版本号>
  • 1
  • 2

docker push

将镜像推送到远程仓库。

docker push <用户名>/<仓库名>:<Tag>
  • 1

docker commit

提交容器副本使之成为一个新的镜像。注意:执行commit命令需要退出容器,在容器外执行。

Docker中的镜像分层,支持通过扩展现有镜像,创建新的镜像。类似于Java继承一个Base基础类,自己按需创建自己的子类。新镜像就是从base基础镜像一层一层的叠加生成的,每安装一个软件就是在现有镜像的基础上增加一层。

在这里插入图片描述
基础镜像Base Image只有一层。
在这里插入图片描述

案例一: ubuntu+vim

docker run -it --name ubuntu ubuntu
# 更新ubuntu中的包管理工具
apt-get update
apt-get -y install vim

# -m:提交信息
# -a:作者
# 容器id:当前所在的容器的id
# 包名/容器名:版本号
docker commit -m="add vim cmd" -a="hh" <容器ID> huihui/myubuntu:1.0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

案例二:jdlk+tomcat

# 1. 通过ftp工具将jdk安装文件上传到linu宿主机中
jdk-8u161-linux-x64.tar.gz
apache-tomcat-7.0.47.tar.gz

# 2. 拉取一个基础镜像
docker pull centos

# 3. 运行容器,并进入容器
docker run -it --name centos centos /bin/bash

# 4.将jdk和tomcat安装文件拷贝到容器中
docker cp jdk-8u161-linux-x64.tar.gz centos:/root
docker cp apache-tomcat-7.0.47.tar.gz centos:/root

# 5.在容器中解压安装文件
tar -zxvf jdk-8u161-linux-x64.tar.gz -C /usr/local

# 6.配置环境变量
vi /etc/profile
JAVA_HOME=/usr/local/jdk1.8.0_161
export PATH=$JAVA_HOME/bin:$PATH
source /etc/profile

# 测试jdk是否安装成功
java -version
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
tar -zxvf apache-tomcat-7.0.47.tar.gz -C /usr/local

# 在setclasspath.sh配置JAVA_HOME和JRE_HOME
vim /usr/local/apache-tomcat-7.0.47/bin/setclasspath.sh
export JAVA_HOME=/usr/local/jdk1.8.0_161
export JRE_HOME=/usr/local/jdk1.8.0_161/jre
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
---
# docker commit 基础镜像名 制作的镜像名
docker commit centos mytomcat

docker images

---
# 创建容器
docker run -itd --name mytomcat -p 8888:8080 mytomcat /bin/bash

# 进入容器并执行脚本
docker exec mytomcat /usr/local/apache-tomcat-7.0.47/bin/startup.sh
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

在这里插入图片描述

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/453663
推荐阅读
相关标签
  

闽ICP备14008679号