docker 学习笔记

Docker简介

Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从 Apache2.0 协议开源。

Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级、可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。

容器是完全使用沙箱机制,相互之间不会有任何接口(类似 iPhone 的 app),更重要的是容器性能开销极低。

Docker的应用场景

  • Web 应用的自动化打包和发布。
  • 自动化测试和持续集成、发布。
  • 在服务型环境中部署和调整数据库或其他的后台应用。
  • 从头编译或者扩展现有的 OpenShift 或 Cloud Foundry 平台来搭建自己的 PaaS 环境。

Docker 的优点

  • 快速,一致地交付您的应用程序
  • 响应式部署和扩展
  • 在同一硬件上运行更多工作负载

Docker 官网:https://www.docker.com

Github Docker 源码:https://github.com/docker/docker-ce

Docker架构

imgDocker 包括三个基本概念:

  • 镜像(Image):Docker 镜像(Image),就相当于是一个 root 文件系统。比如官方镜像 ubuntu:16.04 就包含了完整的一套 Ubuntu16.04 最小系统的 root 文件系统。
  • 容器(Container):镜像(Image)和容器(Container)的关系,就像是面向对象程序设计中的类和实例一样,镜像是静态的定义,容器是镜像运行时的实体。容器可以被创建、启动、停止、删除、暂停等。
  • 仓库(Repository):仓库可看成一个代码控制中心,用来保存镜像。

Docker 使用客户端-服务器 (C/S) 架构模式,使用远程API来管理和创建Docker容器。

Docker 容器通过 Docker 镜像来创建。

容器与镜像的关系类似于面向对象编程中的对象与类。

Docker 安装

Ubuntu Docker 安装

CentOS Docker 安装

Docker 镜像加速

阿里镜像加速

1
2
3
4
5
6
7
8
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://rnjrwkn6.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

Docker常用命令

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

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
[root@i-6x8256ap ~]# docker -h
Flag shorthand -h has been deprecated, please use --help

Usage: docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
--config string Location of client config files (default "/root/.docker")
-c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and
default context set with "docker context use")
-D, --debug Enable debug mode
-H, --host list Daemon socket(s) to connect to
-l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/root/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit

Management Commands:
builder Manage builds
config Manage Docker configs
container Manage containers
context Manage contexts
engine Manage the docker engine
image Manage images
network Manage networks
node Manage Swarm nodes
plugin Manage plugins
secret Manage Docker secrets
service Manage services
stack Manage Docker stacks
swarm Manage Swarm
system Manage Docker
trust Manage trust on Docker images
volume Manage volumes

Commands:
attach Attach local standard input, output, and error streams to a running container
build Build an image from a Dockerfile
commit Create a new image from a container's changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
diff Inspect changes to files or directories on a container's filesystem
events Get real time events from the server
exec Run a command in a running container
export Export a container's filesystem as a tar archive
history Show the history of an image
images List images
import Import the contents from a tarball to create a filesystem image
info Display system-wide information
inspect Return low-level information on Docker objects
kill Kill one or more running containers
load Load an image from a tar archive or STDIN
login Log in to a Docker registry
logout Log out from a Docker registry
logs Fetch the logs of a container
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
ps List containers
pull Pull an image or a repository from a registry
push Push an image or a repository to a registry
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
rmi Remove one or more images
run Run a command in a new container
save Save one or more images to a tar archive (streamed to STDOUT by default)
search Search the Docker Hub for images
start Start one or more stopped containers
stats Display a live stream of container(s) resource usage statistics
stop Stop one or more running containers
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
top Display the running processes of a container
unpause Unpause all processes within one or more containers
update Update configuration of one or more containers
version Show the Docker version information
wait Block until one or more containers stop, then print their exit codes

镜像相关的命令

创建镜像 docker build -t <imageName:tag> -f /path/to/dockerfile .

  • 用法
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
[root@i-6x8256ap compose_test]# docker build --help

