1、帮助启动类命令(CentOS)

启动docker

systemctl start docker

停止docker

systemctl stop docker

重启docker

  1. systemctl restart docker

查看docker状态

systemctl status docker

开机启动

systemctl enable docker

查看docker概要信息

docker info

查看docker总体帮助文档

docker —help

查看docker命令帮助文档

docker 具体命令 —help

2、镜像命令

列出本机上的镜像:docker images

REPOSITORY :镜像仓库源
TAG : 镜像标签
IMAGE ID : 镜像id
CREATED : 镜像创建时间
SIZE : 镜像大小
-a, —all Show all images (default hides intermediate images)
—digests Show digests
-f, —filter filter Filter output based on conditions provided
—format string Pretty-print images using a Go template
—no-trunc Don’t truncate output
-q, —quiet Only show image IDs

查找某个镜像:docker search xxx

NAME : 镜像mingc
DESCRIPTION : 镜像说明
STARS : 点赞数
OFFICIAL : 是否官方的
AUTOMATED : 是否自动构建

-f, —filter filter Filter output based on conditions provided
—format string Pretty-print search using a Go template
—limit int Max number of search results (default 25)
—no-trunc Don’t truncate output
例:
docker search redis —limit 10

拉取某个镜像 :docker pull xxx

-a, —all-tags Download all tagged images in the repository
—disable-content-trust Skip image verification (default true)
—platform string Set platform if server is multi-platform capable
-q, —quiet Suppress verbose output
拉取指定TAG的镜像
docker pull redis:6.2.6
-a 显示所有的,-q 只显示镜像id

查看所有镜像/容器/数据卷所占的空间: docker system df

image.png
df -h :查看Linux系统所用空间

删除某个镜像名字id: docker rmi xxx

Options:
-f, —force Force removal of the image
—no-prune Do not delete untagged parents

docker rmi hello-world:latest

Error response from daemon: conflict: unable to remove repository reference “hello-world” (must force) - container 3320317460ce is using its referenced image feb5d9fea6a5

需要 强制删除
docker rmi -f hello-world:latest

删除单个 镜像
docker rmi -f hello-world:latest

删除多个
docker rmi -f hello-world:latest redis:6.2.6

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

查询所有的docker 镜像 的id
docker images -qa

面试题: 谈谈docker 虚悬镜像是什么?

是什么

仓库名、标签都是的镜像,俗称虚悬镜像 dangling image

长什么样

image.png

3、容器命令

下载CentOS或ubuntu镜像演示

image.png
docker pull ubuntu

新建+启动容器

docker run [OPTIONS] IMAGE [COMMAND][ARG …]

