目 录CONTENT

文章目录

Docker 入门系列(5)- Docker 容器基础操作

ZERO
2022-06-18 / 0 评论 / 0 点赞 / 45 阅读 / 0 字

文章转载自https://www.skynemo.cn/archives/05-dokcer-container-basic

本文中所有描述均以 Docker version 20.10.x 为基准

容器

容器生命周期

Untitled

Docker 容器主要可以分为以下状态

  • created:容器已经创建但尚未运行(较少使用,一般会使用 docker run 直接创建并运行)
  • running:容器处于运行状态
  • paused:容器处于暂停状态
  • stopped:容器已停止,可以使用 docker start 继续运行
  • deleted:容器已删除

帮助文档

Docker 提供了官方文档的镜像,可以在本地运行 docker 文档容器,方便检索

docker run -it -d --restart always -p 4000:4000 docs/docker.github.io:latest

容器管理

docker 命令官方详解:https://docs.docker.com/engine/reference/commandline/cli/

注:docker 容器管理命令大多拥有两种书写格式,例如:docker container rundocker run 两个命令并无实质区别

创建并启动容器

docker run 可以创建、启动、进入到容器,并随机生成容器ID和名称;相当于 docker createdocker start 的结合

root@docker:~# docker run --help
Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
# 或
root@docker:~# docker container run --help
Usage:  docker container run [OPTIONS] IMAGE [COMMAND] [ARG...]

# 常用选项
-i, --interactive			# 保持标准输入
-t, --tty				# 创建一个 tty,通常与 -i 一起使用;容器需要运行 shell 才能进入
-d, --detach				# 在后台运行容器,并打印容器 ID(默认为前台运行)

--name string				# 给容器分配一个名称
-h, --hostname string			# 配置容器的主机名
--rm					# 当容器退出时自动删除,常用于测试

-p, --publish list			# 将容器的端口映射到宿主机,示例-映射容器 80 端口: -p 8099:80
-P, --publish-all			# 将容器的所有公开端口随机映射到主机上

--dns list				# 设置容器的 DNS 服务器地址

--entrypoint string			# 指定镜像的默认入口命令,该入口命令会在启动容器时作为根命令执行,所有其他传入值作为该命令的参数

-e, --env list				# 设置容器的环境变量
--env-file list				# 指定一个文件作为容器的环境变量

--privileged				# 使容器扩展宿主机的用户权限

--restart policy			# 根据 policy 决定是否在容器退出时重启容器
	no					# 默认 policy,容器退出时不会自动重启
	on-failure[:max-retries]		# 容器退出状态为非0时重启容器,可设置尝试重启次数
	always					# 不管容器的退出状态,都会重启容器,常用于设置容器开机启动
	unless-stopped				# 除了正常 stop 以外,不管容器的退出状态,都会重启容器

示例一-运行容器

# 运行容器
root@docker:~# docker run alpine

# 查看所有容器(包括已停止)
root@docker:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND     CREATED         STATUS                     PORTS     NAMES
f65beccbe2e8   alpine    "/bin/sh"   5 seconds ago   Exited (0) 5 seconds ago             priceless_hamilton

示例二-交互式运行容器

root@docker:~# docker run -it busybox sh
/ # echo 'hello'
hello
/ # exit

示例三-一次性运行容器

# 退出容器时会自动删除
root@docker:~# docker run --rm alpine hostname
9b518421318c

示例四-启动后台守护式容器

# 使用 -d 选项配置后台启动
root@docker:~# docker run -d --name nginx -p 80:80 nginx:latest
5c7887dab84f2e192a27e12ab0b4eb1d37231b03bfae2f10571fc21b4e11cc79

# 查看运行中的容器
root@docker:~# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                      NAMES
5c7887dab84f   nginx:latest   "/docker-entrypoint.…"   11 seconds ago   Up 11 seconds   192.168.1.201:80->80/tcp   nginx

示例五-开机自动运行容器

# 使用 --restart=always 配置容器总是运行
root@ubuntu-20:~# docker run -d --name nginx_daemon --restart=always -p 8080:80 nginx
a79804338708138ce0d660b62f0f67355f920b6e7bd2200a7e257c03c47de947

root@ubuntu-20:~# reboot

root@ubuntu-20:~# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                                   NAMES
a79804338708   nginx     "/docker-entrypoint.…"   42 seconds ago   Up 13 seconds   0.0.0.0:8080->80/tcp, :::8080->80/tcp   nginx_daemon