Usage: docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Options:
--add-host list Add a custom host-to-IP mapping (host:ip)
--build-arg list Set build-time variables
--cache-from strings Images to consider as cache sources
--cgroup-parent string Optional parent cgroup for the container
--compress Compress the build context using gzip
--cpu-period int Limit the CPU CFS (Completely Fair Scheduler) period
--cpu-quota int Limit the CPU CFS (Completely Fair Scheduler) quota
-c, --cpu-shares int CPU shares (relative weight)
--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)
--disable-content-trust Skip image verification (default true)
-f, --file string Name of the Dockerfile (Default is 'PATH/Dockerfile')
--force-rm Always remove intermediate containers
--iidfile string Write the image ID to the file
--isolation string Container isolation technology
--label list Set metadata for an image
-m, --memory bytes Memory limit
--memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap
--network string Set the networking mode for the RUN instructions during build (default "default")
--no-cache Do not use cache when building the image
-o, --output stringArray Output destination (format: type=local,dest=path)
--platform string Set platform if server is multi-platform capable
--progress string Set type of progress output (auto, plain, tty). Use plain to show container output (default "auto")
--pull Always attempt to pull a newer version of the image
-q, --quiet Suppress the build output and print image ID on success
--rm Remove intermediate containers after a successful build (default true)
--secret stringArray Secret file to expose to the build (only if BuildKit enabled): id=mysecret,src=/local/secret
--security-opt strings Security options
--shm-size bytes Size of /dev/shm
--squash Squash newly built layers into a single new layer
--ssh stringArray SSH agent socket or keys to expose to the build (only if BuildKit enabled) (format: default|<id>[=<socket>|<key>[,<key>]])
--stream Stream attaches to server to negotiate build context
-t, --tag list Name and optionally a tag in the 'name:tag' format
--target string Set the target build stage to build.
--ulimit ulimit Ulimit options (default [])
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@i-6x8256ap compose_test]# docker build -t docker_web -f Dockerfile .
Sending build context to Docker daemon 6.144kB
Step 1/5 : FROM python:3.7
---> 978a47fa762f
Step 2/5 : COPY src/ /opt/src
---> Using cache
---> f2e42b56b98b
Step 3/5 : WORKDIR /opt/src
---> Using cache
---> 84d1debebaf3
Step 4/5 : RUN pip install -r requirements.txt
---> Using cache
---> 5e63e1ecf854
Step 5/5 : CMD ["python", "app.py"]
---> Using cache
---> d7ebf4a81d35
Successfully built d7ebf4a81d35
Successfully tagged docker_web:latest

查看镜像列表 docker images

  • 示例
1
2
3
4
5
6
7
[root@i-6x8256ap ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
python 3.6 6693bf717fb6 4 months ago 874MB
jumpserver/jms_koko 1.5.9 86b49fc31c21 6 months ago 356MB
jumpserver/jms_guacamole 1.5.9 0c3963b634a4 6 months ago 657MB
consul latest 0544f375e878 7 months ago 117MB
hello-world latest bf756fb1ae65 11 months ago 13.3kB
  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@i-6x8256ap ~]# docker images -h
Flag shorthand -h has been deprecated, please use --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 numeric IDs

搜索镜像 docker search <镜像名字>

  • 示例
1
2
3
4
5
6
7
8
[root@i-6x8256ap ~]# docker search nginx
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
nginx Official build of Nginx. 14172 [OK]
jwilder/nginx-proxy Automated Nginx reverse proxy for docker con1929 [OK]
richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable of… 797 [OK]
linuxserver/nginx An Nginx container, brought to you by LinuxS… 134
jc21/nginx-proxy-manager Docker container for managing Nginx proxy ho… 120
tiangolo/nginx-rtmp Docker image with Nginx using the nginx-rtmp… 106 [OK]
  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@i-6x8256ap ~]# docker search -h

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

# 过滤stars大于200,且是官方的nginx镜像
docker search nginx -f stars=200 is-official=true

拉取镜像 docker pull <镜像名字>

  • 示例
1
2
3
4
5
6
7
[root@i-6x8256ap ~]# docker pull hello-world
Using default tag: latest
latest: Pulling from library/hello-world
0e03bdcc26d7: Already exists
Digest: sha256:1a523af650137b8accdaed439c17d684df61ee4d74feac151b5b337bd29e7eec
Status: Downloaded newer image for hello-world:latest
docker.io/library/hello-world:latest
  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
[root@i-6x8256ap ~]# docker pull -h
Flag shorthand -h has been deprecated, please use --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

删除镜像:docker rmi <镜像名字>

  • 示例
1
2
3
4
[root@i-6x8256ap ~]# docker rmi -f  hello-world
Untagged: hello-world:latest
Untagged: hello-world@sha256:1a523af650137b8accdaed439c17d684df61ee4d74feac151b5b337bd29e7eec
Deleted: sha256:bf756fb1ae65adf866bd8c456593cd24beb6a0a061dedf42b26a993176745f6b
  • 用法
1
2
3
4
5
6
7
8
9
10
[root@i-6x8256ap ~]# docker rmi -h
Flag shorthand -h has been deprecated, please use --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

提交信息到镜像 docker commit

  • 用法
1
2
3
4
5
6
7
8
9
10
11
[root@i-6x8256ap ~]# 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)

导出镜像 docker save -o name.tar <imageID>

  • 用法
1
2
3
4
5
6
7
8
[root@i-6x8256ap ~]# 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
  • 示例
1
2
3
4
5
6
7
8
9
10
[root@i-6x8256ap ~]# docker save -o tomcat-8.5.tar tomcat:8.5
[root@i-6x8256ap ~]# ll
total 612460
-rw------- 1 root root 544990208 Dec 20 17:48 tomcat-8.5.tar

