Docker整理
Docker
docker版本
ajune@ubuntu:~$ docker -v
Docker version 20.10.7, build f0df350
安装后需要执行的操作
将当前用户添加到docker用户组 docker 用户组,在安装docker后会自动创建
sudo usermod -aG docker USER NAME
然后退出重新登陆即可。
镜像
查找
-
查找, 通过docker search 可以进行对镜像的查找。查找是通过https://hub.docker.com/进行查找的。
docker search 镜像名称
ajune@ubuntu:~$ docker search --help Usage: docker search [OPTIONS] TERM Search the Docker Hub for images Options: -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 # 根据条件过滤 ajune@ubuntu:~$ docker search nginx -f STARS=3000 NAME DESCRIPTION STARS OFFICIAL AUTOMATED nginx Official build of Nginx. 15317 [OK]
查看
-
查看
docker images
ajune@ubuntu:~$ docker images --help Usage: docker images [OPTIONS] [REPOSITORY[:TAG]] List images Options: -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 pull进行镜像的拉取,可以对拉取的镜像版本进行指定拉取。
docker pull [选项] 镜像名称[:标签|@hash值]
ajune@ubuntu:~$ docker pull --help Usage: docker pull [OPTIONS] NAME[:TAG|@DIGEST] Pull an image or a repository from a registry Options: -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 # 拉取不同版本的镜像 # 拉取python3的镜像 ajune@ubuntu:~$ docker pull python:3 3: Pulling from library/python ... Digest: sha256:ec3fd3c3585160da037d2b01908ee7837a802be8984f449e65d3d80065d6d23a Status: Downloaded newer image for python:3 docker.io/library/python:3 # 拉取python2的镜像 ajune@ubuntu:~$ docker pull python:2 2: Pulling from library/python ... Digest: sha256:cfa62318c459b1fde9e0841c619906d15ada5910d625176e24bf692cf8a2601d Status: Downloaded newer image for python:2 docker.io/library/python:2 # 查看python的镜像 ajune@ubuntu:~$ docker images python REPOSITORY TAG IMAGE ID CREATED SIZE python 3 b2278d5ae327 3 days ago 886MB python 2 68e7be49c28c 16 months ago 902MB
删除
-
删除
docker rmi python
ajune@ubuntu:~$ docker rmi --help Usage: docker rmi [OPTIONS] IMAGE [IMAGE...] Remove one or more images Options: -f, --force Force removal of the image # 如果镜像被使用,那么直接删除会失败,如果要删除需要添加该参数 --no-prune Do not delete untagged parents # 删除tag为2 的python ajune@ubuntu:~$ docker rmi python:2
清理
docker image prune
清理长时间未使用的镜像
ajune@ubuntu:~$ docker image prune --help
Usage: docker image prune [OPTIONS]
Remove unused images
Options:
-a, --all Remove all unused images, not just dangling ones
--filter filter Provide filter values (e.g. 'until=<timestamp>')
-f, --force Do not prompt for confirmation
创建
commit
ajune@ubuntu:~$ docker commit --help
Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
Create a new image from a container's changes
Options:
-a, --author string Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
-c, --change list Apply Dockerfile instruction to the created image
-m, --message string Commit message
-p, --pause Pause container during commit (default true)
ajune@ubuntu:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c6d7d2387c2f nginx "/docker-entrypoint.…" 2 hours ago Up 2 hours 0.0.0.0:8081->80/tcp, :::8081->80/tcp nginxVolumeTest
fcff774abdc3 nginx "/docker-entrypoint.…" 2 hours ago Up 2 hours 0.0.0.0:8080->80/tcp, :::8080->80/tcp nginx01
ajune@ubuntu:~$ docker commit -m "修改了index.html" -a "ajune" nginx01 nginxowner:v1
sha256:8e0d4807304c1bb96211c6e877df6430bb0d00377a31558c952208f76466dfde
ajune@ubuntu:~$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginxowner v1 8e0d4807304c 5 seconds ago 133MB
nginx latest 08b152afcfae 3 weeks ago 133MB
import
ajune@ubuntu:~$ docker import --help
Usage: docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]
Import the contents from a tarball to create a filesystem image
Options:
-c, --change list Apply Dockerfile instruction to the created image
-m, --message string Set commit message for imported image
--platform string Set platform if server is multi-platform capable
基于Dockerfile创建
导出与导入
导出
ajune@ubuntu:~$ docker save --help
Usage: docker save [OPTIONS] IMAGE [IMAGE...]
Save one or more images to a tar archive (streamed to STDOUT by default)
Options:
-o, --output string Write to a file, instead of STDOUT
ajune@ubuntu:~$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
dtest v1 683cb0154877 16 hours ago 141MB
ajune@ubuntu:~$ docker save -o dtest.tar dtest:v1
ajune@ubuntu:~$ ll dtest*
-rw------- 1 ajune docker 147870208 Aug 17 09:47 dtest.tar
导入
ajune@ubuntu:~$ docker load --help
Usage: docker load [OPTIONS]
Load an image from a tar archive or STDIN
Options:
-i, --input string Read from tar archive file, instead of STDIN
-q, --quiet Suppress the load output
ajune@ubuntu:~$ docker load -i dtest.tar
容器
创建
docker create -it ubuntu
仅仅是创建了一个容器
ajune@ubuntu:~$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8111753f3fc2 ubuntu "bash" 5 minutes ago Created dazzling_bardeen
启动
docker start
ajune@ubuntu:~$ docker start --help
Usage: docker 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
ajune@ubuntu:~$ docker start 8111753f3fc2
ajune@ubuntu:~$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8111753f3fc2 ubuntu "bash" 5 minutes ago Exited (0) 2 seconds ago dazzling_bardeen
运行
-
运行
docker run
该
docker run
命令首先creates
在指定映像上创建一个可写容器层,然后starts
使用指定的命令。也就是说,docker run
相当于 API/containers/create
then/containers/(id)/start
。一个停止的容器可以使用docker start
. 查看docker ps -a
以查看所有容器的列表。
Docker在后台运行的标准操作:-
检查本地是否存在指定的镜像,如果不存在,从公共仓库下下载
-
利用镜像创建一个容器,并启动该容器
-
分配一个文件系统给容器,并在只读的镜像层外面怪在一层可读写层
-
从宿主机配置的网桥接一个虚拟接口到容器中
-
从网桥的地址池配置一个IP地址给容器
-
执行用户指定的应用程序
-
执行完毕后容器被自动终止
# 使用交互终端的方式启动名字为python3的容器,并且使用的镜像为python镜像tag为3. ajune@ubuntu:~$ docker run -it --name python3 python:3 /bin/bash root@8665c5fb049e:/# python Python 3.9.6 (default, Jul 22 2021, 15:16:20) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> exit() # 退出容器 root@8665c5fb049e:/# exit exit # 此时对应的容器也停止了 ajune@ubuntu:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8665c5fb049e python:3 "/bin/bash" About a minute ago Exited (0) 4 seconds ago python3 # 运行一个nginx容器, 启动一个名字为nginx01的容器,将宿主机的8080端口映射到容器的80端口。 ajune@ubuntu:~$ docker run -d --name nginx01 -p 8080:80 nginx fcff774abdc3f80685212e27372f3a2c710f535aaebc4d5bb31e6a8dfbbea73d ajune@ubuntu:~$ docker ps --filter name=nginx CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES fcff774abdc3 nginx "/docker-entrypoint.…" 8 seconds ago Up 7 seconds 0.0.0.0:8080->80/tcp, :::8080->80/tcp nginx01 ajune@ubuntu:~$
参数 默认值 含义 --add-host
添加自定义主机到 IP 映射 (host:ip) --attach
,-a
附加到 STDIN、STDOUT 或 STDERR --blkio-weight
Block IO(相对权重),在 10 到 1000 之间,或 0 表示禁用(默认为 0) --blkio-weight-device
块IO权重(相对设备权重) --cap-add
添加 Linux 功能 --cap-drop
删除 Linux 功能 --cgroup-parent
容器的可选父 cgroup --cgroupns
API 1.41+ 要使用的 Cgroup 命名空间 (host|private) 'host':在 Docker 主机的 cgroup 命名空间中运行容器 'private':在其自己的私有 cgroup 命名空间中运行容器 '':使用由 default-cgroupns-配置的 cgroup 命名空间守护进程的模式选项(默认) --cidfile
将容器 ID 写入文件 --cpu-count
CPU 计数(仅限 Windows) --cpu-percent
CPU 百分比(仅限 Windows) --cpu-period
限制 CPU CFS(完全公平调度程序)周期 --cpu-quota
限制 CPU CFS(完全公平调度程序)配额 --cpu-rt-period
API 1.25+ 以微秒为单位限制 CPU 实时周期 --cpu-rt-runtime
API 1.25+ 以微秒为单位限制 CPU 实时运行时间 --cpu-shares
,-c
CPU份额(相对权重) --cpus
API 1.25+ CPU数量 --cpuset-cpus
允许执行的 CPU (0-3, 0,1) --cpuset-mems
允许执行的 MEM (0-3, 0,1) --detach
,-d
在后台运行容器并打印容器 ID --detach-keys
覆盖用于分离容器的键序列 --device
将主机设备添加到容器 --device-cgroup-rule
向 cgroup 允许的设备列表添加规则 --device-read-bps
限制设备的读取速率(每秒字节数) --device-read-iops
限制设备的读取速率(每秒 IO) --device-write-bps
限制设备的写入速率(每秒字节数) --device-write-iops
限制设备的写入速率(每秒 IO) --disable-content-trust
true
跳过图像验证 --dns
设置自定义 DNS 服务器 --dns-opt
设置 DNS 选项 --dns-option
设置 DNS 选项 --dns-search
设置自定义 DNS 搜索域 --domainname
容器NIS域名 --entrypoint
覆盖图像的默认 ENTRYPOINT --env
,-e
设置环境变量 --env-file
读入环境变量文件 --expose
公开一个端口或一系列端口 --gpus
API 1.40+ 要添加到容器中的 GPU 设备('all' 以传递所有 GPU) --group-add
添加要加入的其他组 --health-cmd
运行以检查健康状况的命令 --health-interval
运行检查之间的时间(ms|s|m|h)(默认为 0s) --health-retries
报告不健康需要连续失败 --health-start-period
API 1.29+ 在开始健康重试倒计时(ms|s|m|h)之前容器初始化的开始时间(默认为 0s) --health-timeout
允许运行一次检查的最长时间(ms|s|m|h)(默认为 0s) --help
打印使用 --hostname
,-h
容器主机名 --init
API 1.25+ 在容器内运行一个 init 来转发信号和收获进程 --interactive
,-i
即使未连接,也要保持 STDIN 打开 --io-maxbandwidth
系统驱动器的最大 IO 带宽限制(仅限 Windows) --io-maxiops
系统驱动器的最大 IOps 限制(仅限 Windows) --ip
IPv4 地址(例如 172.30.100.104) --ip6
IPv6 地址(例如,2001:db8::33) --ipc
使用IPC模式 --isolation
容器隔离技术 --kernel-memory
内核内存限制 --label
,-l
在容器上设置元数据 --label-file
读入一行分隔的标签文件 --link
添加到另一个容器的链接 --link-local-ip
容器 IPv4/IPv6 链路本地地址 --log-driver
容器的日志驱动 --log-opt
日志驱动程序选项 --mac-address
容器 MAC 地址(例如,92:d0:c6:0a:29:33) --memory
,-m
内存限制 --memory-reservation
内存软限制 --memory-swap
交换限制等于内存加交换:“-1”启用无限交换 --memory-swappiness
-1
调整容器内存交换(0 到 100) --mount
将文件系统挂载附加到容器 --name
为容器指定名称 --net
将容器连接到网络 --net-alias
为容器添加网络范围的别名 --network
将容器连接到网络 --network-alias
为容器添加网络范围的别名 --no-healthcheck
禁用任何容器指定的 HEALTHCHECK --oom-kill-disable
禁用 OOM 杀手 --oom-score-adj
调整主机的 OOM 首选项(-1000 到 1000) --pid
要使用的 PID 命名空间 --pids-limit
调整容器 pids 限制(设置 -1 表示无限制) --platform
API 1.32+ 如果服务器支持多平台,则设置平台 --privileged
授予此容器扩展权限 --publish
,-p
将容器的端口发布到主机 --publish-all
,-P
将所有暴露的端口发布到随机端口 --pull
missing
运行前拉取镜像(“总是”|“缺失”|“从不”) --read-only
将容器的根文件系统挂载为只读 --restart
no
容器退出时应用的重启策略 --rm
退出时自动移除容器 --runtime
用于此容器的运行时 --security-opt
安全选项 --shm-size
/dev/shm 的大小 --sig-proxy
true
代理接收到进程的信号 --stop-signal
SIGTERM
停止容器的信号 --stop-timeout
API 1.25+ 停止容器的超时时间(以秒为单位) --storage-opt
容器的存储驱动程序选项 --sysctl
sysctl 选项 --tmpfs
挂载一个 tmpfs 目录 --tty
,-t
分配一个伪 TTY --ulimit
超限选项 --user
,-u
用户名或 UID(格式:<name|uid>[:<group|gid>]) --userns
要使用的用户命名空间 --uts
要使用的 UTS 命名空间 --volume
,-v
绑定挂载卷 --volume-driver
容器的可选卷驱动程序 --volumes-from
从指定的容器挂载卷 --workdir
,-w
容器内的工作目录 -
暂停
docker pause
ajune@ubuntu:~$ docker pause --help
Usage: docker pause CONTAINER [CONTAINER...]
Pause all processes within one or more containers
ajune@ubuntu:~$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8111753f3fc2 ubuntu "bash" 5 minutes ago Exited (0) 2 seconds ago dazzling_bardeen
c6d7d2387c2f nginx "/docker-entrypoint.…" 2 hours ago Up 2 hours 0.0.0.0:8081->80/tcp, :::8081->80/tcp nginxVolumeTest
fcff774abdc3 nginx "/docker-entrypoint.…" 2 hours ago Up 2 hours 0.0.0.0:8080->80/tcp, :::8080->80/tcp nginx01
ajune@ubuntu:~$ docker pause nginx01
nginx01
ajune@ubuntu:~$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8111753f3fc2 ubuntu "bash" 10 minutes ago Exited (0) 4 minutes ago dazzling_bardeen
c6d7d2387c2f nginx "/docker-entrypoint.…" 2 hours ago Up 2 hours 0.0.0.0:8081->80/tcp, :::8081->80/tcp nginxVolumeTest
fcff774abdc3 nginx "/docker-entrypoint.…" 2 hours ago Up 2 hours (Paused) 0.0.0.0:8080->80/tcp, :::8080->80/tcp nginx01
终止
-
终止
ajune@ubuntu:~$ docker stop --help Usage: docker 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 attach
无法进入一个已经停止的容器当多个窗口同时使用该命令进入该容器时,所有的窗口都会同步显示。如果有一个窗口阻塞了,那么其他窗口也无法再进行操作。
因为这个原因,所以docker attach命令不太适合于生产环境,平时自己开发应用时可以使用该命令。
ajune@ubuntu:~$ docker attach --help Usage: docker 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 # 指定退出attach的模式的快捷键,默认为Ctrl+P --no-stdin Do not attach STDIN # 是否关闭标准输入,默认是打开 --sig-proxy Proxy all received signals to the process (default true) # 是否代理收到的信号给应用进程
# 进入名字为python3的容器 ajune@ubuntu:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8665c5fb049e python:3 "/bin/bash" 14 minutes ago Exited (0) 4 seconds ago python3 ajune@ubuntu:~$ docker attach python3 You cannot attach to a stopped container, start it first ajune@ubuntu:~$ docker start python3 python3 ajune@ubuntu:~$ docker attach python3 # 如果使用exit退出容器会停止。 # 如果使用Ctrl+P+Q可以退出,但是容器不会停止运行。 root@8665c5fb049e:/# read escape sequence ajune@ubuntu:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8665c5fb049e python:3 "/bin/bash" 16 minutes ago Up About a minute python3
-
docker exec
无法进入一个已经停止的容器打开一个新的终端
ajune@ubuntu:~$ docker exec --help Usage: docker 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
ajune@ubuntu:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 2490845e7be8 python:3 "python3" 6 minutes ago Exited (0) 6 minutes ago python3 # 与attach 一样,无法进入已停止运行的容器 ajune@ubuntu:~$ docker exec -it python3 /bin/bash Error response from daemon: Container 2490845e7be8fd0c6ba6e8e6e744ac1d685795c40f4a55d5a63ef0c76227b75a is not running ajune@ubuntu:~$ docker start python3 python3 ajune@ubuntu:~$ docker exec -it python3 /bin/bash root@2490845e7be8:/# exit exit # 容器被挂起,但是没停止运行 ajune@ubuntu:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 2490845e7be8 python:3 "python3" 7 minutes ago Up 28 seconds python3
删除
-
删除, 一个正在运行的容器无法直接删除
docker rm
ajune@ubuntu:~$ docker rm --help Usage: docker 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
# 删除容器 ajune@ubuntu:~$ docker rm python3 Error response from daemon: You cannot remove a running container 8665c5fb049e127fcbd0cf527652b4d74bc17e0e27bebb3bcdda58b51edf19f6. Stop the container before attempting removal or force remove # 要删除的容器正在运行,无法删除 ajune@ubuntu:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8665c5fb049e python:3 "/bin/bash" 20 minutes ago Up 6 minutes python3 # 使用-f参数,强制删除。Docker后先发送SINGKILL信号给容器,终止其中的应用,之后强制删除。 ajune@ubuntu:~$ docker rm -f python3 python3 ajune@ubuntu:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
导入与导出
导出容器
docker export -o 文件名.tar 镜像
ajune@ubuntu:~$ docker export --help
Usage: docker export [OPTIONS] CONTAINER
Export a container's filesystem as a tar archive
Options:
-o, --output string Write to a file, instead of STDOUT
ajune@ubuntu:~$ docker export -o nginx01.tar nginx01
ajune@ubuntu:~$ ls |grep nginx
nginx01.tar
ajune@ubuntu:~$
导入容器
docker import
ajune@ubuntu:~$ docker import --help
Usage: docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]
Import the contents from a tarball to create a filesystem image
Options:
-c, --change list Apply Dockerfile instruction to the created image
-m, --message string Set commit message for imported image
--platform string Set platform if server is multi-platform capable
查看容器
查看容器详情
docker inspect
查看容器内进程
docker top
查看看统计信息
docker stats
其他命令
复制
docker cp
将文件从宿主机复制到容器内,或者将文件从容器内复制到宿主机。
ajune@ubuntu:~$ docker cp --help
Usage: docker 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
ajune@ubuntu:~$ docker cp ./index.html nginx01:/usr/share/nginx/html/
查看容器变更
docker diff
查看端口映射
docker port
更新配置
docker update
数据卷
创建数据卷
ajune@ubuntu:~$ docker volume --help
Usage: docker volume COMMAND
Manage volumes
Commands:
create Create a volume
inspect Display detailed information on one or more volumes
ls List volumes
prune Remove all unused local volumes
rm Remove one or more volumes
Run 'docker volume COMMAND --help' for more information on a command.
ajune@ubuntu:~$ docker volume create testVolume
testVolume
ajune@ubuntu:~$ docker volume ls
DRIVER VOLUME NAME
local testVolume
ajune@ubuntu:~$ docker volume inspect testVolume
[
{
"CreatedAt": "2021-08-16T14:07:49+08:00",
"Driver": "local",
"Labels": {},
"Mountpoint": "/var/lib/docker/volumes/testVolume/_data",
"Name": "testVolume",
"Options": {},
"Scope": "local"
}
]
绑定数据卷
可以在创建容器时通过-mount选项使用数据卷。
- volume:普通数据卷,映射到主机目录下。
- bind:绑定数据卷,映射到主机的指定路径下。
- tmpfs:临时数据卷,只存在于内存中。
添加数据卷
ajune@ubuntu:~$ docker run --name nginxVolumeTest -d -v /home/ajune/sourceDir:/desDir -p 8081:80 nginx
c6d7d2387c2f69b406c47f623eb596b0a0708a0ba7c8ee3216bd3500c76eed0d
ajune@ubuntu:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c6d7d2387c2f nginx "/docker-entrypoint.…" 3 seconds ago Up 2 seconds 0.0.0.0:8081->80/tcp, :::8081->80/tcp nginxVolumeTest
fcff774abdc3 nginx "/docker-entrypoint.…" 22 minutes ago Up 22 minutes 0.0.0.0:8080->80/tcp, :::8080->80/tcp nginx01
多个容器挂在到同一个数据卷上
ajune@ubuntu:~$ mkdir p0
ajune@ubuntu:~$ docker run -it --name u1 -v /home/ajune/p0:/desDir ubuntu /bin/bash
ajune@ubuntu:~$ docker run -it --name u2 -v /home/ajune/p0:/desDir ubuntu /bin/bash
ajune@ubuntu:~$ docker run -it --name u3 -v /home/ajune/p0:/desDir ubuntu /bin/bash
端口
映射
docker run -d -p 5000:5000 --name pythonweb training/webapp python app.py
ajune@ubuntu:~$ docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Run a command in a new container
Options:
...
-p, --publish list Publish a container's port(s) to the host
-P, --publish-all Publish all exposed ports to random ports
...
互联
ajune@ubuntu:~$ docker run --help|grep link
--link list Add link to another container
--link-local-ip list Container IPv4/IPv6 link-local addresses
ajune@ubuntu:~$ docker run -d --name db training/postgres
ajune@ubuntu:~$ docker run -d -P --name web --link db:db training/webapp python app.py
通过Dockerfile创建镜像
Dockerfile 主体内容分为四部分:基础镜像信息、 维护者信息、 镜像操作指 令和容器启动时执行指令。
# 指定所创建镜像的基础镜像
# 指定所创建镜像的基础镜像
ARG VERSION=9.3
FROM debian:${VERSION}
# 为生成的镜像添加元数据标签信息
LABEL maintainer docker_user<ajune>
LABEL version="1.0" author="ajune" date="2020-01-01" description=""
# 暴露端口,只起到声明作用,并不会自动完成端口的映射
EXPOSE 22 80 8443
# 指定环境变量, 但是可以在docker run时通过--env key=value的方式进行覆盖
ENV APP VERSION=l.0.0
ENV APP_HOME=/usr/local/app
ENV PATH $PATH:/usr/local/bin
# 指定镜像的默认入口命令, 该入口命令会在启动容器时作为根命令执行, 所有传人值作为该命令的参数。
# ENTRYPOINT ["executable", "paraml ", "param2"] # exec 调用执行
# ENTRYPOINT command param 1 param2 # shell 中执行
# 数据卷挂载
VOLUME ["/data1", "/data2"]
RUN useradd --create-home --no-log-init --shell /bin/bash ajune \
&& adduser ajune sudo \
&& echo 'ajune:ajunepwd' | chpasswd \
&& apt-get update \
&& apt-get install -y python3 \
&& rm -rf /var/cache/apt \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir /app \
&& pwd
# 用于指定执行后续命令的用户和用户组,这边只是切换后续命令执行的用户(用户和用户组必须提前已经存在)。
USER ajune
# 指定工作目录
WORKDIR /
WORKDIR app
# 此时工作目录为/app
# 当基于这个镜像创建新的镜像时才会执行
ONBUILD ADD . /app # 当使用这个dockerfile创建镜像时并不执行,当使用了该镜像创建新的镜像时才会执行。
# SHELL ["executable", "parameters"] 默认值 ["/bin/sh", "-c"]
SHELL ["/bin/sh", "-c"]
# CMD指令用来指定启动容器时默认执行的命令
# CMD [ "executable" , "param1 " , "param2"]:相当于执行executable param1 param2,推荐方式;
# CMD command param1 param2:在默认的Shell 中执行,提供给需要交互的应用;
# CMD [ "param1" , "param2"]:提供给ENTRYPOINT的默认参数。
# 每个Dockerfile只能有一条CMD命令。如果指定了多条命令,只有最后一条会被执行。如果用户启动容器时候手动指定了运行的命令(作为run命令的参数),则会覆盖掉CMD指定的命令。
CMD ["/bin/sh", "-c"]
# ADD 添加文件到镜像内
# 格式为ADD <src> <dest>。
# 该命令将复制指定的<src>路径下内容到容器中的<dest>路径下。
#其中<src>可以是Dockerfile所在目录的一个相对路径(文件或目录);也可以是一个URL;还可以是一个tar文件(自动解压为目录)<dest>可以是镜像内绝对路径,或者相对于工作目录(WORKDIR)的相对路径。路径支持正则格式。
ADD add.txt /app
# COPY 复制内容到镜像。
# 格式为COPY <src> <dest>。
# 复制本地主机的<src>(为Dockerfile所在目录的相对路径,文件或目录)下内容到镜像中的<dest>。目标路径不存在时,会自动创建。
# 路径同样支持正则格式。
# COPY与ADD指令功能类似,当使用本地目录为源目录时,推荐使用COPY。
copy ./copy /copy
分类 | 指令 | 说明 |
---|---|---|
配置 | ARG | 定义创建镜像过程之中使用的变量 |
FROM | 指定所创建镜像的基础镜像 | |
LABEL | 为生成的镜像添加元数据标签信息 | |
EXPOSE | 声明镜像内服务监听的端口 | |
ENV | 指定环境变量 | |
ENTRYPOINT | 指定镜像的默认入口命令 | |
VOLUME | 创建一个数据卷挂载点 | |
USER | 指定运行容器时的用户名或UID | |
WORKDIR | 配置工作目录 | |
ONBUILD | 创建子镜像时指定自动执行的操作指令 | |
STOPSIGNAL | 指定退出的信号值 | |
HEALTHCHECK | 配置所启动容器如何进行健康检查 | |
SHELL | 指定默认shell类型 | |
操作指令 | RUN | 运行指定命令 |
CMD | 启动容器时指定默认执行的命令 | |
ADD | 添加内容到镜像 | |
COPY | 复制内容到镜像 |
创建的时候每遇到一个RUN、ADD、COPY都会生成一个新的镜像。
# 使用上面的内容写到Dockerfile中
ajune@ubuntu:~/dockerfile_test vim Dockerfile
ajune@ubuntu:~/dockerfile_test$ docker build -t dtest:v1 .
ajune@ubuntu:~/dockerfile_test$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
dtest v1 683cb0154877 21 seconds ago 141MB
ajune@ubuntu:~/dockerfile_test$ docker run -it --name dockerfiletest dtest:v1 /bin/bash
ajune@939ae842b5f5:/app$ pwd
/app
网络
Docker使用Linux桥接,在宿主机虚拟一个Docker容器网桥(docker0),Docker启动一个容器时会根据Docker网桥的网段分配给容器一个IP地址,称为Container-IP,同时Docker网桥是每个容器的默认网关。因为在同一宿主机内的容器都接入同一个网桥,这样容器之间就能够通过容器的Container-IP直接通信。
Docker网桥是宿主机虚拟出来的,并不是真实存在的网络设备,外部网络是无法寻址到的,这也意味着外部网络无法通过直接Container-IP访问到容器。如果容器希望外部访问能够访问到,可以通过映射容器端口到宿主主机(端口映射),即docker run创建容器时候通过 -p 或 -P 参数来启用,访问容器的时候就通过[宿主机IP]:[容器端口]访问容器。
Docker网络模式 | 配置 | 说明 |
---|---|---|
host模式 | –net=host | 容器和宿主机共享Network |
container模式 | –net=container:NAME_or_ID | 容器和另外一个容器共享Network namespace |
none模式 | –net=none | 容器有独立的Network namespace,但并没有对其进行任何网络设置,如分配veth pair 和网桥连接,配置IP等。 |
bridge模式 | –net=bridge | (默认为该模式) |
查看网络
ajune@ubuntu:~$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:54:f7:8d brd ff:ff:ff:ff:ff:ff
inet 192.168.8.100/24 brd 192.168.8.255 scope global ens33
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe54:f78d/64 scope link
valid_lft forever preferred_lft forever
# 为docker创建的默认网络
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:56:b5:8a:35 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::42:56ff:feb5:8a35/64 scope link
valid_lft forever preferred_lft forever
使用默认网络(docker0)
# 启动redis的docker容器
ajune@ubuntu:~$ docker run -it --name redis01 redis /bin/bash
# 查看redis01 的详细信息
ajune@ubuntu:~$ docker inspect redis01
#...
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "22a590522789485dbdea9b86af07bd0906d45b395d79580a53a0cb89d157a5b4",
"EndpointID": "fb3729f0fda0f72e326f51b40221fff90702bbcbe3de157129d384370b7bedfc",
"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
}
}
#...
创建新的容器,与redis01使用--link连接
ajune@ubuntu:~$ docker run -it --name redis02 --link redis01 redis /bin/bash
ajune@ubuntu:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
bcd415508ab5 redis "docker-entrypoint.s…" 5 minutes ago Up 5 minutes 6379/tcp redis02
2ecd76c87214 redis "docker-entrypoint.s…" 22 minutes ago Up 22 minutes 6379/tcp redis01
# 如果找不到ping命令
# 先执行apt update
# 再执行apt install -y iputils-ping
# redis01 ip:172.17.0.2
# redis02 ip:172.17.0.3
ajune@ubuntu:~$ docker exec -it redis02 /bin/bash
# 在redis02中ping redis01,只能通过IP 进行ping
root@bcd415508ab5:/data# ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.166 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.100 ms
64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.097 ms
64 bytes from 172.17.0.2: icmp_seq=4 ttl=64 time=0.164 ms
64 bytes from 172.17.0.2: icmp_seq=5 ttl=64 time=0.129 ms
^C
--- 172.17.0.2 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 6ms
rtt min/avg/max/mdev = 0.097/0.131/0.166/0.030 ms
ajune@ubuntu:~$ docker exec -it redis01 /bin/bash
# 在redis01中ping redis02
root@2ecd76c87214:/data# ping 172.17.0.3
PING 172.17.0.3 (172.17.0.3) 56(84) bytes of data.
64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.076 ms
64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.098 ms
64 bytes from 172.17.0.3: icmp_seq=3 ttl=64 time=0.074 ms
^C
--- 172.17.0.3 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.074/0.082/0.098/0.015 ms
查看docker0
ajune@ubuntu:~$ docker network inspect bridge
[
{
"Name": "bridge",
"Id": "22a590522789485dbdea9b86af07bd0906d45b395d79580a53a0cb89d157a5b4",
"Created": "2021-08-17T14:32:15.940672329+08:00",
"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": {
# 该网络下有哪些容器
"2ecd76c872142227e4f331f951958e150589b28bbf7562893b68daf962cc91a7": {
"Name": "redis01",
"EndpointID": "fb3729f0fda0f72e326f51b40221fff90702bbcbe3de157129d384370b7bedfc",
"MacAddress": "02:42:ac:11:00:02",
"IPv4Address": "172.17.0.2/16",
"IPv6Address": ""
},
"bcd415508ab5c7ba42dfc340b1e6c09f5443f1ffe80206eb2d6f511b0b693b15": {
"Name": "redis02",
"EndpointID": "bf0a17cbe8aad8cda8d307f52a60a83064196078492a9429b88f0b9db5df2cc4",
"MacAddress": "02:42:ac:11:00:03",
"IPv4Address": "172.17.0.3/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": {}
}
]
创建自定义网络
ajune@ubuntu:~$ docker network --help
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network
create Create a network
disconnect Disconnect a container from a network
inspect Display detailed information on one or more networks
ls List networks
prune Remove all unused networks
rm Remove one or more networks
Run 'docker network COMMAND --help' for more information on a command.
ajune@ubuntu:~$ docker network create --help
Usage: docker network create [OPTIONS] NETWORK
Create a network
Options:
--attachable Enable manual container attachment
--aux-address map Auxiliary IPv4 or IPv6 addresses used by Network driver (default map[])
--config-from string The network from which to copy the configuration
--config-only Create a configuration only network
-d, --driver string Driver to manage the Network (default "bridge")
--gateway strings IPv4 or IPv6 Gateway for the master subnet
--ingress Create swarm routing-mesh network
--internal Restrict external access to the network
--ip-range strings Allocate container ip from a sub-range
--ipam-driver string IP Address Management Driver (default "default")
--ipam-opt map Set IPAM driver specific options (default map[])
--ipv6 Enable IPv6 networking
--label list Set metadata on a network
-o, --opt map Set driver specific options (default map[])
--scope string Control the network's scope
--subnet strings Subnet in CIDR format that represents a network segment
# 创建网络段为172.16.0.0/16的网络,网关为172.16.0.1 名字为redis-net
ajune@ubuntu:~$ docker network create --driver bridge --subnet 172.16.0.0/16 --gateway 172.16.0.1 redis-net
e6b96f4e33d3d3bbe1bd88247b64127f51ad6e87a95f57cb4ea35e11d2b65492
# 查看redis-net信息
ajune@ubuntu:~$ docker network inspect redis-net
[
{
"Name": "redis-net",
"Id": "e6b96f4e33d3d3bbe1bd88247b64127f51ad6e87a95f57cb4ea35e11d2b65492",
"Created": "2021-08-18T10:46:40.210906268+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": {},
"Config": [
{
"Subnet": "172.16.0.0/16",
"Gateway": "172.16.0.1"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {},
"Options": {},
"Labels": {}
}
]
使用自定义网络
# 停止正在运行的容器
ajune@ubuntu:~$ docker stop $(docker ps -aq)
# 删除容器
ajune@ubuntu:~$ docker rm $(docker ps -aq)
# 创建容器,使用自定义网络,并指定ip
# 创建一个名字为redis10,使用网络redis-net,IP为172.16.0.10的容器
ajune@ubuntu:~$ docker run -d --name redis10 --network redis-net --ip 172.16.0.10 redis
9d90331ff1f82d18df66872b2bb121d898811fa05b7989e18385d97167094c2b
# 创建一个名字为redis11,使用网络redis-net,IP为172.16.0.11的容器
ajune@ubuntu:~$ docker run -d --name redis11 --network redis-net --ip 172.16.0.11 redis
1f96d916bc45b6f6b5ef72b3bedb50f21548e73752126b40bcfd0d8048ec1b1a
# 创建一个名字为redis12,使用网络redis-net,IP为172.16.0.12的容器
ajune@ubuntu:~$ docker run -d --name redis12 --network redis-net --ip 172.16.0.12 redis
bbcc9d6ee81fc2f66c7479949271011a28a00ea0eda63a05dc44fc7f65546f16
ajune@ubuntu:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
bbcc9d6ee81f redis "docker-entrypoint.s…" 9 seconds ago Up 8 seconds 6379/tcp redis12
1f96d916bc45 redis "docker-entrypoint.s…" 15 seconds ago Up 14 seconds 6379/tcp redis11
9d90331ff1f8 redis "docker-entrypoint.s…" 33 seconds ago Up 31 seconds 6379/tcp redis10
查看此时redis-net的网络情况
ajune@ubuntu:~$ docker network inspect redis-net
[
{
"Name": "redis-net",
"Id": "e6b96f4e33d3d3bbe1bd88247b64127f51ad6e87a95f57cb4ea35e11d2b65492",
"Created": "2021-08-18T10:46:40.210906268+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": {},
"Config": [
{
"Subnet": "172.16.0.0/16",
"Gateway": "172.16.0.1"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"1f96d916bc45b6f6b5ef72b3bedb50f21548e73752126b40bcfd0d8048ec1b1a": {
"Name": "redis11",
"EndpointID": "9ffac287198baaa3ba2850a4ee4d8de35d9dd29c9660196305add3c94220044b",
"MacAddress": "02:42:ac:10:00:0b",
"IPv4Address": "172.16.0.11/16",
"IPv6Address": ""
},
"9d90331ff1f82d18df66872b2bb121d898811fa05b7989e18385d97167094c2b": {
"Name": "redis10",
"EndpointID": "12c0fafce8491ff6335d27c551fe8b6ce21a5b5c570c4e741816e0941f4de582",
"MacAddress": "02:42:ac:10:00:0a",
"IPv4Address": "172.16.0.10/16",
"IPv6Address": ""
},
"bbcc9d6ee81fc2f66c7479949271011a28a00ea0eda63a05dc44fc7f65546f16": {
"Name": "redis12",
"EndpointID": "68c6695feead4a74b28a78ebb4e2d2275646781e3f03c29659eb33fcd5f61379",
"MacAddress": "02:42:ac:10:00:0c",
"IPv4Address": "172.16.0.12/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {}
}
]
# 在redis10中ping redis11、redis12(不使用IP)
root@9d90331ff1f8:/data# ping redis12
PING redis12 (172.16.0.12) 56(84) bytes of data.
64 bytes from redis12.redis-net (172.16.0.12): icmp_seq=1 ttl=64 time=0.099 ms
64 bytes from redis12.redis-net (172.16.0.12): icmp_seq=2 ttl=64 time=0.105 ms
64 bytes from redis12.redis-net (172.16.0.12): icmp_seq=3 ttl=64 time=0.095 ms
^C
--- redis12 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 3ms
rtt min/avg/max/mdev = 0.095/0.099/0.105/0.012 ms
root@9d90331ff1f8:/data# ping redis11
PING redis11 (172.16.0.11) 56(84) bytes of data.
64 bytes from redis11.redis-net (172.16.0.11): icmp_seq=1 ttl=64 time=0.172 ms
64 bytes from redis11.redis-net (172.16.0.11): icmp_seq=2 ttl=64 time=0.104 ms
64 bytes from redis11.redis-net (172.16.0.11): icmp_seq=3 ttl=64 time=0.058 ms
64 bytes from redis11.redis-net (172.16.0.11): icmp_seq=4 ttl=64 time=0.136 ms
^C
--- redis11 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 4ms
rtt min/avg/max/mdev = 0.058/0.117/0.172/0.043 ms
root@9d90331ff1f8:/data#
在宿主机查看
ajune@ubuntu:~$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:54:f7:8d brd ff:ff:ff:ff:ff:ff
inet 192.168.8.100/24 brd 192.168.8.255 scope global ens33
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe54:f78d/64 scope link
valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:56:b5:8a:35 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::42:56ff:feb5:8a35/64 scope link
valid_lft forever preferred_lft forever
# 之前创建的redis-net
140: br-e6b96f4e33d3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:83:b5:e7:32 brd ff:ff:ff:ff:ff:ff
inet 172.16.0.1/16 brd 172.16.255.255 scope global br-e6b96f4e33d3
valid_lft forever preferred_lft forever
inet6 fe80::42:83ff:feb5:e732/64 scope link
valid_lft forever preferred_lft forever
142: veth3df46a9@if141: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-e6b96f4e33d3 state UP group default
link/ether 82:e1:9d:6d:cf:d9 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet6 fe80::80e1:9dff:fe6d:cfd9/64 scope link
valid_lft forever preferred_lft forever
144: veth2def6a8@if143: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-e6b96f4e33d3 state UP group default
link/ether 7e:b4:2a:75:10:fb brd ff:ff:ff:ff:ff:ff link-netnsid 1
inet6 fe80::7cb4:2aff:fe75:10fb/64 scope link
valid_lft forever preferred_lft forever
146: veth8638d90@if145: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-e6b96f4e33d3 state UP group default
link/ether b6:56:6a:cf:66:ec brd ff:ff:ff:ff:ff:ff link-netnsid 2
inet6 fe80::b456:6aff:fecf:66ec/64 scope link
valid_lft forever preferred_lft forever