从容器内退出

退出并停止容器

exit

退出但不停止容器

同时按住 ctrl + p + q

查看容器

查看容器列表

命令格式

root@docker:~# docker ps --help
Usage:  docker ps [OPTIONS]
# 或
root@docker:~# docker container ls --help
Usage:  docker container ls [OPTIONS]

List containers

Options:
  -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

示例一-显示容器

# 显示运行中的容器
docker ps

# 显示全部容器,包括已停止的
docker ps -a

# 只显示容器 ID
docker ps -q

# 显示容器大小
docker ps -s

# 显示最新创建的的容器
docker ps -l

示例二-显示并过滤容器

# 过滤名称包含nginx,状态为running的容器
root@docker:~# docker ps -f 'status=running' -f 'name=nginx'
CONTAINER ID   IMAGE     COMMAND                  CREATED        STATUS        PORTS                                   NAMES
a79804338708   nginx     "/docker-entrypoint.…"   15 hours ago   Up 15 hours   0.0.0.0:8080->80/tcp, :::8080->80/tcp   nginx_daemon

可过滤参数如下

Filter Description
id Container’s ID
name Container’s name
label An arbitrary string representing either a key or a key-value pair. Expressed as <key> or <key>=<value>
exited An integer representing the container’s exit code. Only useful with --all.
status One of created, restarting, running, removing, paused, exited, or dead
ancestor Filters containers which share a given image as an ancestor. Expressed as <image-name>[:<tag>], image id , or dead
before or since Filters containers created before or after a given container ID or name
volume Filters running containers which have mounted a given volume or bind mount.
network Filters running containers connected to a given network.
publish or expose Filters containers which publish or expose a given port. Expressed as <port>[/proto] or <startport-endport>/[<proto>]
health Filters containers based on their healthcheck status. One of starting, healthy, unhealthy or none.
isolation Windows daemon only. One of default, process, or hyperv.
is-task Filters containers that are a “task” for a service. Boolean option (true or false)

查看容器中的进程

命令格式

root@docker:~# docker top --help
Usage:  docker top CONTAINER [ps OPTIONS]
# 或
root@docker:~# docker container top --help
Usage:  docker container top CONTAINER [ps OPTIONS]

Display the running processes of a container

示例-查看容器中的进程

# 获取容器 ID
root@docker:~# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS                      NAMES
5c7887dab84f   nginx:latest   "/docker-entrypoint.…"   5 minutes ago   Up 5 minutes   192.168.1.201:80->80/tcp   nginx

# 使用容器 ID 查看容器内进程
root@docker:~# docker top 5c7887dab84f
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                9648                9626                0                   04:48               ?                   00:00:00            nginx: master process nginx -g daemon off;
systemd+            9711                9648                0                   04:48               ?                   00:00:00            nginx: worker process
systemd+            9712                9648                0                   04:48               ?                   00:00:00            nginx: worker process

查看容器资源使用情况

命令格式

root@docker:~# docker stats --help
Usage:  docker stats [OPTIONS] [CONTAINER...]
# 或
root@docker:~# docker container stats --help
Usage:  docker container stats [OPTIONS] [CONTAINER...]

Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Pretty-print images using a Go template
      --no-stream       Disable streaming stats and only pull the first result
      --no-trunc        Do not truncate output

示例一-实时显示容器资源情况

# 获取容器 ID
root@docker:~# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED        STATUS        PORTS                      NAMES
5c7887dab84f   nginx:latest   "/docker-entrypoint.…"   22 hours ago   Up 22 hours   192.168.1.201:80->80/tcp   nginx

# 实时显示资源占用
root@ubuntu-20:~# docker stats 5c7887dab84f
CONTAINER ID   NAME      CPU %     MEM USAGE / LIMIT     MEM %     NET I/O       BLOCK I/O         PIDS
5c7887dab84f   nginx     0.00%     6.668MiB / 1.907GiB   0.34%     2.67kB / 0B   20.2MB / 16.4kB   3

示例二-非实时显示容器资源情况

root@docker:~# docker stats --no-stream 5c7887dab84f
CONTAINER ID   NAME      CPU %     MEM USAGE / LIMIT     MEM %     NET I/O       BLOCK I/O         PIDS
5c7887dab84f   nginx     0.00%     6.668MiB / 1.907GiB   0.34%     2.74kB / 0B   20.2MB / 16.4kB   3