# 导出的文件在当前目录,上述命令亦可用下面的命令替代
[root@i-6x8256ap ~]# docker save tomcat:8.5 > tomcat-8.5.tar.copy
[root@i-6x8256ap ~]# ll
-rw------- 1 root root 544990208 Dec 20 17:48 tomcat-8.5.tar
-rw-r--r-- 1 root root 544990208 Dec 20 17:53 tomcat-8.5.tar.copy

导入镜像 docker load -i <镜像tar包>

  • 用法
1
2
3
4
5
6
7
8
9
[root@i-6x8256ap ~]# 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
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 方式一
[root@i-6x8256ap ~]# docker load -i tomcat-8.5.tar
ffb4778f8a52: Loading layer [==================================================>] 3.584kB/3.584kB
f85e383859a1: Loading layer [==================================================>] 209.7MB/209.7MB
534cb8e32a3a: Loading layer [==================================================>] 2.56kB/2.56kB
ffe983ff0cbb: Loading layer [==================================================>] 19.58MB/19.58MB
b0968020cd45: Loading layer [==================================================>] 2.048kB/2.048kB
Loaded image: tomcat:8.5

# 方式二
[root@i-6x8256ap ~]# docker load < tomcat-8.5.tar.copy
ffb4778f8a52: Loading layer [==================================================>] 3.584kB/3.584kB
f85e383859a1: Loading layer [==================================================>] 209.7MB/209.7MB
534cb8e32a3a: Loading layer [==================================================>] 2.56kB/2.56kB
ffe983ff0cbb: Loading layer [==================================================>] 19.58MB/19.58MB
b0968020cd45: Loading layer [==================================================>] 2.048kB/2.048kB
Loaded image: tomcat:8.5

容器相关的命令

创建并启动容器 docker run

  • 用法
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
[root@i-6x8256ap ~]# 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
--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
--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 进程 dcoker ps

  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@i-6x8256ap ~]# docker ps --help

Usage: docker ps [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 numeric IDs
-s, --size Display total file sizes

查看容器状态统计 docker stats <容器ID>

  • 用法
1
2
3
4
5
6
7
8
9
10
11
[root@i-6x8256ap ~]# docker stats --help

Usage: docker 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
  • 示例
1
2
3
[root@i-6x8256ap ~]# docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
7d0e935b85a4 pensive_wiles 0.01% 71.02MiB / 3.7GiB 1.87% 656B / 0B 0B / 0B 36

退出容器

  • 用法
1
2
方式一:exit  # 退出并关闭容器
方式二:ctrl + p +q # 退出不关闭容器

重启容器 docker restart <容器ID>

  • 用法
1
2
3
4
5
6
7
8
[root@i-6x8256ap ~]# docker restart --help

Usage: docker restart [OPTIONS] CONTAINER [CONTAINER...]

Restart one or more containers

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

停止容器 docker stop <容器ID>

  • 用法
1
2
3
4
5
6
7
8
[root@i-6x8256ap ~]# 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 kill <容器ID>

  • 用法
1
2
3
4
5
6
7
8
[root@i-6x8256ap ~]# docker kill --help

Usage: docker kill [OPTIONS] CONTAINER [CONTAINER...]

Kill one or more running containers

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

删除已经停止的容器 docker rm <容器ID>

  • 示例
1
2
3
4
[root@i-6x8256ap ~]# docker rm 73a82cd8d59e a32c2ed88835 50f3a65f2219
73a82cd8d59e
a32c2ed88835
50f3a65f2219
  • 用法
1
2
3
4
5
6
7
8
9
10
[root@i-6x8256ap ~]# 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

删除容器 docker rm <容器:ID>

  • 示例
1
2
3
4
5
# 删除一个
[root@i-6x8256ap ~]# docker rm -f da2c804390fe

# 一次删除多个
[root@i-6x8256ap ~]# docker rm -f $(docker ps -qa)
  • 用法
1
2
3
4
5
6
7
8
9
10
[root@i-6x8256ap ~]# 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

以守护进程启动容器

  • 示例
1
2
3
4
[root@i-6x8256ap ~]# docker run -d centos /bin/sh -c "while true;do echo 'I Love You';sleep 2;done"
3eb5dffe30c62242faa89aa5c007cc65b475900f0ca034e32b71ed8918e153cf

# 如果没有交互进程,容器启动后就会结束

查看容器内的进程 docker top <容器ID>

  • 示例
1
2
3
4
[root@i-6x8256ap ~]# docker top 3eb5dffe30c6
UID PID PPID C STIME TTY TIME CMD
root 14938 14920 0 16:36 ? 00:00:00 /bin/sh -c while true;do echo 'I Love You';sleep 2;done
root 16136 14938 0 16:42 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 2
  • 用法
1
2
3
4
5
[root@i-6x8256ap ~]# docker top --help

Usage: docker top CONTAINER [ps OPTIONS]

Display the running processes of a container

查看容器日志 docker logs -ft <容器ID>

  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
[root@i-6x8256ap ~]# docker logs --help

Usage: docker 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:37) or relative (e.g. 42m for 42 minutes)
--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:37) or relative (e.g. 42m for 42 minutes)
  • 示例
