Docker 常用命令

Docker常用的实用命令

官网命令

网址:https://docs.docker.com/engine/reference/run/

可以看到里面有所有的关于docker命令行的操作命令

帮助命令

语法:

1
docker 命令 --help

功能:帮助命令,好用的帮助查询命令。

比如我们现在想知道 docker run 里面的各项参数的含义是什么的话,那么我们可以输入以下命令:

1
docker run --help

出现以下界面则表示将所有可选项参数都给我们展示出来了,对我们后续的查询及提供帮助文档非常实用。

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
[root@localhost data]# docker run --help

Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

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

docker images

功能:列出所有镜像
命令:

1
docker images
1
2
3
4
5
6
7
8
9
[root@localhost data]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
redis 5.0 071510791e92 8 months ago 110MB
nginx latest ea335eea17ab 8 months ago 141MB
mysql 5.7 8b43c6af2ad0 8 months ago 448MB
minio/minio RELEASE.2021-06-17T00-10-46Z a1f05d5aad90 14 months ago 296MB
titpetric/netdata latest b1110f52439e 2 years ago 299MB
java 8-alpine 3fd9dd82815c 5 years ago 145MB
java 8 d23bdf5b1b1b 5 years ago 643MB

名词解释:

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

可选项参数:

1
2
3
-a	 显示所有的镜像
-q 只显示镜像的id
-aq 显示所有镜像的Id

功能:搜索镜像

命令:

1
docker search mysql
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
[root@localhost data]# docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 12999 [OK]
mariadb MariaDB Server is a high performing open sou… 4982 [OK]
phpmyadmin phpMyAdmin - A web interface for MySQL and M… 597 [OK]
percona Percona Server is a fork of the MySQL relati… 583 [OK]
bitnami/mysql Bitnami MySQL Docker Image 72 [OK]
linuxserver/mysql-workbench 41
linuxserver/mysql A Mysql container, brought to you by LinuxSe… 37
ubuntu/mysql MySQL open source fast, stable, multi-thread… 36
circleci/mysql MySQL is a widely used, open-source relation… 26
google/mysql MySQL server for Google Compute Engine 21 [OK]
rapidfort/mysql RapidFort optimized, hardened image for MySQL 13
bitnami/mysqld-exporter 3
ibmcom/mysql-s390x Docker image for mysql-s390x 2
newrelic/mysql-plugin New Relic Plugin for monitoring MySQL databa… 1 [OK]
vitess/mysqlctld vitess/mysqlctld 1 [OK]
hashicorp/mysql-portworx-demo 0
docksal/mysql MySQL service images for Docksal - https://d… 0
mirantis/mysql 0
cimg/mysql 0
drud/mysql 0
silintl/mysql-backup-restore Simple docker image to perform mysql backups… 0 [OK]
corpusops/mysql https://github.com/corpusops/docker-images/ 0
drud/mysql-local-57 ddev mysql local container 0
drud/mysql-docker-local-57 This repo has been deprecated, new tags are … 0
drud/mysql-docker-local docker containers for local womysql rk 0 [OK]

docker pull

功能:下载镜像,它采用的是分层下载

下载最新版本
命令:

1
docker pull mysql

下载指定版本
命令:

1
docker pull mysql:5.7

docker rmi -f [镜像id]

功能:删除指定镜像
图片

删除指定镜像
命令:

1
docker rmi -f 7b94cda7ffc7

删除所有镜像
命令:

1
docker rmi -f $(docker images -aq)

docker run

功能:创建并启动一个容器

下载指定镜像
命令:

1
docker pull centos

创建并启动容器
命令:

1
docker run -it centos /bin/bash

docker ps

功能:列出所有正在运行的容器

列出所有正在运行的容器
命令:

1
docker ps

列出所有的容器(正在运行的容器和历史运行过的容器)
命令:

1
docker ps -a

docker rm -f [容器id]

功能:删除指定容器

删除指定容器
命令:

1
docker rm -f 9bc74608b76e

删除所有容器
命令:

1
docker rm -f $(docker ps -aq)

docker start [容器id]

功能:启动容器
命令:

1
docker start [容器id]

docker restart [容器id]

功能:重启容器
命令:

1
docker restart [容器id]

docker stop [容器id]

功能:停止当前正在运行的容器
命令:

1
docker stop [容器id]

docker kill [容器id]

功能:强制停止当前正在运行的容器

命令:

1
docker kill [容器id]

docker logs

功能:查看容器日志

查看指定时间后的日志,只显示最后100行:

1
docker logs -f -t --since="2022-08-08" --tail=100 CONTAINER_ID

查看最近30分钟的日志:

1
docker logs --since 30m CONTAINER_ID

查看某时间之后的日志:

1
docker logs -t --since="2022-08-18T11:46:37" CONTAINER_ID

查看某时间之后最新的100条日志:

1
docker logs -t --since="2022-08-08T11:46:37" --tail=100 CONTAINER_ID

查看某时间段日志:

1
docker logs -t --since="2022-08-18T11:46:37" --until "2022-08-18T11:47:37" CONTAINER_ID

打印匹配行的前后10行

1
docker logs CONTAINER_ID | grep -C 10 'error'

把日志写入文件:

1
docker logs -t CONTAINER_ID | grep 'error' >> logs_error.txt

进入容器

功能:进入容器

进入当前容器后开启一个新的终端,可以在里面操作。(常用)

1
docker exec -it 容器id /bin/bash

进入容器正在执行某个命令的终端,不能在里面操作

1
docker attach 容器id

容器数据卷

功能:挂载数据卷

查看所有卷的情况

1
docker volume ls

查看具体的卷信息

1
docker volume inspect 容器id

-v 容器内路径 匿名挂载(只写了内部的挂载路径)

1
docker run -d -P --name nginx01 -v /etc/nginx:rw nginx

-v 卷名:容器内路径 具名挂载

1
docker run -d -P --name nginx02 -v juming-nginx:/etc/nginx:ro nginx
1
2
3
4
5
6
7
-v /宿主机路径:容器内路径  指定路径挂载



ro: 只读,只能通过宿主机改变

rw :可读可写(默认的)

所有容器内的卷,如果没有指定目录的情况下都是在/var/lib/dockervolumes/xxxx/_data

拷贝

功能:容器、宿主机文件互相拷贝

容器到宿主机

1
2
3
docker cp 容器id:要拷贝的文件在容器里面的路径 要拷贝到宿主机的相应路径

docker cp 容器id:/opt/ansible/ansible/tox.ini /root

宿主机到容器

1
2
3
docker cp 要拷贝的文件路径 容器id:要拷贝到容器里面对应的路径

docker cp rabbitmq_delayed_message_exchange-3.8.0.ez 容器id:/opt/rabbitmq/plugins

更改容器时间

功能:修改容器的时间,有的时候,我们因为一些操作导致容器内的时间和宿主机时间不一致,这个时候我们可能需要进行修改。

1、以root身份进入容器

1
docker exec -it -u root 24795ac94ae7 /bin/sh

可以使用date -R 查看时间

2、在容器中创建文件

1
mkdir -p /usr/share/zoneinfo/Asia

3、回到宿主机,复制宿主机里的文件到容器中

1
docker cp /usr/share/zoneinfo/Asia/Shanghai 容器ID或容器名:/usr/share/zoneinfo/Asia

4、进入容器

1
docker exec -it -u root 容器Id或容器名 bash

执行命令

1
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

图片

5、执行date -R 查看时区显示时间是否正确

docker内安装vim

功能:我们的docker容器内是一个小的虚拟机环境,它没有一些类似vim的命令,那我们在容器内使用这些命令的话就需要单独进行安装

第一步 配置国内镜像源
进入某个容器,例如进入mysql

1
docker exec -it mysql /bin/bash

1
2
3
4
5
mv /etc/apt/sources.list /etc/apt/sources.list.bak
echo "deb http://mirrors.163.com/debian/ jessie main non-free contrib" >> /etc/apt/sources.list
echo "deb http://mirrors.163.com/debian/ jessie-proposed-updates main non-free contrib" >>/etc/apt/sources.list
echo "deb-src http://mirrors.163.com/debian/ jessie main non-free contrib" >>/etc/apt/sources.list
echo "deb-src http://mirrors.163.com/debian/ jessie-proposed-updates main non-free contrib" >>/etc/apt/sources.list

第二步:更新源

1
apt update

第三步安装vim

1
apt-get install vim

docker打包及导出

功能:将docker镜像打包进行导入导出

1、保存正在运行的容器为镜像commit(基本不使用)

1
docker commit 容器id/容器名称

2、保存正在运行的容器为镜像压缩包import/export

1
2
docker export 容器id > redis.tar
docker import 压缩包名称 自定义镜像名称

3、保存镜像为压缩包save/load

1
2
3
docker save 镜像id/镜像名称 > 包名称
docker save -o xxx.tar 镜像id
docker load < xxx.tar

一些区别:
export导出的镜像体积要小于save(save保存更完全,export会丢掉一些不必要的数据)
save可以将多个镜像打包到同一个文件中

一辈子很短,努力的做好两件事就好;
第一件事是热爱生活,好好的去爱身边的人;
第二件事是努力学习,在工作中取得不一样的成绩,实现自己的价值,而不是仅仅为了赚钱;

继开 wechat
欢迎加我的微信,共同交流技术