Options:

  --add-host list                  Add a custom host-to-IP mapping (host:ip)<br />  -a, --attach list                    Attach to STDIN, STDOUT or STDERR<br />      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)<br />      --blkio-weight-device list       Block IO weight (relative device weight) (default [])<br />      --cap-add list                   Add Linux capabilities<br />      --cap-drop list                  Drop Linux capabilities<br />      --cgroup-parent string           Optional parent cgroup for the container<br />      --cgroupns string                Cgroup namespace to use (host|private)<br />                                       'host':    Run the container in the Docker host's cgroup namespace<br />                                       'private': Run the container in its own private cgroup namespace<br />                                       '':        Use the cgroup namespace as configured by the<br />                                                  default-cgroupns-mode option on the daemon (default)<br />      --cidfile string                 Write the container ID to the file<br />      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period<br />      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota<br />      --cpu-rt-period int              Limit CPU real-time period in microseconds<br />      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds<br />  -c, --cpu-shares int                 CPU shares (relative weight)<br />      --cpus decimal                   Number of CPUs<br />      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)<br />      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)<br />  -d, --detach                         Run container in background and print container ID<br />      --detach-keys string             Override the key sequence for detaching a container<br />      --device list                    Add a host device to the container<br />      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list<br />      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])<br />      --device-read-iops list          Limit read rate (IO per second) from a device (default [])<br />      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])<br />      --device-write-iops list         Limit write rate (IO per second) to a device (default [])<br />      --disable-content-trust          Skip image verification (default true)<br />      --dns list                       Set custom DNS servers<br />      --dns-option list                Set DNS options<br />      --dns-search list                Set custom DNS search domains<br />      --domainname string              Container NIS domain name<br />      --entrypoint string              Overwrite the default ENTRYPOINT of the image<br />  -e, --env list                       Set environment variables<br />      --env-file list                  Read in a file of environment variables<br />      --expose list                    Expose a port or a range of ports<br />      --gpus gpu-request               GPU devices to add to the container ('all' to pass all GPUs)<br />      --group-add list                 Add additional groups to join<br />      --health-cmd string              Command to run to check health<br />      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)<br />      --health-retries int             Consecutive failures needed to report unhealthy<br />      --health-start-period duration   Start period for the container to initialize before starting health-retries<br />                                       countdown (ms|s|m|h) (default 0s)<br />      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)<br />      --help                           Print usage<br />  -h, --hostname string                Container host name<br />      --init                           Run an init inside the container that forwards signals and reaps processes<br />  -i, --interactive                    Keep STDIN open even if not attached<br />      --ip string                      IPv4 address (e.g., 172.30.100.104)<br />      --ip6 string                     IPv6 address (e.g., 2001:db8::33)<br />      --ipc string                     IPC mode to use<br />      --isolation string               Container isolation technology<br />      --kernel-memory bytes            Kernel memory limit<br />  -l, --label list                     Set meta data on a container<br />      --label-file list                Read in a line delimited file of labels<br />      --link list                      Add link to another container<br />      --link-local-ip list             Container IPv4/IPv6 link-local addresses<br />      --log-driver string              Logging driver for the container<br />      --log-opt list                   Log driver options<br />      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)<br />  -m, --memory bytes                   Memory limit<br />      --memory-reservation bytes       Memory soft limit<br />      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap<br />      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)<br />      --mount mount                    Attach a filesystem mount to the container<br />      --name string                    Assign a name to the container<br />      --network network                Connect a container to a network<br />      --network-alias list             Add network-scoped alias for the container<br />      --no-healthcheck                 Disable any container-specified HEALTHCHECK<br />      --oom-kill-disable               Disable OOM Killer<br />      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)<br />      --pid string                     PID namespace to use<br />      --pids-limit int                 Tune container pids limit (set -1 for unlimited)<br />      --platform string                Set platform if server is multi-platform capable<br />      --privileged                     Give extended privileges to this container<br />  -p, --publish list                   Publish a container's port(s) to the host<br />  -P, --publish-all                    Publish all exposed ports to random ports<br />      --pull string                    Pull image before running ("always"|"missing"|"never") (default "missing")<br />      --read-only                      Mount the container's root filesystem as read only<br />      --restart string                 Restart policy to apply when a container exits (default "no")<br />      --rm                             Automatically remove the container when it exits<br />      --runtime string                 Runtime to use for this container<br />      --security-opt list              Security Options<br />      --shm-size bytes                 Size of /dev/shm<br />      --sig-proxy                      Proxy received signals to the process (default true)<br />      --stop-signal string             Signal to stop a container (default "SIGTERM")<br />      --stop-timeout int               Timeout (in seconds) to stop a container<br />      --storage-opt list               Storage driver options for the container<br />      --sysctl map                     Sysctl options (default map[])<br />      --tmpfs list                     Mount a tmpfs directory<br />  -t, --tty                            Allocate a pseudo-TTY<br />      --ulimit ulimit                  Ulimit options (default [])<br />  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])<br />      --userns string                  User namespace to use<br />      --uts string                     UTS namespace to use<br />  -v, --volume list                    Bind mount a volume<br />      --volume-driver string           Optional volume driver for the container<br />      --volumes-from list              Mount volumes from the specified container(s)<br />  -w, --workdir string                 Working directory inside the container

常用参数

—name=”容器新名字” 为容器指定一个名称
-d :后台运行容器并返回容器 ID, 及 启动守护式容器(后台运行)
-i : 以交互模式运行容器 通常与 -t 同时使用 interactive
-t :为容器重新分配一个伪输入终端, 通常与 -i 同时使用 tyy