1
[root@i-6x8256ap ~]# docker logs -ft --tail 5 7d0e935b85a4

查看容器内的细节 docker inspect <容器ID>

进入容器

docker attach <容器ID>
  • 用法
1
2
3
4
5
6
7
8
9
10
[root@i-6x8256ap ~]# 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
--no-stdin Do not attach STDIN
--sig-proxy Proxy all received signals to the process (default true)

注:docker attach可以attach到一个已经运行的容器的stdin,然后进行命令执行的动作。
但是需要注意的是,如果从这个stdin中exit,会导致容器的停止。

docker exec -t <容器ID> <cmd>
  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@i-6x8256ap ~]# 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
-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

copy容器内的数据到本地

  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@i-6x8256ap ~]# 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

Docker 网络命令 docker network <opts>

  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@i-6x8256ap ~]# 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.

查看network列表 docker network ls

1
2
3
4
5
[root@i-6x8256ap ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
5aa8673629ff bridge bridge local
8793af47e9b0 host host local
d6dd4ae716a8 none null local

查看network详情 docker network inspect <networkID>

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
[root@i-6x8256ap ~]# docker network inspect 5aa8673629ff
[
{
"Name": "bridge",
"Id": "5aa8673629ffd516f43f87d3d082f4288cf7a72526f82aaedc04772ab501ae9f",
"Created": "2020-12-19T21:17:37.224915641+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": {
"6c3c46cca05b59d60df1c2fa8cb58a6d7a57e3963a01baa2de7275c44f83824f": {
"Name": "tomcat2",
"EndpointID": "f867dafc7f8d5805e89fe2861e33a1aa8f38783ab042d0641f79d2ba529b682e",
"MacAddress": "02:42:ac:11:00:03",
"IPv4Address": "172.17.0.3/16",
"IPv6Address": ""
},
"8615f51616f391c460e30843d4258c2c3b9a26719b7deed8e7ad642094d7595f": {
"Name": "tomcat3",
"EndpointID": "99a3cb6a218738d9c3e92657b5bacd0223f07acc0929095da4c4e74588017096",
"MacAddress": "02:42:ac:11:00:04",
"IPv4Address": "172.17.0.4/16",
"IPv6Address": ""
},
"8d1699a2171254b871cabe8017c5a84fe8870b581989dfed2517e291619cb78d": {
"Name": "tomcat1",
"EndpointID": "d14d7f0375f1a76eb7500faab0ed29a94f1b914f51ab5619ad224cc2398a4509",
"MacAddress": "02:42:ac:11:00:02",
"IPv4Address": "172.17.0.2/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": {}
}
]

Docker镜像

镜像是一种轻量级、可执行的独立软件包,用来打包软件运行环境和基于运行环境开发的软件,它包含运行某个软件所需要的所有内容,包括代码、运行时、库、环境变量和配置文件等

Docker联合文件系统Union File System

Docker联合文件系统(Union File System),它是实现Docker镜像的技术基础,是一种轻量级的高性能分层文件系统,支持将文件系统中的修改进行提交和层层叠加,这个特性使得镜像可以通过分层实现和继承。同时支持将不同目录挂载到同一个虚拟文件系统下。

在Docker镜像分为基础镜像和父镜像,没有父镜像的镜像被称为基础镜像。用户是基于基础镜像来制作各种不同的应用镜像。这些应用镜像共享同一个基础镜像层,提高了存储效率。

特性:一次同时加载多个文件系统,但从外面看起来,只能看到一个文件系统,联合加载会把各层文件系统叠加起来,这样最终的文件系统会包含所有底层的文件和目录.

Docker镜像加载原理

在Docker中使用AUFS(Another Union File System或Advanced Multilayered Unification File System)就是一种联合文件系统。AUFS不仅可以对每一个目录设定只读(Readonly)、读写(Readwrite)和写(Witeout-able)权限,同时AUFS也可以支持分层的机制,例如,可以对只读权限部分逻辑上进行增量地修改而不影响只读部分。

docker的镜像实际上由一层一层的文件系统组成,这种层级的文件系统称之为UnionFS。从linux启动为例介绍docker在AUFS特性的运用。典型的Linux启动到运行需要两个FileSystem,BootFS 和RootFS。

BootFS (boot file system)主要包含BootLoader 和Kernel, BootLoader主要是引导加载Kernel,Linux刚启动时会加载bootfs文件系统,在Docker镜像的最底层是bootfs。当Boot成功后,Kernel被加载到内存中BootFS就被Umount了。

RootFS (root file system)包含的就是典型 Linux 系统中的 /dev、/proc、/bin 等标准目录和文件。rootfs就是各种不同的操作系统发行版,比如Ubuntu,Centos等等。

不同的linux发行版,BootFS基本是一致的, RootFS会有差别,因此不同的发行版可以共享BootFS。

Docker镜像都是只读的,当容器启动时,一个新的可写层被加载到镜像的顶部。这一层通常被称作“容器层”,“容器层”之下的都叫“镜像层”。

Docker容器数据卷

在Docker容器的实际使用中,经常会遇到容器的数据持久化,容器之间的数据共享等问题,通常我们有两种解决方案:

1)数据卷(Data Volumes):就是将容器内数据直接映射到本地主机环境的指定文件目录之中,可以理解为容器挂载一个虚拟数据卷然后映射到一个主机目录中

2)数据卷容器(Data Volume Containers):用专门的容器来挂载数据卷,其他容器通过挂载这个父容器来实现数据共享,这个专门挂载数据卷的容器就是数据卷容器,简单的总结就是有一个容器来专门管理数据的持久化和容器之间数据共享

注:前者常用于单一容器数据持久化,后者常用于多容器之间的数据共享和数据持久化

数据卷(Data Volumes)

我们可以在镜像程序运行时通过”-v /主机目录文件名:/容器目录名” 命令,将容器卷指定一个主机目录,这样我们的程序运行的数据就可以持久保存到这个映射的主机目录文件当中。

1
2
3
docker run -d -v /root/examples:/usr/local/tomcat/webapps/examples:[ro] -p 9000:8080 tomcat:8.5.32

# [ro] 表示只有读的权限,默认是具有读写权限

特点:

  • 数据卷可以在容器之间共享或重用数据
  • 数据卷中的更改可以直接生效
  • 数据卷中的更改不会包含在镜像的更新中
  • 数据卷的生命周期一直持续到没有容器使用它为止

数据卷容器(Data Volume Containers)

如我我们经常需要多个容器之间进行数据共享我们需要用到命令“–volumes-from”

1)我们从仓库拉一个centos的容器镜像