查看容器信息

命令格式

#####  docker inspect   #####
# docker inspect 命令不仅适用于容器,还可以用于镜像等 docker 对象
root@docker:~# docker inspect --help
Usage:  docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Return low-level information on Docker objects

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 container inspect   #####
# docker container inspect 命令只适用于容器
root@docker:~# docker container inspect --help

Usage:  docker container inspect [OPTIONS] CONTAINER [CONTAINER...]

Display detailed information on one or more containers

Options:
  -f, --format string   Format the output using the given Go template
  -s, --size            Display total file sizes

示例一-查看容器全部信息

root@ubuntu-20:~# docker container inspect 5c7887dab84f
[
    {
        "Id": "a79804338708138ce0d660b62f0f67355f920b6e7bd2200a7e257c03c47de947",
        "Created": "2022-01-18T17:04:46.261612312Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
.......

示例二-选择查看容器部分信息

# 双大括号包含需要解析的 JSON 数据的 key

root@docker:~# docker inspect -f "{{.Created}}" 5c7887dab84f
2022-04-27T20:48:10.005730455Z

root@docker:~# docker inspect -f "{{.State.Status}}" 5c7887dab84f
running

root@docker:~# docker inspect -f "{{.Id}}---{{.State.Status}}" 5c7887dab84f
5c7887dab84f2e192a27e12ab0b4eb1d37231b03bfae2f10571fc21b4e11cc79---running

docker rmdocker container rm

docker rmdocker container rm 可以删除正在运行中的容器

格式

root@docker:~# docker rm --help
Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]
# 或
root@docker:~# docker container rm --help
Usage:  docker container rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers

Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)
  -l, --link      Remove the specified link
  -v, --volumes   Remove anonymous volumes associated with the container

示例-删除指定状态的容器

# 过滤指定状态的容器ID
root@docker:~# docker ps -q -f status=exited
594f6dc9c06f
507452e774d7

# 删除
root@docker:~# docker rm `docker ps -q -f status=exited`
594f6dc9c06f
507452e774d7

docker container prune

docker container prune 用于删除已停止的容器

root@ubuntu-20:~# docker container prune --help
Usage:  docker container prune [OPTIONS]

Remove all stopped containers

Options:
      --filter filter   Provide filter values (e.g. 'until=<timestamp>')
  -f, --force           Do not prompt for confirmation

示例-删除所有停止的容器

root@docker:~# docker container prune -f
Deleted Containers:
6cc3cb27ea8a78e332d1c78628cc48f2f07a814125708dfa27e1e59477cbe220

Total reclaimed space: 0B

容器状态控制(启动、停止、暂停、重启)

启动容器

启动处于 created 或者 stopped 状态的容器,进入 running 状态

命令格式

root@docker:~# docker start --help
Usage:  docker start [OPTIONS] CONTAINER [CONTAINER...]
# 或
root@docker:~# docker container start --help
Usage:  docker container start [OPTIONS] CONTAINER [CONTAINER...]

Start one or more stopped containers

Options:
  -a, --attach               Attach STDOUT/STDERR and forward signals
      --detach-keys string   Override the key sequence for detaching a container
  -i, --interactive          Attach container's STDIN

停止容器

停止处于 running 状态的容器,进入 stopped 状态

命令格式

root@docker:~# docker stop --help
Usage:  docker stop [OPTIONS] CONTAINER [CONTAINER...]
# 或
root@docker:~# docker container stop --help
Usage:  docker container stop [OPTIONS] CONTAINER [CONTAINER...]

Stop one or more running containers

Options:
  -t, --time int   Seconds to wait for stop before killing it (default 10)

常用命令

# 批量正常启动或关闭所有容器
docker start `docker ps -a -q`
docker stop `docker ps -a -q`

重启容器

命令格式

root@docker:~# docker restart --help
Usage:  docker restart [OPTIONS] CONTAINER [CONTAINER...]
# 或
root@docker:~# docker container restart --help
Usage:  docker container restart [OPTIONS] CONTAINER [CONTAINER...]

Restart one or more containers

Options:
  -t, --time int   Seconds to wait for stop before killing the container (default 10)

暂停容器

暂停处于 running 状态的容器,进入 paused 状态

root@docker:~# docker pause --help
Usage:  docker pause CONTAINER [CONTAINER...]
# 或
root@docker:~# docker container pause --help
Usage:  docker container pause CONTAINER [CONTAINER...]

