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

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.
➜  ~ 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 [])

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]

Docker Hub ( https://hub.docker.com/ ) Docker官方仓库,用于搜索仓库中的镜像,以及查看镜像中的具体使用文档等,也可以将自己的镜像推送到官方仓库中。
Docker(二):Docker常用命令-LMLPHP

docker login

登录docker仓库。

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

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

docker images

# 查看本地所有镜像列表。
➜  ~ 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

docker rmi

删除镜像,-f : 表示强制force删除,默认只能删除未使用的,删除时可以使用容器名:标签,也可以使用容器的id。

➜  ~ docker rmi -f  openjdk:11
➜  ~ docker rmi openjdk:11
Untagged: openjdk:11
Untagged: openjdk@sha256:99bac5bf83633e3c7399aed725c8415e7b569b54e03e4599e580fc9cdb7c21ab
Deleted: sha256:47a932d998b743b9b0bcce55aa8ede77de94a6a183c8a67dec9d5e3b8ce0faa7
Deleted: sha256:a99b7985263322d8e9da8c89f2f57b2e703cc2f8ad8ea87fb0ee402bb6162b78
Deleted: sha256:f751ef4f6907367707782910911112642b84b2d01ac8003d7c13fe8d76b5ae3d
Deleted: sha256:e7dd29f3ffa73e8d8d9ccb88f1507bb35fe14749d2f5a7c1a44b33ea62a13a1b
Deleted: sha256:1376fe23991c7bd9ac29c2469f6489e5e68b2311f78191e87c47acd67e846372
Deleted: sha256:935ab298b59cf4955c8a62f40960766ceedee432fde87f22a71d557be7e05d0a
Deleted: sha256:6fa094ba2e6e15e0fab64e7d1372945f05e70ed3bdf6fd90409153d7ec19d160
Deleted: sha256:9c742cd6c7a5752ee36be8ecb14be45c0885e10e6dd34f26a9ae3eb096c5d492

docker save & docker load

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

# -o:output
➜  ~ docker save -o openjdk11.tar  openjdk:11
➜  ~ docker rmi openjdk:11
Untagged: openjdk:11
Untagged: openjdk@sha256:99bac5bf83633e3c7399aed725c8415e7b569b54e03e4599e580fc9cdb7c21ab
Deleted: sha256:47a932d998b743b9b0bcce55aa8ede77de94a6a183c8a67dec9d5e3b8ce0faa7
Deleted: sha256:a99b7985263322d8e9da8c89f2f57b2e703cc2f8ad8ea87fb0ee402bb6162b78
Deleted: sha256:f751ef4f6907367707782910911112642b84b2d01ac8003d7c13fe8d76b5ae3d
Deleted: sha256:e7dd29f3ffa73e8d8d9ccb88f1507bb35fe14749d2f5a7c1a44b33ea62a13a1b
Deleted: sha256:1376fe23991c7bd9ac29c2469f6489e5e68b2311f78191e87c47acd67e846372
Deleted: sha256:935ab298b59cf4955c8a62f40960766ceedee432fde87f22a71d557be7e05d0a
Deleted: sha256:6fa094ba2e6e15e0fab64e7d1372945f05e70ed3bdf6fd90409153d7ec19d160
Deleted: sha256:9c742cd6c7a5752ee36be8ecb14be45c0885e10e6dd34f26a9ae3eb096c5d492
➜  ~ 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

docker volume

volume 数据卷,用于宿主机目录和容器中的目录的双向绑定互相映射用的。映射后,可以直接在宿主机上修改容器上的文件,同样在容器中修改文件也会同步修改宿主机上。

数据卷挂载的好处:

  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
➜  ~ 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

docker run

docker run :如果镜像不存在先下载镜像并运行镜像,注意:每次运行都会创建一个新的容器。

# -i: 创建一个交互式容器
# -t: --tty tty终端(分配一个终端来操作容器)
# -d: --detach 后台运行
# --name: 容器名称(唯一)
# -p: port 端口映射 宿主机端口:容器端口
# -v:volume, 数据卷目录映射双向绑定,可以使用数据卷名映射容器目录,也可以直接使用将宿主机目录映射到容器目录(宿主机目录必须以/或者./开头)
# -e:environment 环境参数,镜像内部需要使用到的参数
# 如果省略tag默认为latest,如果拉取的镜像是指定版本的,这里要显式指定版本号

# 创建交互式容器
docker run -itd \
	--name <container name>  \
	-p 宿主机端口:容器端口 \
	-e 环境变量名=\
	-v 宿主机目录:容器目录 \
	<image name[:tag]>
# 关于mysql的所有配置都可以在Docker Hub上查到
➜  ~ docker run -d \
        --name mysql \
        -p 3307:3306 \
        -e TZ=Asia/Shanghai \
        -e MYSQL_ROOT_PASSWORD=123456 \
        -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
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

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"
        }
    }
]


# 查看容器的ip地址属性,docker的ip为172.17.0.1,其它容器的依次是172.17.0.2递增
docker inspect -f='{{.NetworkSettings.IPAddress}}' container_name/container_id

docker network

查看Docker的IP。

yum install net-tools -y
ifconfig

Docker(二):Docker常用命令-LMLPHP

Docker在安装的是会创建一个docker0网卡,每个容器都有自己的IP地址,默认情况下所有容器都是以bridge的方式连接到Docker的一个虚拟网桥上 172.17.0.1/16, /16表示IP前两段是固定的,只有后两段式可以变的,在同一个网段的容器之间时可以互相访问的,但是容器的IP地址会变的,通过容器的IP地址访问不可靠,可以通过自定义网络,自定义网络可以通过容器名来互相访问。

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

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

# 创建一个网络
docker network create <网络名>

# 删除某个自定义网络
docker network rm <网络名>
# 删除所有未使用的网络
docker network prune
➜  ~ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f18b70eee01c        bridge              bridge              local
bcb18ec1867c        host                host                local
75d5d48759de        none                null                local
➜  ~
➜  ~ docker network inspect bridge
[
    {
        "Name": "bridge",
        "Id": "f18b70eee01cbc5d52dd1d29d082c566b78b8da4292db3f89fe348a02891680c",
        "Created": "2024-03-23T04:32:41.393581303Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "ab9f14e882ff74a2de99fa979fb09f20f31cc0808b700c894bc7c6a705380349": {
                "Name": "mysql",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    },
    "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

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

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

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

# -f指定格式
docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Ports}}\t{{.Status}}\t{{.Names}}"

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

docker rm

删除容器。

➜  ~ docker rm mysql
mysql


# 删除所有停止的容器
# -a: all 显示所有容器
# -q: quiet 只显式容器id这列的值
docker rm $(docker ps -a -q)

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

# 运行时指定容器
➜  ~ 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


➜  ~ 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"
                }
            }
        }
	}
]

docker network connect & docker network disconnect

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


# 断开某个网络
docker network disconnect <网络名> <容器名>

docker exec & exit

docker exec 进入容器执行和容器相关的命令。

# 进入镜像
docker exec -it <image_name> /bin/bash
docker exec -it <image_name> bash
# 可以直接跟bash的命令
docker exec -it <image_name> 应用命令
docker exec -it mysql mysql -root -p
# 交互式容器:exit会停止运行容器
# 守护式容器:exit会退出容器,并不会停止运行容器
exit
# 进入容器,@后面是容器的id
➜  ~ 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

➜  ~

docker cp

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

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

docker logs

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

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

docker build

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

docker tag

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

docker push

将镜像推送到远程仓库。

docker push <用户名>/<仓库名>:<Tag>
03-24 22:25