1
\$ docker pull centos

2)然后运行这个镜像并创建一个数据卷挂载到/mydata

1
\$ docker run -it -v /mydata --name mycentos centos

3)再运行两个容器,在这两个容器中使用–volumes-from来挂载mycentos容器中的数据卷.

1
2
3
\$ docker run -it --volumes-from mycentos --name soncentos1 centos

\$ docker run -it --volumes-from mycentos --name soncentos2 centos

此时,容器soncentos1和soncentos2都挂载同一个数据卷到相同的/mydata 目录。三个容器任何一方在该目录下的写入数据,其他容器都可以看到。

注:可以多次使用–volumes-from参数来从多个容器挂载多个数据卷。还可以从其他已经挂载了容器卷的容器来挂载数据卷。
使用–volumes-from参数所挂载数据卷的容器自身并不需要保持在运行状态。
如果删除了挂载的容器(包括dbdata、db1和db2),数据卷并不会被自动删除。如果要删除一个数据卷,必须在删除最后一个还挂载着它的容器时显式使用docker rm -v命令来指定同时删除关联的容器。

DockerFile解析

Dockerfile 是一个用来构建镜像的,有一系列命令和参数组成的文本文件。

docker build命令用于从Dockerfile构建映像。可以在docker build命令中使用-f标志指向文件系统中任何位置的Dockerfile。例:

1
docker build -f /path/to/a/Dockerfile

DockerFile内容基本知识

  • 每条保留字指令都必须为大写字母且后面至少需要一个参数
  • 指令是自上而下顺序执行
  • #表示注释
  • 每条指令都会创建一个新的镜像层,并对镜像进行提交

DockerFile执行的流程

  • docker 从基础镜像运行一个容器
  • 执行一条指令并对容器作出修改
  • 执行类似docker commit的操作提交一个新的镜像层
  • docker再基于刚提交的镜像运行一个新容器
  • 执行DockerFile中的下一条指令制导所有指令都执行完成

DockerFile中的关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
FROM:指定创建镜像的基础镜像
MAINTAINER:Dockerfile作者信息,一般写的是联系方式
RUN:运行Linux系统的命令使用
CMD:指定容器启动执行的命令;启动容器中的服务
LABEL:指定生成镜像的源数据标签
EXPOSE:指定镜像容器监听端口号;发布服务使用
ENV:使用环境变量
ADD:对压缩文件进行解压缩;将数据移动到指定的目录
COPY:复制宿主机数据到镜像内部使用
WORKDIR:切换到镜像容器中的指定目录中
VOLUME:挂载数据卷到镜像容器中
USER:指定运行容器的用户
ARG:指定镜像的版本号信息
ONBUILD:创建镜像,作为其他镜像的基础镜像运行操作指令
ENTRYPOINT:指定运行容器启动过程执行命令,覆盖CMD参数

参考:Dockerfile文件详解

Docker 常用安装

Docker 网络

  • 启动tomcat1
1
2
[root@i-6x8256ap ~]# docker run -d -p 9000:8080 --name tomcat1 tomcat:8.5.32
8d1699a2171254b871cabe8017c5a84fe8870b581989dfed2517e291619cb78d

网络信息