Pause all processes within one or more containers

恢复暂停

恢复暂停后处于 paused 状态的容器,重新进入 running 状态

root@docker:~# docker unpause --help
Usage:  docker unpause CONTAINER [CONTAINER...]
# 或
root@docker:~# docker container unpause --help
Usage:  docker container unpause CONTAINER [CONTAINER...]

Unpause all processes within one or more containers

给运行中容器发信号

docker kill 可以给容器发信号,默认为 KILL,即 9 信号停止容器

命令格式

root@docker:~# docker kill --help
Usage:  docker kill [OPTIONS] CONTAINER [CONTAINER...]
# 或
root@docker:~# docker container kill --help
Usage:  docker container kill [OPTIONS] CONTAINER [CONTAINER...]

Kill one or more running containers

Options:
  -s, --signal string   Signal to send to the container (default "KILL")

进入运行中的容器

attach(不推荐)

dcoker attachdocker container attach 的操作会在同一个容器的多个会话同步显示(类似于VNC远程桌面),使用 exit 退出后,容器会关闭,因此不推荐使用

命令格式

root@docker:~# docker attach --help
Usage:  docker attach [OPTIONS] CONTAINER
# 或
root@docker:~# docker container attach --help
Usage:  docker container attach [OPTIONS] CONTAINER

Attach local standard input, output, and error streams to a running container

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)

示例-进入运行中的容器

# 列出容器 ID 为 9e8d1fd0f0ab 的容器
root@docker:~# docker 列出 -f 'id=9e8d1fd0f0ab 的容器'
CONTAINER ID   IMAGE           COMMAND   CREATED         STATUS         PORTS     NAMES
9e8d1fd0f0ab   alpine:latest   "sh"      2 minutes ago   Up 2 minutes             silly_edison

# 进入容器
root@docker:~# docker attach 9e8d1fd0f0ab

exec(推荐)

docker execdocker container exec 可以进入容器,甚至可以执行单次命令,其进入容器是在一个新的独立的会话中

命令格式

root@docker:~# docker exec --help
Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
# 或
root@docker:~# docker container exec --help
Usage:  docker container exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

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: <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container

常见用法

docker exec -it 容器ID sh|bash

示例一-进入容器

root@docker:~# docker exec -it d593134af6c2 sh
/ #

nsenter

nsenter 命令需要通过PID进入到容器内部,该工具来自于 util-linux 包,需要容器有 bash 环境

安装

root@docker:~# apt install -y util-linux

命令帮助

root@docker:~# nsenter --help

Usage:
 nsenter [options] [<program> [<argument>...]]

Run a program with namespaces of other processes.

Options:
 -a, --all              enter all namespaces
 -t, --target <pid>     target process to get namespaces from
 -m, --mount[=<file>]   enter mount namespace
 -u, --uts[=<file>]     enter UTS namespace (hostname etc)
 -i, --ipc[=<file>]     enter System V IPC namespace
 -n, --net[=<file>]     enter network namespace
 -p, --pid[=<file>]     enter pid namespace
 -C, --cgroup[=<file>]  enter cgroup namespace
 -U, --user[=<file>]    enter user namespace
 -S, --setuid <uid>     set uid in entered namespace
 -G, --setgid <gid>     set gid in entered namespace
     --preserve-credentials do not touch uids or gids
 -r, --root[=<dir>]     set the root directory
 -w, --wd[=<dir>]       set the working directory
 -F, --no-fork          do not fork before exec'ing <program>
 -Z, --follow-context   set SELinux context according to --target PID

 -h, --help             display this help
 -V, --version          display version

For more details see nsenter(1).

示例

# 查看容器的PID
root@docker:~# docker inspect -f "{{.State.Pid}}" 0cede7571067
10582

# 进入容器
root@docker:~# nsenter -t 10582 -m -u -i -n -p
[root@0cede7571067 /]#

映射容器端口

docker 容器的端口映射建立在 iptables 的 DNAT 之上,通过创建一个 DNAT 规则,将宿主机的报文通过 docker0 虚拟网卡转发到容器中,该功能由 docker-proxyiptables 实现(所以需要保证 docker-proxy 能够运行、docker0 网卡网络正常、iptables 运行正常)

查看容器的端口映射

命令格式

root@docker:~# docker port --help
Usage:  docker port CONTAINER [PRIVATE_PORT[/PROTO]]

List port mappings or a specific mapping for the container

