Docker
1. 安装
- 指定yum源为清华大学镜像站(官方站也可以,不过速度太慢。)
编辑/etc/yum.repos.d/docker.repo增加以下内容:
[docker]
name=docker
enabled=1
baseurl=https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/7/x86_64/stable/
gpgcheck=0
enabled=1
执行安装:
[root@nfs yum.repos.d]# yum install -y docker-ce
安装结果:
Total 2.3 MB/s | 35 MB 00:00:14
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
Installing : pigz-2.3.4-1.el7.x86_64 1/3
Installing : 2:container-selinux-2.55-1.el7.noarch 2/3
setsebool: SELinux is disabled.
Installing : docker-ce-18.03.1.ce-1.el7.centos.x86_64 3/3
Verifying : docker-ce-18.03.1.ce-1.el7.centos.x86_64 1/3
Verifying : 2:container-selinux-2.55-1.el7.noarch 2/3
Verifying : pigz-2.3.4-1.el7.x86_64 3/3
Installed:
docker-ce.x86_64 0:18.03.1.ce-1.el7.centos
Dependency Installed:
container-selinux.noarch 2:2.55-1.el7 pigz.x86_64 0:2.3.4-1.el7
Complete!
启用服务:
[root@nfs ~]# systemctl start docker
2.查看Docker安装版本:
[root@nfs ~]# docker version
Client: #客户端版本
Version: 18.03.1-ce
API version: 1.37
Go version: go1.9.5
Git commit: 9ee9f40
Built: Thu Apr 26 07:20:16 2018
OS/Arch: linux/amd64
Experimental: false
Orchestrator: swarm
Server: #服务端版本
Engine:
Version: 18.03.1-ce
API version: 1.37 (minimum version 1.12)
Go version: go1.9.5
Git commit: 9ee9f40
Built: Thu Apr 26 07:23:58 2018
OS/Arch: linux/amd64
Experimental: false
查看更多信息:太长,有空了再翻译
[root@nfs ~]# docker info
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 18.03.1-ce
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins: #插件
Volume: local #本地卷
Network: bridge host macvlan null overlay
#支持的网络类型:bridge host macvlan(借助mac技术构建的vlan) null overlay(叠加网络)
Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 773c489c9c1b21a6d78b5c538cd395416ec50f88
runc version: 4fc53a81fb7c994640722ac585fa9ca548971871
init version: 949e6fa
Security Options:
seccomp
Profile: default
Kernel Version: 3.10.0-862.3.3.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 7.622GiB
Name: nfs.lxk.com
ID: KXW3:MYH3:A64H:7GZX:WEHB:AN7I:MM77:RNBO:QSXN:QCKI:HU6P:5SPI
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Live Restore Enabled: false
查看命令帮助:
[root@nfs ~]# docker -h
Flag shorthand -h has been deprecated, please use --help
Usage: docker COMMAND
A self-sufficient runtime for containers
Options:
--config string Location of client config files (default "/root/.docker")
-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:
config Manage Docker configs
container Manage containers
image Manage images
network Manage networks
node Manage Swarm nodes
plugin Manage plugins
secret Manage Docker secrets
service Manage services
swarm Manage Swarm
system Manage Docker
trust Manage trust on Docker images
volume Manage volumes
3. 配置阿里云镜像加速器
登录阿里云 --> 容器服务 --> 市场 --> 镜像 --> 容器镜像控制台 --> 镜像加速器
在镜像加速器下会看到专属加速器地址。
- 配置Docker镜像加速器:
- 需Docker客户端版本大于1.10.0
- 修改daemon配置文件/etc/docker/daemon.json
- 把阿里云专属加速器地址填入/etc/docker/daemon.json即可。
[root@nfs ~]# mkdir -p /etc/docker
[root@nfs ~]# tee /etc/docker/daemon.json <<-'EOF'
> {
> "registry-mirrors": ["https://bugdjqkt.mirror.aliyuncs.com"]
> }
> EOF
{
"registry-mirrors": ["https://bugdjqkt.mirror.aliyuncs.com"]
}
[root@nfs ~]# cat /etc/docker/daemon.json
{
"registry-mirrors": ["https://bugdjqkt.mirror.aliyuncs.com"]
}
[root@nfs ~]# systemctl daemon-reload
[root@nfs ~]# systemctl restart docker
[root@nfs ~]# echo $?
0
3.2 下载一个Docker镜像:
注意:如果开了代理可能会影响下载镜像
docker pull 用法:
[root@nfs ~]# 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)
示例:
[root@nfs ~]# docker pull busybox #默认下载TAG为latest的
Using default tag: latest
latest: Pulling from library/busybox
07a152489297: Pull complete
Digest: sha256:141c253bc4c3fd0a201d32dc1f493bcf3fff003b6df416dea4f41046e0f37d47
Status: Downloaded newer image for busybox:latest
[root@nfs ~]# docker pull httpd:2.4 #下载latest为2.4的httpd
2.4: Pulling from library/httpd
3d77ce4481b1: Pull complete
73674f4d9403: Pull complete
d266646f40bd: Pull complete
ce7b0dda0c9f: Pull complete
01729050d692: Pull complete
014246127c67: Pull complete
7cd2e04cf570: Pull complete
Digest: sha256:72f2b4aa99235509146bd12054d1a93c1c869ba60212d21729118c93ca4305d3
Status: Downloaded newer image for httpd:2.4
查看已经下载的Dockerfile:
[root@nfs ~]# docker images -a
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest cd5239a0906a 2 weeks ago 109MB
busybox latest 8c811b4aec35 4 weeks ago 1.15MB
httpd 2.4 fb2f3851a971 8 weeks ago 178MB
hello-world latest e38bc07ac18e 2 months ago 1.85kB
4. 基本操作
docker run 参数:
--name string Assign a name to the container
#给创建的container分配一个名字
--rm Automatically remove the container when it exits
#当container退出时就自动删除 有可能与-it相冲突
-i, --interactive Keep STDIN open even if not attached
#始终打开交互式界面
-t, --tty Allocate a pseudo-TTY
#分配一个终端
--ip string IPv4 address (e.g., 172.30.100.104)
#指定IPv4地址,只支持用户自定义的网络
-d, --detach Run container in background and print container ID
#在后台运行并打印出container的ID
创建一个Container
[root@nfs ~]# docker run --name a1 -it alpine
/ # ifconfig
eth0 Link encap:Ethernet HWaddr 02:42:AC:11:00:02
inet addr:172.17.0.2 Bcast:172.17.255.255 Mask:255.255.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:6 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:508 (508.0 B) TX bytes:0 (0.0 B)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
/ # ping -c 1 -w 1 www.baidu.com
PING www.baidu.com (61.135.169.125): 56 data bytes
64 bytes from 61.135.169.125: seq=0 ttl=54 time=21.822 ms
--- www.baidu.com ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 21.822/21.822/21.822 ms
/ #
切换到另一tty查看当前正在运行的Container
[root@nfs ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
01a889819374 alpine "/bin/sh" 44 minutes ago Up 29 seconds a1
当退出Container之后,查看当前主机上的Container需要加-a选项
[root@nfs ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
01a889819374 alpine "/bin/sh" About an hour ago Up 5 minutes a1
42573024611c hello-world "/hello" About an hour ago Exited (0) About an hour ago sad_dubinsky
99b8f22ed189 hello-world "/hello" About an hour ago Exited (0) About an hour ago stupefied_keldysh
3.4 Container的基本操作
当前终端和docker终端建立连接:docker attach命令
[root@nfs ~]# 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)
启动a1再与之建立联系
[root@nfs ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@nfs ~]# docker start a1 #启用名为a1的Container
a1
[root@nfs ~]# docker ps #查看当前运行的Container
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
01a889819374 alpine "/bin/sh" About an hour ago Up 3 seconds a1
[root@nfs ~]# docker attach a1 #与a1建立联系
/ # exit #退出a1
[root@nfs ~]# docker attach a1 #与a1建立联系,提示需要先start
You cannot attach to a stopped container, start it first
[root@nfs ~]# docker start a1 #启动a1
a1
[root@nfs ~]# docker attach a1 #与a1建立联系
/ #
Container建立之后会自动创建一个网卡
vethc37c497: flags=4163 mtu 1500
inet6 fe80::d07b:57ff:fe94:7191 prefixlen 64 scopeid 0x20
ether d2:7b:57:94:71:91 txqueuelen 0 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8 bytes 648 (648.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
删除容器(不会删除镜像文件)
[root@nfs ~]# 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 the volumes associated with the container
例:删除名为a1的容器
[root@nfs ~]# docker rm a1
a1
[root@nfs ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
42573024611c hello-world "/hello" 5 hours ago Exited (0) 5 hours ago sad_dubinsky
99b8f22ed189 hello-world "/hello" 5 hours ago Exited (0) 5 hours ago stupefied_keldysh
4. 查看底层容器和镜像文件的底层信息:
下载一个nginx镜像
启动nginx容器:
[root@nfs ~]# docker run --name ngx1 -d nginx # -d :启动为后台进程,不会占据当前终端
936b5ecac0abdaa9009694029cf946a05282281fcdc507ccb62c1d6566a6a885
查看正在运行的容器
[root@nfs ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
936b5ecac0ab nginx "nginx -g 'daemon of…" 52 seconds ago Up 51 seconds 80/tcp ngx1
4.1 查看Container和镜像底层信息
docker inspect:查看docker对象底层信息
可通过JSON格式返回docker对象的属性
[root@nfs ~]# docker inspect --help
Usage: docker inspect [OPTIONS] NAME|ID [NAME|ID...]
Return low-level information on Docker objects
Options:
-f, --format string Format the output using the given Go template
#只看对应格式信息
-s, --size Display total file sizes if the type is container
--type string Return JSON for specified type
查看ngx1的底层信息:
[root@nfs ~]# docker inspect ngx1
[
{
"Id": "936b5ecac0abdaa9009694029cf946a05282281fcdc507ccb62c1d6566a6a885",
"Created": "2018-06-26T14:02:22.260021481Z",
"Path": "nginx",
"Args": [
"-g",
"daemon off;"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 6759,
"ExitCode": 0,
"Error": "",
……以下省略
查看镜像文件信息:
[root@nfs ~]# docker inspect nginx:latest
[
{
"Id": "sha256:cd5239a0906a6ccf0562354852fae04bc5b52d72a2aff9a871ddb6bd57553569",
"RepoTags": [
"nginx:latest"
],
"RepoDigests": [
"nginx@sha256:3e2ffcf0edca2a4e9b24ca442d227baea7b7f0e33ad654ef1eb806fbd9bedcf0"
],
"Parent": "",
"Comment": "",
"Created": "2018-06-05T18:20:14.421990858Z",
"Container": "d2bbdbfdb590190edd92eadc4ef8a0453986e63da5f5853e451121df7da73668",
"ContainerConfig": {
"Hostname": "d2bbdbfdb590",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"80/tcp": {}
……以下省略
查看nginx镜像文件的信息:
#查看一级配置段
[root@nfs ~]# docker inspect -f {{.RepoTags}} nginx:latest
[nginx:latest]
[root@nfs ~]# docker inspect -f {{.Metadata}} nginx:latest
{0001-01-01 00:00:00 +0000 UTC}
#查看二级配置段
[root@nfs ~]# docker inspect -f {{.ContainerConfig.Hostname}} nginx:latest
d2bbdbfdb590
#查看三级配置段
[root@nfs ~]# docker inspect -f {{.GraphDriver.Data.WorkDir}} nginx:latest
/var/lib/docker/overlay2/e2c4a62d73120b51c3f30247eb79a7b3b3419bd1fec68723b16006de455c049b/work
4.2 通过exec命令提供的交互式接口查看Container信息
Run a command in a running containeer
在运行中的container中运行命令
[root@nfs ~]# 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: [:])
-w, --workdir string Working directory inside the container
查看container中nginx的配置文件,可在exec的帮助下启动一个shell进程
[root@nfs ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
936b5ecac0ab nginx "nginx -g 'daemon of…" 30 minutes ago Up 30 minutes 80/tcp ngx1
[root@nfs ~]# docker exec -it ngx1 /bin/sh
# hostname
936b5ecac0ab #此处主机名与docker ps中的主机名一致
# exit #退出之后不会关闭Container,只是退出当前交互式界面。
[root@nfs ~]# docker ps #查看当前运行的Container
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
936b5ecac0ab nginx "nginx -g 'daemon of…" 31 minutes ago Up 31 minutes 80/tcp ngx1
运行命令并退出
[root@nfs ~]# docker exec ngx1 hostname
936b5ecac0ab
4.3 查看日志
[root@nfs ~]# 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)
容器内日志记录位置:
都是链接文件,链接至stdout和stderr
[root@nfs ~]# docker exec -it ngx1 /bin/sh
# ls -l /var/log/nginx/
total 0
lrwxrwxrwx 1 root root 11 Jun 5 18:20 access.log -> /dev/stdout
lrwxrwxrwx 1 root root 11 Jun 5 18:20 error.log -> /dev/stderr
为运行nginx的Container生成一条访问日志并查看:
#查看ngx1的IP地址
[root@nfs ~]# docker inspect ngx1 -f {{.NetworkSettings.IPAddress}}
172.17.0.2
[root@nfs ~]# curl 172.17.0.2
Welcome to nginx!
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.
For online documentation and support please refer to
nginx.org.
Commercial support is available at
nginx.com.
Thank you for using nginx.
[root@nfs ~]# curl -I 172.17.0.2
HTTP/1.1 200 OK
Server: nginx/1.15.0
Date: Tue, 26 Jun 2018 14:44:30 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 05 Jun 2018 12:00:18 GMT
Connection: keep-alive
ETag: "5b167b52-264"
Accept-Ranges: bytes
[root@nfs ~]# docker logs ngx1 #查看名为ngx1的Container的访问日志
172.17.0.1 - - [26/Jun/2018:14:44:20 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
172.17.0.1 - - [26/Jun/2018:14:44:30 +0000] "HEAD / HTTP/1.1" 200 0 "-" "curl/7.29.0" "-"
4.4 查看指定Container的资源占用情况:
[root@nfs ~]# 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)
#显示所有Container的信息,默认显示运行中的
--format string Pretty-print images using a Go template
#用Go模板打印出漂亮的样式
--no-stream Disable streaming stats and only pull the first result
#只显示第一个结果,若不加此选项,效果与watch类似。
--no-trunc Do not truncate output
#不截断输出
[root@nfs ~]# docker stats --no-stream ngx1
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
936b5ecac0ab ngx1 0.00% 1.367MiB / 7.622GiB 0.02% 1.75kB / 1.78kB 10.3MB / 0B 2
CONTAINER ID:容器ID
NAME:容器名称
CPU %:CPU使用率
MEM USAGE / LIMIT:内存使用量和限制大小,默认不限制就是宿主机整体内存
MEM %:内存使用率
NET I/O:网络IO
BLOCK I/O:磁盘IO
PIDS:不知道
4.5 top命令:
排出来容器内进程资源使用,倒序,静态显示
[root@nfs ~]# docker top --help
Usage: docker top CONTAINER [ps OPTIONS]
Display the running processes of a container
Options:
[root@nfs ~]# docker top ngx1
UID PID PPID C STIME TTY TIME CMD
root 6759 6743 0 22:02 ? 00:00:00 nginx: master process nginx -g daemon off;
101 6795 6759 0 22:02 ? 00:00:00 nginx: worker process
5. Docker Images
Docker镜像含有启动容器所需要的文件系统及内容,因此其用于创建并启动Docker容器
采用分层构建机制,最底层为bootfs,其上为rootfs
bootfs:用于系统引导的文件系统,包括bootloader和kernel,容器启动完会被卸载以节约内存资源。
rootfs:位于bootfs之上,表现为docker容器的根文件系统。
- 传统模式中,系统启动时,内核挂载rootfs时会首先将其挂载为只读模式,完整性自检完成后将其重新挂载为读写模式。
- docker中,rootfs由内核挂载为只读模式,而后通过联合挂载技术额外挂载一个可写层。
镜像文件需要先加载至本地,然后才能启动。
需要图示驱动系统支持:GraphDriver,通过overlay2实现。
在本地文件系统之上附加一个抽象层,这个抽象层专门用于存储分层文件系统。
若启动三个系统,三个系统基于镜像文件的抽象层来运行。每个容器都有自己专有的层,写操作都保存在这层之上。
创建文件就是在这层之上存放一个文件,删除就是把文件设置为隐藏。修改:写时复制。从底层复制一份,原文件隐藏,修改复制的一份。位于下层的镜像称为父镜像(parent image),最底层的称为基础镜像(base image)。
最上层为可读写层,其下均为只读层。advanced multi-layered unification filesystem:高级多层统一文件系统
用于为Linux文件系统实现联合挂载
aufs是之前的UnionFS的重新实现,2006年由Junjiro Okajima开发
Docker最初使用aufs作为容器文件系统层,它目前仍作为存储后端之一来使用
aufs的竞争产品是overlayfs,后者自从3.18版本开始被合并到Linux内核
Docker的分层镜像,除了aufs,docker还支持btrfs,devicemapper和vfs等
在Ubuntu系统下,Docker默认Ubuntu的aufs。而在CentOS 7上,用的是devicemapper
devicemapper:慢的像一坨翔分层构建和联合挂载肯定会影响性能
因为多个容器共用一个镜像文件。
5 Docker Registry
启动容器时,Docker daemon会试图从本地获取相关的镜像,本地镜像不存在时,其将从Registry中下载该镜像并保存到本地。
用户可使用自建的Registry或者使用官方的Docker Hub
分类:
- Sponsor Registry:第三方的registry,代客户和Docker社区使用
- Mirror Registry:第三方的registry,只让客户使用.如阿里云之类,用于加速
- Vendor Registry:由发布Docker镜像的供应商提供的registry
- Privant Registry:通过设有防火墙和额外的安全层的私有实体提供的registry
第三方非常著名的Registry:quay.io