1
2
3
4
5
6
7
8
9
[root@i-6x8256ap ~]# docker exec -i tomcat1 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
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
46: eth0@if47: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
valid_lft forever preferred_lft forever
  • 启动tomcat2
1
2
[root@i-6x8256ap ~]# docker run -d -p 9001:8080 --name tomcat2 tomcat:8.5.32
6c3c46cca05b59d60df1c2fa8cb58a6d7a57e3963a01baa2de7275c44f83824f

网络信息

1
2
3
4
5
6
7
8
9
[root@i-6x8256ap ~]# docker exec tomcat2 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
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
48: eth0@if49: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
valid_lft forever preferred_lft forever
  • 当前主机的网络信息
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@i-6x8256ap ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 52:54:f5:ea:df:91 brd ff:ff:ff:ff:ff:ff
inet 10.57.21.158/24 brd 10.57.21.255 scope global noprefixroute dynamic eth0
valid_lft 40sec preferred_lft 40sec
inet6 fe80::696e:9fd9:b517:3e9d/64 scope link noprefixroute
valid_lft forever preferred_lft forever
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:4e:b2:8d:e0 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:4eff:feb2:8de0/64 scope link
valid_lft forever preferred_lft forever
47: vethe9abbf1@if46: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether b6:b1:27:4e:68:81 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet6 fe80::b4b1:27ff:fe4e:6881/64 scope link
valid_lft forever preferred_lft forever
49: vethefc90f6@if48: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether ae:86:ee:f0:23:35 brd ff:ff:ff:ff:ff:ff link-netnsid 1
inet6 fe80::ac86:eeff:fef0:2335/64 scope link
valid_lft forever preferred_lft forever

Docker 网络模式

  • bridge:桥接(默认)
  • none:不配置网络
  • host:和宿主机共享网络
  • container:容器网络连同

查看网络列表 docker network ls

  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@i-6x8256ap ~]# docker network ls --help

Usage: docker network ls [OPTIONS]

List networks

Aliases:
ls, list

Options:
-f, --filter filter Provide filter values (e.g. 'driver=bridge')
--format string Pretty-print networks using a Go template
--no-trunc Do not truncate the output
-q, --quiet Only display network IDs
  • 示例
1
2
3
4
5
[root@i-6x8256ap ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
5aa8673629ff bridge bridge local
8793af47e9b0 host host local
d6dd4ae716a8 none null local

查看网络详情 docker network inspect <networkID>

  • 用法
1
2
3
4
5
6
7
8
9
[root@i-6x8256ap ~]# docker network inspect --help

Usage: docker network inspect [OPTIONS] NETWORK [NETWORK...]

Display detailed information on one or more networks

Options:
-f, --format string Format the output using the given Go template
-v, --verbose Verbose output for diagnostics
  • 示例
1
[root@i-6x8256ap ~]# docker network inspect 5aa8673629ff

创建网络 docker network create [opts]

  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@i-6x8256ap ~]# 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 copying 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
  • 示例
1
2
3
4
5
6
7
8
9
[root@i-6x8256ap ~]# docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet
2dc7d8dc168cc70f18b0810b1af1f82a8f89471b6931d684224ae835c4f6f541