示例-查看容器端口映射关系

root@docker:~# docker port 5c7887dab84f
80/tcp -> 192.168.1.201:80

暴露容器所有端口

docker run -P 可以将事先容器预定义的所有端口映射到宿主机的随机端口,宿主机端口默认从 32768 开始

示例-暴露容器所有端口

# 创建容器,暴露所有端口
root@docker:~# docker run -d --name test-nginx -P nginx
4bf53882b4236caf5201afcad478e659bdfb7be3213533bb8f697b14e196c6fa

# 查看创建的容器
root@docker:~# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                         NAMES
4bf53882b423   nginx          "/docker-entrypoint.…"   32 seconds ago   Up 32 seconds   192.168.1.201:49153->80/tcp   test-nginx

# 查看端口映射情况
root@docker:~# docker port 4bf53882b423
80/tcp -> 192.168.1.201:49153

# 查看iptables规则
root@docker:~# iptables -t nat  -nvL
......
Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 MASQUERADE  all  --  *      !docker0  172.16.0.0/16        0.0.0.0/0
    0     0 MASQUERADE  all  --  *      !docker0  172.17.0.0/16        0.0.0.0/0
    0     0 MASQUERADE  tcp  --  *      *       172.16.0.3           172.16.0.3           tcp dpt:80

Chain DOCKER (2 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 RETURN     all  --  docker0 *       0.0.0.0/0            0.0.0.0/0
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            192.168.1.201        tcp dpt:49153 to:172.16.0.3:80
......

# 查看 docker-proxy 是否允许
root@docker:~# ps -ef | grep docker-proxy
root       41537    7688  0 04:19 ?        00:00:00 /usr/bin/docker-proxy -proto tcp -host-ip 192.168.1.201 -host-port 49153 -container-ip 172.16.0.3 -container-port 80

映射特定端口

docker run -p 可以将容器的预定义端口映射到宿主机,并且可以指定映射关系

注:多个容器映射到宿主机的端口不能冲突

常用方式

容器80端口映射到宿主机随机端口

docker run -d -p 80 --name nginx-t1 nginx

容器80端口映射到宿主机8080端口

docker run -d -p 8080:80 --name nginx-t2 nginx

容器80端口映射到宿主机指定IP的8081端口

docker run -d -p 192.168.1.201:8081:80 --name nginx-t3 nginx

容器80端口映射到主机指定IP的随机端口

docker run -d -p 192.168.1.201::80 --name nginx-t4 nginx

指定映射端口的协议

docker run -d -p 192.168.1.201:8082:80/udp --name nginx-t5 nginx

一次性映射多个端口

docker run -d -p 8083:80/tcp -p 8443:443/tcp -p 5300:53/udp --name nginx-t6 nginx

查看容器日志

命令格式

root@docker:~# docker logs --help
Usage:  docker logs [OPTIONS] CONTAINER
# 或
root@docker:~# docker container logs --help
Usage:  docker container logs [OPTIONS] CONTAINER

Fetch the logs of a container

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)

示例一-查看容器日志