-P : 随机端口映射 ,大写P
-p:指定端口映射 , 小写p

启动交互式容器(前台命令行)

例:

docker run -it ubuntu /bin/bash

docker run -it --name=ubu1 ubuntu

列出当前所有正在运行的容器

docker ps
显示所有的容器
-a, —all Show all containers (default shows just running)
-f, —filter filter Filter output based on conditions provided
—format string Pretty-print containers using a Go template
显示最近创建的个容器
-n, —last int Show n last created containers (includes all states) (default -1)
显示最近创建的容器
-l, —latest Show the latest created container (includes all states)
—no-trunc Don’t truncate output

-q, —quiet Only display container IDs
-s, —size Display total file sizes

退出容器

exit 退出,run进去容器,exit 退出, 容器停止
ctrl+p+q run进去容器,ctrl+p+q 退出,容器不停止

启动已停止运行的容器

docker start 容器ID 或者容器名

重启容器

docker restart 容器ID 或者容器名

停止容器

docker stop 容器ID 或者容器名

强制停止容器

docker kill 容器ID 或者容器名

删除已停止的容器

docker rm 容器id

Error response from daemon: You cannot remove a running container 3f39aa2c63957b01e12feb50b8e01f678be9f5405feff34839ae007de4f1476d. Stop the container before attempting removal or force remove
提示:优先暂停容器

强制删除
docker rm -f 容器id

删除多个容器 警告生产禁止使用
docker rm -f $(docker ps -a -q)
docker ps -a -q | xargs docker rm

重要

启动守护式容器(后台服务器)

使用 : docker run -d 容器名
前台交互式启动
docker run -it redis:6.2.6
后台交互式启动
docker run -d redis:6.2.6

查看容器日志

docker logs xxx容器id

Options:
—details Show extra details provided to logs
-f, —follow Follow log output
—since string Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
-n, —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:37Z) or relative (e.g. 42m for 42 minutes)

查看容器内运行的进程

docker top xxx 容器id

查看容器内部细节

docker inspect 容器
Options:
-f, —format string Format the output using the given Go template
-s, —size Display total file sizes if the type is container
—type string Return JSON for specified type

进入正在运行的容器并以命令行交互

docker exec -it 容器id /bin/bash

Options:
-d, —detach Detached mode: run command in the background
—detach-keys string Override the key sequence for detaching a container
-e, —env list Set environment variables
—env-file list Read in a file of environment variables
-i, —interactive Keep STDIN open even if not attached
—privileged Give extended privileges to the command
-t, —tty Allocate a pseudo-TTY
-u, —user string Username or UID (format: [:])
-w, —workdir string Working directory inside the container

重新进入docker attach 容器ID

Options:
—detach-keys string Override the key sequence for detaching a container
—no-stdin Do not attach STDIN
—sig-proxy Proxy all received signals to the process (default true)

上述两个区别

attach 直接进入容器启动命令的终端,不会启动新的进程,用exit退出,会导致容器的停止
exec 是在容器中打开新的终端,并且可以启动新的进程,用exit 退出,不会导致容器的停止

推荐使用docker exec 命令 ,因为退出容器终端,不会导致容器的停止

从容器拷贝文件到主机上

docker cp 容器ID:容器内路径 目的主机路径
Options:
-a, —archive Archive mode (copy all uid/gid information)
-L, —follow-link Always follow symbol link in SRC_PATH

image.png
docker exec -it ubu1 /bin/bash
touch test.txt
docker cp 6a8c60b2a48f:/tmp/test.txt /tmp

导入和导出容器

export 导出容器的内容留作为一个tar归档文件

导入到是当前目录
docker export 容器id > 文件名.tar

docker export 6a8c60b2a48f > ubu1.tar

import 从tar包中的内容创建一个新的文件系统再导入为镜像

cat 文件名.tar | docker import - 镜像用户/镜像名:镜像版本号

cat ubu1.tar | docker import -wujing/ubu:1.0

image.png
docker run -it d301da508cc8 /bin/bash

image.png

4、小总结