概念
容器是Docker的另一个核心概念。简单来说,容器是镜像的一个运行实例。所不同的是,镜像是静态的只读文件,而容器带有运行时需要的可写文件层,同时容器中的应用进程处于运行状态。如果认为虚拟机是模拟运行的一整套操作系统(包括内核、应用运行态环境和其他系统环境)和跑在上面的应用。那么Docker 容器就是独立运行的一个(或一组)应用,以及它们必需的运行环境。
创建容器
λ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 7 months ago 13.3kB
λ docker create hello-world -ti
241063f261f97684b7a30ac69a278b4a4bf22b6e4a0512068957f3418764130a
λ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
NAMES
241063f261f9 hello-world "-ti" 7 seconds ago Created flamboyant_heyrovsky
启动容器
λ docker start 7b6add071f0b
7b6add071f0b
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
NAMES
7b6add071f0b 2888deb59dfc "docker-entrypoint.s…" 5 weeks ago Up 5 seconds 4369/tcp, 5671/tcp, 0.0.0.0:5672- >5672/tcp, 15671/tcp, 25672/tcp, 0.0.0.0:15672->15672/tcp rabbitmq
新建并启动容器
λ docker run ubuntu:15.10 /bin/echo "Hello world"
Hello world
启动一个bash终端,允许用户进行交互
λ docker run -ti ubuntu:15.10 /bin/bash
root@978e2a533c74:/# ls
bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
- -t选项让Docker 分配一个伪终端( pseudo-tty)并绑定到容器的标准输入上
- -i则让容器的标准输入保持打开
- 更多的命令选项可以See ‘docker run --help’。
λ 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 "15")
--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
wait 可以查看退出容器返回结果
λ docker container wait 835f56e2340b
127
守护态运行
λ docker run -tid ubuntu:15.10 /bin/bash
a6ad1501ac0963398b5c43c7cfa4823ad57d5586923e03283ef39baf89fc0ab2
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
NAMES
a6ad1501ac09 ubuntu:15.10 "/bin/bash" 5 seconds ago Up 3 seconds
jolly_heyrovsky
查看容器输出
λ docker run -d ubuntu:15.10 /bin/bash -c "while true; do echo hello word; sleep 1; done"
719c799c2302717191db0aae855157041da622a3faa56b4a39a53b4fb8d6dd8d
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
NAMES
719c799c2302 ubuntu:15.10 "/bin/bash -c 'while…" 8 seconds ago Up 7 seconds
romantic_dijkstra
λ docker logs 719c799c2302
hello word
hello word
hello word
hello word
hello word
hello word
hello word
hello word
hello word
hello word
hello word
hello word
hello word
hello word
hello word
暂停容器
λ docker run -dti --name test ubuntu:15.10 /bin/bash
8e27fb64dc4ddd19d04ccbb0f9a713e5d6812d1c19eb2a22083d47dda5731e18
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8e27fb64dc4d ubuntu:15.10 "/bin/bash" 3 seconds ago Up 2 seconds test
λ docker pause test
test
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8e27fb64dc4d ubuntu:15.10 "/bin/bash" 39 seconds ago Up 38 seconds (Paused) test
λ docker exec -ti test /bin/bash
Error response from daemon: Container test is paused, unpause the container before exec
终止容器
λ docker stop test
test
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
λ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
NAMES
8e27fb64dc4d ubuntu:15.10 "/bin/bash" 3 minutes ago Exited (0) About a minute ago
test
进入容器
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8e27fb64dc4d ubuntu:15.10 "/bin/bash" 8 minutes ago Up 7 seconds test
λ docker exec -ti test /bin/bash
root@8e27fb64dc4d:/# ls
bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
删除容器
λ docker stop test
test
λ docker rm test
test
导出容器
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b21e4124a45e ubuntu:15.10 "/bin/bash" 49 seconds ago Up 48 seconds test
λ docker export test > test.tar
导入容器
λ docker import test.tar ubuntu:15.10
sha256:7ce3c3a3010c5f14a39b30ae6541d18ed67478e9aef95dfca0b730e585b98e45
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
λ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu 15.10 7ce3c3a3010c 11 seconds ago 119MB
查看容器
λ docker container inspect test
[
{
"Id": "c3bf78c6e5ca3bf1ea386b700ab018661c66ee5b60763311f5efa883b1fee079",
"Created": "2022-05-13T07:16:20.5304764Z",
"Path": "/bin/bash",
"Args": [],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 2682,
"ExitCode": 0,
"Error": "",
"StartedAt": "2022-05-13T07:16:20.8766639Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:7ce3c3a3010c5f14a39b30ae6541d18ed67478e9aef95dfca0b730e585b98e45",
"ResolvConfPath": "/var/lib/docker/containers/c3bf78c6e5ca3bf1ea386b700ab018661c66ee5b60763311f5efa883b1fee079/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/c3bf78c6e5ca3bf1ea386b700ab018661c66ee5b60763311f5efa883b1fee079/hostname",
"HostsPath": "/var/lib/docker/containers/c3bf78c6e5ca3bf1ea386b700ab018661c66ee5b60763311f5efa883b1fee079/hosts",
"LogPath": "/var/lib/docker/containers/c3bf78c6e5ca3bf1ea386b700ab018661c66ee5b60763311f5efa883b1fee079/c3bf78c6e5ca3bf1ea386b700ab018661c66ee5b60763311f5efa883b1fee079-json.log",
"Name": "/test",
"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,
"CgroupnsMode": "private",
"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": [
29,
118
],
"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": null,
"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/3ca9bf5b7690f3ed4ee2752ac6e1d32c1d7527dae575993f145245637851817e-init/diff:/var/lib/docker/overlay2/4a4ee1526dd3829d67236118d5243a2048fa3721793490cc244bf09735fae45a/diff",
"MergedDir": "/var/lib/docker/overlay2/3ca9bf5b7690f3ed4ee2752ac6e1d32c1d7527dae575993f145245637851817e/merged",
"UpperDir": "/var/lib/docker/overlay2/3ca9bf5b7690f3ed4ee2752ac6e1d32c1d7527dae575993f145245637851817e/diff",
"WorkDir": "/var/lib/docker/overlay2/3ca9bf5b7690f3ed4ee2752ac6e1d32c1d7527dae575993f145245637851817e/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "c3bf78c6e5ca",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": true,
"OpenStdin": true,
"StdinOnce": false,
"Env": null,
"Cmd": [
"/bin/bash"
],
"Image": "ubuntu:15.10",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "5c37bf8b91bb82cbc53e8f533b6ea91d92c9418c00f82683fde34fb4aa1b8fbb",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/5c37bf8b91bb",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "7aa0c8dc918210bf51bdd783ef0c7cbff522436ad353753685c258c1857b58d4",
"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": "e7158acd53024b16020bc6d9d91aeb183d4646e9787468a7c094e412633d538a",
"EndpointID": "7aa0c8dc918210bf51bdd783ef0c7cbff522436ad353753685c258c1857b58d4",
"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 top test
UID PID PPID C STIME TTY
TIME CMD
root 2682 2656 0 07:16 ?
00:00:00 /bin/bash
查看统计信息
CPU 内存 存储 网络
docker stats test
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
c3bf78c6e5ca test 0.00% 1.449MiB / 1.909GiB 0.07% 1.09kB / 0B 0B / 0B 1
宿主机与容器之间的复制
λ docker cp example.txt test:/app/data
λ docker exec -ti test /bin/bash
root@c3bf78c6e5ca:/# ls -l /app/data/
total 4
-rwxr-xr-x 1 root root 1244 May 13 02:57 example.txt
反向
docker cp test:/app/data/example.txt test.txt
查看容器变更
λ docker container diff test
C /root
A /root/.bash_history
A /app
A /app/data
A /app/data/example.txt
查看端口变更
docker container port test