[root@i-6x8256ap ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
5aa8673629ff bridge bridge local
8793af47e9b0 host host local
2dc7d8dc168c mynet bridge local
d6dd4ae716a8 none null local

使用自定义的网络创建容器

1
2
3
[root@i-6x8256ap ~]# docker run -d -p 9010:8080 --name tomcat-net1 --net mynet  tomcat:8.5.32
d02b191f7db4995af4e69237f1a797b2bee2d5324cd9022ccf328879701a20bf
[root@i-6x8256ap ~]# docker run -d -p 9011:8080 --name tomcat-net2 --net mynet tomcat:8.5.32

测试网络连同性

1
2
3
4
5
6
7
8
9
[root@i-6x8256ap ~]# docker exec tomcat-net1 ping tomcat-net2
PING tomcat-net2 (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcat-net2.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.267 ms
64 bytes from tomcat-net2.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.204 ms

[root@i-6x8256ap ~]# docker exec tomcat-net2 ping tomcat-net1
PING tomcat-net1 (192.168.0.2) 56(84) bytes of data.
64 bytes from tomcat-net1.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.328 ms
64 bytes from tomcat-net1.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.182 ms

注:使用自定义的网络的容器之间是互通的

使不同的网络之间互通 docker network connect <network> <container>

  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
[root@i-6x8256ap ~]# docker network connect --help

Usage: docker network connect [OPTIONS] NETWORK CONTAINER

Connect a container to a network

Options:
--alias strings Add network-scoped alias for the container
--driver-opt strings driver options for the network
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--link list Add link to another container
--link-local-ip strings Add a link-local address for the container
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
# 初始时无法ping
[root@i-6x8256ap ~]# docker exec tomcat3 ping tomcat-net1
ping: tomcat-net1: Name or service not known

# 设置网络互通
[root@i-6x8256ap ~]# docker network connect mynet tomcat3

# 测试已经ok
[root@i-6x8256ap ~]# docker exec tomcat3 ping tomcat-net1
PING tomcat-net1 (192.168.0.2) 56(84) bytes of data.
64 bytes from tomcat-net1.mynet (192.168.0.2): icmp_seq=1 ttl=64 time=0.416 ms
64 bytes from tomcat-net1.mynet (192.168.0.2): icmp_seq=2 ttl=64 time=0.195 ms

注:docker network connect直接将tomcat3 新增了一个网卡

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@i-6x8256ap ~]# docker exec tomcat3 ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
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
52: eth0@if53: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:11:00:04 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.0.4/16 brd 172.17.255.255 scope global eth0
valid_lft forever preferred_lft forever
61: eth1@if62: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:c0:a8:00:04 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 192.168.0.4/16 brd 192.168.255.255 scope global eth1
valid_lft forever preferred_lft forever

Docker Compose

Compose 简介

Compose 是用于定义和运行多容器 Docker 应用程序的工具。通过 Compose,您可以使用 YML 文件来配置应用程序需要的所有服务。然后,使用一个命令,就可以从 YML 文件配置中创建并启动所有服务。

Compose 使用的三个步骤:

  • 使用 Dockerfile 定义应用程序的环境。
  • 使用 docker-compose.yml 定义构成应用程序的服务,这样它们可以在隔离环境中一起运行。
  • 最后,执行 docker-compose up 命令来启动并运行整个应用程序。

Compose 安装

  • 从github上下载docker-compose二进制文件安装

    Linux 上我们可以从 Github 上下载它的二进制包来使用,最新发行的版本地址:https://github.com/docker/compose/releases

    运行以下命令以下载 Docker Compose 的当前稳定版本:

    1
    # sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

    要安装其他版本的 Compose,请替换 1.27.4。

    将可执行权限应用于二进制文件:

    1
    # sudo chmod +x /usr/local/bin/docker-compose

    创建软链:

    1
    # sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

    测试是否安装成功:

    1
    2
    $ docker-compose --version
    cker-compose version 1.27.4, build 4667896b
  • pip安装

    1
    # sudo pip install docker-compose

Compose 示例

参考:docker-compose教程(安装,使用, 快速入门)

Compose 命令参数

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
[root@i-6x8256ap ~]# docker-compose --help
Define and run multi-container applications with Docker.

Usage:
docker-compose [-f <arg>...] [options] [--] [COMMAND] [ARGS...]
docker-compose -h|--help

Options:
-f, --file FILE Specify an alternate compose file
(default: docker-compose.yml)
-p, --project-name NAME Specify an alternate project name
(default: directory name)
-c, --context NAME Specify a context name
--verbose Show more output
--log-level LEVEL Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
--no-ansi Do not print ANSI control characters
-v, --version Print version and exit
-H, --host HOST Daemon socket to connect to

--tls Use TLS; implied by --tlsverify
--tlscacert CA_PATH Trust certs signed only by this CA
--tlscert CLIENT_CERT_PATH Path to TLS certificate file
--tlskey TLS_KEY_PATH Path to TLS key file
--tlsverify Use TLS and verify the remote
--skip-hostname-check Don't check the daemon's hostname against the
name specified in the client certificate
--project-directory PATH Specify an alternate working directory
(default: the path of the Compose file)
--compatibility If set, Compose will attempt to convert keys
in v3 files to their non-Swarm equivalent (DEPRECATED)
--env-file PATH Specify an alternate environment file

Commands:
build Build or rebuild services
config Validate and view the Compose file
create Create services
down Stop and remove containers, networks, images, and volumes
events Receive real time events from containers
exec Execute a command in a running container
help Get help on a command
images List images
kill Kill containers
logs View output from containers
pause Pause services
port Print the public port for a port binding
ps List containers
pull Pull service images
push Push service images
restart Restart services
rm Remove stopped containers
run Run a one-off command
scale Set number of containers for a service
start Start services
stop Stop services
top Display the running processes
unpause Unpause services
up Create and start containers
version Show version information and quit

注:Docker compose的使用非常类似于docker命令的使用,但是需要注意的是大部分的compose命令都需要到docker-compose.yml文件所在的目录下才能执行

以守护进程模式运行加-d选项

1
# docker-compose up -d

查看服务列表 docker-compose ps

  • 用法
1
2
3
4
5
6
7
8
9
10
[root@i-6x8256ap docker]# docker-compose ps -h
List containers.

Usage: ps [options] [--] [SERVICE...]

Options:
-q, --quiet Only display IDs
--services Display services
--filter KEY=VAL Filter services by a property
-a, --all Show all stopped containers (including those created by the run command)
  • 示例
1
2
3
4
5
[root@i-6x8256ap docker]# docker-compose ps -a
Name Command State Ports
--------------------------------------------------------------------------------
docker_redis_1 docker-entrypoint.sh redis ... Up 6379/tcp
docker_web_1 python app.py Up 0.0.0.0:5000->5000/tcp

查看日志 docker-compose logs <sericeName>

  • 示例
1
[root@i-6x8256ap docker]# docker-compose logs -t web
  • 用法
1
2
3
4
5
6
7
8
9
10
11
[root@i-6x8256ap docker]# docker-compose logs -h
View output from containers.

Usage: logs [options] [--] [SERVICE...]

Options:
--no-color Produce monochrome output.
-f, --follow Follow log output.
-t, --timestamps Show timestamps.
--tail="all" Number of lines to show from the end of the logs
for each container.

Docker Machine

Docker Machine 是一种可以让您在虚拟主机上安装 Docker 的工具,并可以使用 docker-machine 命令来管理主机。

Docker Machine 也可以集中管理所有的 docker 主机,比如快速的给 100 台服务器安装上 docker。

Docker Machine 管理的虚拟主机可以是机上的,也可以是云供应商,如阿里云,腾讯云,AWS,或 DigitalOcean。

使用 docker-machine 命令,您可以启动,检查,停止和重新启动托管主机,也可以升级 Docker 客户端和守护程序,以及配置 Docker 客户端与您的主机进行通信。

Machine 安装

安装 Docker Machine 之前你需要先安装 Docker。

Docker Mechine 可以在多种平台上安装使用,包括 Linux 、MacOS 以及 windows。

Linux 安装命令

1
2
3
4
$ base=https://github.com/docker/machine/releases/download/v0.16.2 &&
curl -L $base/docker-machine-$(uname -s)-$(uname -m) >/tmp/docker-machine &&
sudo mv /tmp/docker-machine /usr/local/bin/docker-machine &&
chmod +x /usr/local/bin/docker-machine

macOS 安装命令

1
2
3
$ base=https://github.com/docker/machine/releases/download/v0.16.2 &&
curl -L $base/docker-machine-$(uname -s)-$(uname -m) >/usr/local/bin/docker-machine &&
chmod +x /usr/local/bin/docker-machine

Windows 安装命令

如果你是 Windows 平台,可以使用 Git BASH,并输入以下命令:

1
2
3
4
$ base=https://github.com/docker/machine/releases/download/v0.16.02 &&
mkdir -p "$HOME/bin" &&
curl -L $base/docker-machine-Windows-x86_64.exe > "$HOME/bin/docker-machine.exe" &&
chmod +x "$HOME/bin/docker-machine.exe"

查看是否安装成功:

1
2
$ docker-machine version
docker-machine version 0.16.0, build 9371605

Machine 命令参数

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
[root@i-6x8256ap ~]# docker-machine -h
Usage: docker-machine [OPTIONS] COMMAND [arg...]

Create and manage machines running Docker.

Version: 0.16.2, build bd45ab13

Author:
Docker Machine Contributors - <https://github.com/docker/machine>

Options:
--debug, -D Enable debug mode
--storage-path, -s "/root/.docker/machine" Configures storage path [$MACHINE_STORAGE_PATH]
--tls-ca-cert CA to verify remotes against [$MACHINE_TLS_CA_CERT]
--tls-ca-key Private key to generate certificates [$MACHINE_TLS_CA_KEY]
--tls-client-cert Client cert to use for TLS [$MACHINE_TLS_CLIENT_CERT]
--tls-client-key Private key used in client TLS auth [$MACHINE_TLS_CLIENT_KEY]
--github-api-token Token to use for requests to the Github API [$MACHINE_GITHUB_API_TOKEN]
--native-ssh Use the native (Go-based) SSH implementation. [$MACHINE_NATIVE_SSH]
--bugsnag-api-token BugSnag API token for crash reporting [$MACHINE_BUGSNAG_API_TOKEN]
--help, -h show help
--version, -v print the version

Commands:
active Print which machine is active
config Print the connection config for machine
create Create a machine
env Display the commands to set up the environment for the Docker client
inspect Inspect information about a machine
ip Get the IP address of a machine
kill Kill a machine
ls List machines
provision Re-provision existing machines
regenerate-certs Regenerate TLS Certificates for a machine
restart Restart a machine
rm Remove a machine
ssh Log into or run a command on a machine with SSH.
scp Copy files between machines
mount Mount or unmount a directory from a machine with SSHFS.
start Start a machine
status Get the status of a machine
stop Stop a machine
upgrade Upgrade a machine to the latest version of Docker
url Get the URL of a machine
version Show the Docker Machine version or a machine docker version
help Shows a list of commands or help for one command

Run 'docker-machine COMMAND --help' for more information on a command.

Docker 可视化工具

portainer安装

1
docker run -d -p 8088:9000 --restart always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer

登录:http://103.21.118.193:8088

本地镜像发布到阿里云

参考

从零开始,使用Docker Swarm部署集群教程

-------------本文结束感谢您的阅读-------------