帮助命令

docker version      # 显示docker的版本信息
docker info         # 显示docker的系统信息,包括镜像和容器的数量
docker 命令 --help   # 帮助命令

镜像命令

# 查看所有本地主机上的镜像
docker images 
# 搜索镜像
docker search image_name
# 下载镜像
docker pull image_name
# 删除镜像
docker rmi -f image_name[:tag]

容器命令

有了镜像才能创建容器

docker pull centos

运行容器

docker run [可选参数] image

# 参数说明
--name = "Name"    容器名字  tomcat01,tomcat02,用来区分容器
-d                 后台方式运行
-it                使用交互方式运行,进入容器查看区分
-p                 指定容器的端口 -p 8080:8080
    -p ip:主机端口:容器端口
    -p 主机端口:容器端口(常用)
    -p 容器端口
    容器端口
-p                 随机指定端口

# 测试,启动并进入容器
[root@AlibabaECS bin]# docker run -it centos /bin/bash
[root@94d468db18da /]# ls  # 主机名就是镜像id。查看容器内的centos,基础版本,很多命令都是不完善的!
bin  etc   lib    lost+found  mnt  proc  run   srv  tmp  var
dev  home  lib64  media       opt  root  sbin  sys  usr


# 从容器中退回主机
exit

列出容器

docker ps # 列出当前正在运行的容器
	-a   # 列出当前正在运行的容器+历史运行过的容器
  -n=? # 显示最近创建的容器
  -q   # 只显示容器的编号

退出容器

exit #容器停止 退出
ctrl+p+q # 容器不停止 退出

删除容器

docker rm 容器id                  # 删除指定容器,不能删除正在运行的容器,如果要强制删除 rm -f
docker rm -f $(docker ps -aq)    # 删除所有的容器
docker ps -aq|xargs docker rm    # 删除所有的容器

启动和停止容器

docker start 容器id        # 启动容器
docker restart 容器id      # 重启容器
docker stop 容器id         # 停止当前正在运行的容器
docker kill 容器id         # 强制停止当前容器

常用其他命令

后台启动容器

# 命令 docker run -d 镜像名
docker run -d centos

问题: docker ps, 发现 centos 停止了

常见的坑, docker容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止
比如, nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了

查看日志

docker logs [OPTIONS] CONTAINER

      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)

# 显示日志
-tf                # 显示日志
--tail number      # 要显示的日志条数

查看容器中的进程信息

docker top containerID

查看镜像元数据

# 命令
docker inspect containerID
# 测试 先run一个容器 再查看一下
[root@node2 ~] docker inspect 6899c57813f3
[
    {
        "Id": "6899c57813f31ad163ad8e8c73820d4f89d6272f1c01378c518e955924cba8de",
        "Created": "2020-11-23T06:06:10.016359497Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 26514,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-11-23T06:06:10.316400382Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:0d120b6ccaa8c5e149176798b3501d4dd1885f961922497cd0abef155c869566",
        "ResolvConfPath": "/var/lib/docker/containers/6899c57813f31ad163ad8e8c73820d4f89d6272f1c01378c518e955924cba8de/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/6899c57813f31ad163ad8e8c73820d4f89d6272f1c01378c518e955924cba8de/hostname",
        "HostsPath": "/var/lib/docker/containers/6899c57813f31ad163ad8e8c73820d4f89d6272f1c01378c518e955924cba8de/hosts",
        "LogPath": "/var/lib/docker/containers/6899c57813f31ad163ad8e8c73820d4f89d6272f1c01378c518e955924cba8de/6899c57813f31ad163ad8e8c73820d4f89d6272f1c01378c518e955924cba8de-json.log",
        "Name": "/naughty_turing",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/434c792d7b0b208d8ae4e9afc0afd0f1f2441c83eafc1691c6df2027fd509d2a-init/diff:/var/lib/docker/overlay2/53d85ebb1fdbf966d5dabe7382c2bfb3e3e3f048c3cc8900af158deb2f134f26/diff",
                "MergedDir": "/var/lib/docker/overlay2/434c792d7b0b208d8ae4e9afc0afd0f1f2441c83eafc1691c6df2027fd509d2a/merged",
                "UpperDir": "/var/lib/docker/overlay2/434c792d7b0b208d8ae4e9afc0afd0f1f2441c83eafc1691c6df2027fd509d2a/diff",
                "WorkDir": "/var/lib/docker/overlay2/434c792d7b0b208d8ae4e9afc0afd0f1f2441c83eafc1691c6df2027fd509d2a/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "6899c57813f3",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20200809",
                "org.label-schema.license": "GPLv2",
                "": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "9d565c6018f50aa3fbd72e216f5bb76bc63634d6ecfafa3d1fa71d591185fcf1",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/9d565c6018f5",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "ee86a6096a693659c2119f4ba817d57bafea9c2ac520b6c2654f53aedda19836",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "3421e308d805bb9d0cb7d2a8df954e836c187715743ba002e20f699acf9ef8bb",
                    "EndpointID": "ee86a6096a693659c2119f4ba817d57bafea9c2ac520b6c2654f53aedda19836",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

进入当前正在运行的容器

# 我们通常都是使用后台方式运行的,需要进入容器,修改一些配置

# 命令
docker exec -it 容器id baseShell
或者
docker attach 容器id

# docker exec        # 进入容器后开启一个新的终端,可以在里面操作(常用)
# docker attach      # 进入容器正在执行的终端,不会启动新的进程

从容器内拷贝到主机上

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

dockers容器如何查端口是否开放了 查看docker端口号_centos

attach      Attach local standard input, output, and error streams to a running container
  #当前shell下 attach连接指定运行的镜像
  build       Build an image from a Dockerfile # 通过Dockerfile定制镜像
  commit      Create a new image from a container's changes #提交当前容器为新的镜像
  cp          Copy files/folders between a container and the local filesystem #拷贝文件
  create      Create a new container #创建一个新的容器
  diff        Inspect changes to files or directories on a container's filesystem #查看docker容器的变化
  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 #导出容器文件系统作为一个tar归档文件[对应import]
  history     Show the history of an image # 展示一个镜像形成历史
  images      List images #列出系统当前的镜像
  import      Import the contents from a tarball to create a filesystem image #从tar包中导入内容创建一个文件系统镜像
  info        Display system-wide information # 显示全系统信息
  inspect     Return low-level information on Docker objects #查看容器详细信息
  kill        Kill one or more running containers # kill指定docker容器
  load        Load an image from a tar archive or STDIN #从一个tar包或标准输入中加载一个镜像[对应save]
  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