root@docker:~# docker logs 4bf53882b423
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
... 启动日志 ....
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/04/28 20:19:51 [notice] 1#1: using the "epoll" event method
2022/04/28 20:19:51 [notice] 1#1: nginx/1.21.5
2022/04/28 20:19:51 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
......
... 访问日志 ...
192.168.1.201 - - [28/Apr/2022:20:32:42 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.68.0" "-"
192.168.1.201 - - [28/Apr/2022:20:32:47 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.68.0" "-"
......

示例二-显示日志后n行

root@docker:~# docker logs --tail 5 4bf53882b423
2022/04/28 20:32:26 [notice] 1#1: start worker processes
2022/04/28 20:32:26 [notice] 1#1: start worker process 25
2022/04/28 20:32:26 [notice] 1#1: start worker process 26
192.168.1.201 - - [28/Apr/2022:20:32:42 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.68.0" "-"
192.168.1.201 - - [28/Apr/2022:20:32:47 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.68.0" "-"

示例三-持续显示日志

# 类似于 tail -f
root@docker:~# docker logs -f --tail 5 4bf53882b423

示例四-显示日志时间

root@docker:~# docker logs -f --tail 5 -t 4bf53882b423
2022-04-28T20:32:26.068790721Z 2022/04/28 20:32:26 [notice] 1#1: start worker processes
2022-04-28T20:32:26.069614256Z 2022/04/28 20:32:26 [notice] 1#1: start worker process 25
2022-04-28T20:32:26.069807156Z 2022/04/28 20:32:26 [notice] 1#1: start worker process 26
2022-04-28T20:32:42.561921374Z 192.168.1.201 - - [28/Apr/2022:20:32:42 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.68.0" "-"
2022-04-28T20:32:47.133435221Z 192.168.1.201 - - [28/Apr/2022:20:32:47 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.68.0" "-"

示例五-显示指定时间段的日志

root@docker:~# docker logs --since "2022-04-28T20:32:25Z" --until "2022-04-28T20:32:45Z"  -t 4bf53882b423
2022-04-28T20:32:26.046260546Z /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
2022-04-28T20:32:26.046291172Z /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
2022-04-28T20:32:26.048815540Z /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
2022-04-28T20:32:26.054141069Z 10-listen-on-ipv6-by-default.sh: info: IPv6 listen already enabled
2022-04-28T20:32:26.054246086Z /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
2022-04-28T20:32:26.059473412Z /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
2022-04-28T20:32:26.067380221Z /docker-entrypoint.sh: Configuration complete; ready for start up
2022-04-28T20:32:26.068298351Z 2022/04/28 20:32:26 [notice] 1#1: using the "epoll" event method
2022-04-28T20:32:26.068400944Z 2022/04/28 20:32:26 [notice] 1#1: nginx/1.21.5
2022-04-28T20:32:26.068443126Z 2022/04/28 20:32:26 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2022-04-28T20:32:26.068481661Z 2022/04/28 20:32:26 [notice] 1#1: OS: Linux 5.4.0-100-generic
2022-04-28T20:32:26.068518991Z 2022/04/28 20:32:26 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022-04-28T20:32:26.068790721Z 2022/04/28 20:32:26 [notice] 1#1: start worker processes
2022-04-28T20:32:26.069614256Z 2022/04/28 20:32:26 [notice] 1#1: start worker process 25
2022-04-28T20:32:26.069807156Z 2022/04/28 20:32:26 [notice] 1#1: start worker process 26
2022-04-28T20:32:42.561921374Z 192.168.1.201 - - [28/Apr/2022:20:32:42 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.68.0" "-"

容器其他常用操作

挂载目录或文件

在容器创建时(docker createdocker run),可以将宿主机的目录或文件挂载到容器中(建议挂载目录),以实现文件的共享

示例

# 创建目录
root@docker:~# mkdir -p /test

# 容器挂载目录,并在容器中写入主机名
root@docker:~# docker run -it -v /test:/altest alpine sh
/ # hostname
33ff9ab56582
/ # echo `hostname` > /altest/hostname.txt
/ # exit

# 宿主机可以看到容器创建的文件和内容
root@docker:~# cat /test/hostname.txt
33ff9ab56582

传递运行命令

容器需要有一个持续运行的进程(守护进程,PID 为 1)才能够保证容器不会退出,通常使用两种方式

  • 传递运行命令
  • 构建镜像时指定容器启动时运行的前台命令

容器中 PID 为 1 的守护进程实现方式

  • 服务类:Nginx、Tomcat 等,但是服务不能停止
  • 命令类:tail -f /etc/hosts 等,主要用于测试环境,注意不要 tail -f <日志>,会出现大量磁盘 IO

示例

# 未传递运行命令时,容器会在运行后立刻退出
root@docker:~# docker run -d alpine
97c48911da368dbc9a29aadf18beb4da98f9d83a83c246bb246f73a228100938
# docker ps -a 查看,运行状态为 Exited
root@docker:~# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS                         NAMES
97c48911da36   alpine    "/bin/sh"                20 seconds ago   Exited (0) 19 seconds ago                                 elastic_lovelace

# 传递运行命令,会一直运行
root@docker:~# docker run -d alpine tail -f /etc/hosts
aabeaea05345b1ee767fdc05e2ddd4ea8637a83c73d468fe5ac8b8f8d6d71dc1
# docker ps -a 查看,运行状态为 UP
root@docker:~# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS         PORTS                         NAMES
aabeaea05345   alpine    "tail -f /etc/hosts"     4 seconds ago    Up 3 seconds                                 boring_mendeleev

修改容器中的 hosts 文件

使用 docker --add-host 选项可以在运行时修改容器的 hosts 文件

示例

root@docker:~# docker run -it --rm --add-host www.skynemo.cn:192.168.1.100 alpine
/ # cat /etc/hosts
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
192.168.1.100	www.skynemo.cn			# 添加的 dns 解析
172.16.0.4	f276d7655619

修改容器中的 DNS 地址

容器的 DNS 配置,默认采用的是宿主机的 DNS 地址,可以使用下列方式进行修改

将容器需要的 DNS 配置在宿主机(不推荐)
在容器启动时增加选项 `--dns=x.x.x.x`
在 `/etc/docker/daemon.json` 文件中指定,优先级比 `--dns` 低(推荐)

示例一-运行时指定DNS和domain

root@docker:~# docker run -it --rm --dns 1.1.1.1 --dns 8.8.8.8 --dns-search a.com --dns-search b.com busybox
/ # cat /etc/resolv.conf
search a.com b.com
nameserver 1.1.1.1
nameserver 8.8.8.8

示例二-配置文件指定DNS和domain

root@docker:~# cat /etc/docker/daemon.json
{
  "bip": "172.16.0.1/16",
  "data-root": "/data/docker",
  "dns": [ "114.114.114.114", "119.29.29.29" ],
  "dns-search": [ "skynemo.cn","xxx.com"],
  "insecure-registries": ["192.168.1.202:5000"],
  "ip": "192.168.1.201",
  "registry-mirrors": ["https://sqr9a2ic.mirror.aliyuncs.com"],
  "storage-driver": "overlay2"
}

# 修改配置文件需要重启 docker
root@docker:~# systemctl restart docker

root@docker:~# docker run -it --rm busybox
/ # cat /etc/resolv.conf
search skynemo.cn xxx.com
nameserver 114.114.114.114
nameserver 119.29.29.29

容器与宿主机间复制文件

命令格式

root@docker:~# docker cp --help
Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
	    docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
# 或
root@docker:~# docker container cp --help
Usage:  docker container cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
	docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem

Use '-' as the source to read a tar archive from stdin
and extract it to a directory destination in a container.
Use '-' as the destination to stream a tar archive of a
container source to stdout.

Options:
  -a, --archive       Archive mode (copy all uid/gid information)
  -L, --follow-link   Always follow symbol link in SRC_PATH

示例

root@docker:~# docker run -it -d alpine
de485eb647e7da7e4626e680ec6f9a0203f70fdf26b2ecf10bf86f625b264192

# 从容器拷贝文件到宿主机
root@docker:~# docker cp de485eb647e7:/etc/issue /root/

# 查看拷贝的文件
root@docker:~# cat /root/issue
Welcome to Alpine Linux 3.15
Kernel \r on an \m (\l)

使用 systemd 控制容器运行

可以使用 systemd 控制单个容器的运行(不推荐使用)

示例

[Unit]
Description= Hello World
After=docker.service

[Service]
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker kill busybox-hello
ExecStartPre=-/usr/bin/docker rm busybox-hello
ExecStartPre=-/usr/bin/docker pull busybox-hello
ExecStart=-/usr/bin/docker run --name busybox-hello busybox /usr/bin/tail -f "/etc/hosts"
ExecStop=-/usr/bin/docker kill busybox-hello

[Install]
WantedBy=multi-user.target

传递环境变量

有些容器运行时需要一些环境变量,可以使用 docker -e <参数> 或者 docker --env-file <参数文件> 实现

示例-传参 MySQL 以运行容器

# 启动容器提示需要传参
root@docker:~# docker run --name mysql-test mysql
2022-01-22 16:36:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.27-1debian10 started.
2022-01-22 16:36:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2022-01-22 16:36:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.27-1debian10 started.
2022-01-22 16:36:36+00:00 [ERROR] [Entrypoint]: Database is uninitialized and password option is not specified
    You need to specify one of the following:
    - MYSQL_ROOT_PASSWORD
    - MYSQL_ALLOW_EMPTY_PASSWORD
    - MYSQL_RANDOM_ROOT_PASSWORD

# 参数作用请参考:https://hub.docker.com/_/mysql

# 传参以启动容器,并将MySQL目录映射到主机 /data/mysql 下
root@docker:~# docker run -d -e MYSQL_ROOT_PASSWORD="520123" -v /data/mysql:/var/lib/mysql -p 3306:3306 --name mysql-3306 mysql

# 连接测试
root@docker:~# mysql -uroot -p520123 -h192.168.1.201
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.27 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>

0

评论区