一、Docker介绍与安装
1、docker概述
Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源。使用最广泛的开源容器引擎、一种操作系统级的虚拟化技术、依赖于Linux内核特性:Namespace(资源隔离)和Cgroups(资源限制)、一个简单的应用程序打包工具。
Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级、可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。容器是完全使用沙箱机制,相互之间不会有任何接口(类似 iPhone 的 app),更重要的是容器性能开销极低。
Docker 从 17.03 版本之后分为 CE(Community Edition: 社区版) 和 EE(Enterprise Edition: 企业版),我们用社区版就可以了。
2、docker的应用场景
应用程序(eg:web应用)的自动化打包和发布、应用程序的隔离。
自动化测试和持续集成、发布。
部署微服务
在服务型环境中部署和调整数据库或其他的后台应用。
从头编译或者扩展现有的 OpenShift 或 Cloud Foundry 平台来搭建自己的 PaaS 环境。
3、docker 的优点
1.简化程序:
Docker 让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,便可以实现虚拟化。Docker改变了虚拟化的方式,使开发者可以直接将自己的成果放入Docker中进行管理。方便快捷已经是 Docker的最大优势,过去需要用数天乃至数周的 任务,在Docker容器的处理下,只需要数秒就能完成。
2.避免选择恐惧症:
如果你有选择恐惧症,还是资深患者。那么你可以使用 Docker 打包你的纠结!比如 Docker 镜像;Docker 镜像中包含了运行环境和配置,所以 Docker 可以简化部署多种应用实例工作。比如 Web 应用、后台应用、数据库应用、大数据应用比如 Hadoop 集群、消息队列等等都可以打包成一个镜像部署。
3.节省开支:
一方面,云计算时代到来,使开发者不必为了追求效果而配置高额的硬件,Docker 改变了高性能必然高价格的思维定势。Docker 与云的结合,让云空间得到更充分的利用。不仅解决了硬件管理的问题,也改变了虚拟化的方式。
4、docker架构
Docker 使用客户端-服务器 (C/S) 架构模式,使用远程API来管理和创建Docker容器。
Docker 容器通过 Docker 镜像来创建。
容器与镜像的关系类似于面向对象编程中的对象与类。
Docker | 面向对象 |
---|---|
容器 | 对象 |
镜像 | 类 |
Docker 镜像(Images) |
Docker 镜像是用于创建 Docker 容器的模板。 |
Docker 容器(Container) |
容器是独立运行的一个或一组应用。 |
Docker 客户端(Client) |
Docker 客户端通过命令行或者其他工具使用 Docker API (https://docs.docker.com/reference/api/docker_remote_api) 与 Docker 的守护进程通信。 |
Docker 主机(Host) |
一个物理或者虚拟的机器用于执行 Docker 守护进程和容器。 |
Docker 仓库(Registry) |
Docker 仓库用来保存镜像,可以理解为代码控制中的代码仓库。 Docker Hub(https://hub.docker.com) 提供了庞大的镜像集合供使用。 |
Docker Machine |
Docker Machine是一个简化Docker安装的命令行工具,通过一个简单的命令行即可在相应的平台上安装Docker,比如VirtualBox、 Digital Ocean、Microsoft Azure。 |
5、容器 VS 虚拟机
常用的虚拟技术:vmware xen Hypervisor kvm virtualBOX esxi
6、二进制包安装
基础环境
1、操作系统:CentOS 7.6
2、Docker版本:https://download.docker.com/linux/static/stable/x86_64/
3、官方参考文档:https://docs.docker.com/install/linux/docker-ce/binaries/#install-static-binaries
Docker安装
步骤一:下载
1
|
wget https: //download.docker.com/linux/static/stable/x86_64/docker-18.09.4-ce.tgz |
步骤二:解压
1
|
tar -xvf docker-18.09.4-ce.tgz |
步骤三:将解压出来的docker文件内容移动到 /usr/bin/ 目录下
cp docker/* /usr/bin/
步骤四:将docker注册为service
1
|
vim /etc/systemd/system/docker.service |
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
|
[Unit] Description=Docker Application Container Engine Documentation=https: //docs.docker.com After=network-online.target firewalld.service Wants=network-online.target [Service] Type=notify # the default is not to use systemd for cgroups because the delegate issues still # exists and systemd currently does not support the cgroup feature set required # for containers run by docker ExecStart=/usr/bin/dockerd ExecReload=/bin/kill -s HUP $MAINPID # Having non-zero Limit*s causes performance problems due to accounting overhead # in the kernel. We recommend using cgroups to do container-local accounting. LimitNOFILE=infinity LimitNPROC=infinity LimitCORE=infinity # Uncomment TasksMax if your systemd version supports it. # Only systemd 226 and above support this version. #TasksMax=infinity TimeoutStartSec=0 # set delegate yes so that systemd does not reset the cgroups of docker containers Delegate=yes # kill only the docker process, not all processes in the cgroup KillMode=process # restart the docker process if it exits prematurely Restart= on -failure StartLimitBurst=3 StartLimitInterval=60s [Install] WantedBy=multi-user.target |
步骤五:启动
1
2
3
4
5
|
chmod +x /etc/systemd/system/docker.service #添加文件权限并启动docker systemctl daemon-reload #重新加载配置文件 systemctl start docker #启动Docker systemctl enable docker.service #设置开机自启 |
步骤六:验证
1
2
|
systemctl status docker #查看Docker状态 docker -v #查看Docker版本 |
7、yum安装(这里使用yum安装)
Docker版本 社区版(Community Edition,CE) 一般社区版 企业版(Enterprise Edition,EE) 支持平台 Linux(CentOS,Debian,Fedora,Oracle Linux,RHEL,SUSE和Ubuntu) Mac Windows CentOS7.x官方安装Docker文档网址 https://docs.docker.com/engine/install/centos/ [root@docker01 ~]# vim /etc/selinux/config [root@docker01 ~]# systemctl stop firewalld [root@docker01 ~]# systemctl disable firewalld #删除老版本 yum remove docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine # 安装依赖包 yum install -y yum-utils device-mapper-persistent-data lvm2 # 添加Docker软件包源 #不行的话就用阿里源http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo # 安装Docker CE yum install -y docker-ce # 启动Docker服务并设置开机启动 systemctl start docker systemctl enable docker 官方文档:https://docs.docker.com
[root@docker01 docker]# docker 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 Run 'docker COMMAND --help' for more information on a command. [root@docker01 docker]#
二、Docker镜像管理
1、镜像是什么?
•一个分层存储的文件
•一个软件的环境
•一个镜像可以创建N个容器
•一种标准化的交付
•一个不包含Linux内核而又精简的Linux操作系统
/var/lib/docker #数据目录
镜像不是一个单一的文件,而是有多层构成。我们可以通过docker history <ID/NAME> 查看镜像中各层内容及大小,每层对应着Dockerfile中的一条指令。Docker镜像默认存储在/var/lib/docker/<storage-driver>中。
[root@docker01 ~]# docker info Client: Debug Mode: false Server: Containers: 0 Running: 0 Paused: 0 Stopped: 0 Images: 0 Server Version: 19.03.8 Storage Driver: overlay2 Backing Filesystem: <unknown> Supports d_type: true Native Overlay Diff: true Logging Driver: json-file Cgroup Driver: cgroupfs Plugins: Volume: local Network: bridge host ipvlan macvlan null overlay Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog Swarm: inactive Runtimes: runc Default Runtime: runc Init Binary: docker-init containerd version: 7ad184331fa3e55e52b890ea95e65ba581ae3429 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd init version: fec3683 Security Options: seccomp Profile: default Kernel Version: 3.10.0-957.el7.x86_64 Operating System: CentOS Linux 7 (Core) OSType: linux Architecture: x86_64 CPUs: 2 Total Memory: 1.777GiB Name: docker01 ID: QEWP:RF6O:TXVH:FGSU:2FBO:VCR2:BON4:HDPR:KVJM:4W6E:O7DA:SWRC Docker Root Dir: /var/lib/docker Debug Mode: false Registry: https://index.docker.io/v1/ Labels: Experimental: false Insecure Registries: 127.0.0.0/8 Live Restore Enabled: false WARNING: bridge-nf-call-iptables is disabled WARNING: bridge-nf-call-ip6tables is disabled
[root@docker01 ~]# docker version Client: Docker Engine - Community Version: 19.03.8 API version: 1.40 Go version: go1.12.17 Git commit: afacb8b Built: Wed Mar 11 01:27:04 2020 OS/Arch: linux/amd64 Experimental: false Server: Docker Engine - Community Engine: Version: 19.03.8 API version: 1.40 (minimum version 1.12) Go version: go1.12.17 Git commit: afacb8b Built: Wed Mar 11 01:25:42 2020 OS/Arch: linux/amd64 Experimental: false containerd: Version: 1.2.13 GitCommit: 7ad184331fa3e55e52b890ea95e65ba581ae3429 runc: Version: 1.0.0-rc10 GitCommit: dc9208a3303feef5b3839f4323d9beb36df0a9dd docker-init: Version: 0.18.0 GitCommit: fec3683 [root@docker01 ~]#
2、镜像从哪里来?
Docker Hub是由Docker公司负责维护的公共注册中心,包含大量的容器镜像,Docker工具默认从这个公共镜像库下载镜像。
地址:https://hub.docker.com/explore
配置镜像加速器:https://www.daocloud.io/mirror
curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://f1361db2.m.daocloud.io
[root@docker01 ~]# curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://f1361db2.m.daocloud.io docker version >= 1.12 {"registry-mirrors": ["http://f1361db2.m.daocloud.io"]} Success. You need to restart docker to take effect: sudo systemctl restart docker [root@docker01 ~]# docker info | grep -C 3 'Registry Mirrors' #查看加速是否主策成功 Registry Mirrors: http://f1361db2.m.daocloud.io/ Live Restore Enabled: false WARNING: bridge-nf-call-iptables is disabled WARNING: bridge-nf-call-ip6tables is disabled [root@docker01 ~]# systemctl restart docker #重启服务
3、镜像与容器联系
如图,容器其实是在镜像的最上面加了一层读写层,在运行容器里文件改动时,会先从镜像里要写的文件复制到容器自己的文件系统中(读写层)。如果容器删除了,最上面的读写层也就删除了,改动也就丢失了。
所以无论多少个容器共享一个镜像,所做的写操作都是从镜像的文件系统中复制过来操作的,并不会修改镜像的源文件,这种方式提高磁盘利用率。
若想持久化这些改动,可以通过docker commit 将容器保存成一个新镜像。
UFS 联合文件系统(分层) docker三大核心之一 Namespace(资源隔离)和Cgroups(资源限制)
4、管理镜像常用操作指令
[root@docker01 docker]# docker image help #使用为了好看,镜像操作做最好加上image Usage: docker image COMMAND Manage images Commands: build Build an image from a Dockerfile history Show the history of an image import Import the contents from a tarball to create a filesystem image inspect Display detailed information on one or more images load Load an image from a tar archive or STDIN ls List images prune Remove unused images pull Pull an image or a repository from a registry push Push an image or a repository to a registry rm Remove one or more images save Save one or more images to a tar archive (streamed to STDOUT by default) tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE Run 'docker image COMMAND --help' for more information on a command.
列出所有镜像
[root@docker01 overlay2]# docker image ls #列出所镜像信息 REPOSITORY TAG IMAGE ID CREATED SIZE centos 7 9f38484d220f 5 months ago 202MB [root@docker01 overlay2]#
下载镜像
[root@docker01 ~]# docker image pull mysql:5.7 5.7: Pulling from library/mysql [DEPRECATION NOTICE] registry v2 schema1 support will be removed in an upcoming release. Please contact admins of the docker.io registry NOW to avoid future disruption. 9fc222b64b0a: Pull complete 291e388076f0: Pull complete d6634415290b: Pull complete 1f1e7d852ad4: Pull complete 125fc05f36e0: Pull complete 2aed16e5b02f: Pull complete 5fa9342b7235: Pull complete a1e72cc32505: Pull complete 81225f74ecbe: Pull complete b9a45d065520: Pull complete a3e7b2fe9950: Pull complete Digest: sha256:8fbb73711ebcdd8a76d34b0bbeef80b5b7ef8ca43edbdbc213cede5654ec7b81 Status: Downloaded newer image for mysql:5.7 docker.io/library/mysql:5.7
拉取镜像并查看分层信息
[root@docker01 ~]# docker pull nginx:1.15 1.15: Pulling from library/nginx 743f2d6c1f65: Pulling fs layer 6bfc4ec4420a: Pulling fs layer 688a776db95f: Pulling fs layer 1.15: Pulling from library/nginx 743f2d6c1f65: Pull complete 6bfc4ec4420a: Pull complete 688a776db95f: Pull complete Digest: sha256:23b4dcdf0d34d4a129755fc6f52e1c6e23bb34ea011b315d87e193033bcd1b68 Status: Downloaded newer image for nginx:1.15 docker.io/library/nginx:1.15 [root@docker01 ~]# [root@docker01 ~]# docker history nginx:1.15 #镜像是分层的 IMAGE CREATED CREATED BY SIZE COMMENT 53f3fd8007f7 12 months ago /bin/sh -c #(nop) CMD ["nginx" "-g" "daemon… 0B <missing> 12 months ago /bin/sh -c #(nop) STOPSIGNAL SIGTERM 0B <missing> 12 months ago /bin/sh -c #(nop) EXPOSE 80 0B <missing> 12 months ago /bin/sh -c ln -sf /dev/stdout /var/log/nginx… 22B <missing> 12 months ago /bin/sh -c set -x && apt-get update && apt… 54.1MB <missing> 12 months ago /bin/sh -c #(nop) ENV NJS_VERSION=1.15.12.0… 0B <missing> 12 months ago /bin/sh -c #(nop) ENV NGINX_VERSION=1.15.12… 0B <missing> 12 months ago /bin/sh -c #(nop) LABEL maintainer=NGINX Do… 0B <missing> 12 months ago /bin/sh -c #(nop) CMD ["bash"] 0B <missing> 12 months ago /bin/sh -c #(nop) ADD file:fcb9328ea4c115670… 55.3MB [root@docker01 ~]#
[root@docker01 docker]# docker search nginx #查看配置的镜像仓库 所有的nginx相关的 NAME DESCRIPTION STARS OFFICIAL AUTOMATED nginx Official build of Nginx. 13103 [OK] jwilder/nginx-proxy Automated Nginx reverse proxy for docker con… 1786 [OK] richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable of… 771 [OK] linuxserver/nginx An Nginx container, brought to you by LinuxS… 107 bitnami/nginx Bitnami nginx Docker Image 83 [OK] tiangolo/nginx-rtmp Docker image with Nginx using the nginx-rtmp… 70 [OK] jc21/nginx-proxy-manager Docker container for managing Nginx proxy ho… 54 nginxdemos/hello NGINX webserver that serves a simple page co… 48 [OK] jlesage/nginx-proxy-manager Docker container for Nginx Proxy Manager 39 [OK] nginx/unit NGINX Unit is a dynamic web and application … 37 nginx/nginx-ingress NGINX Ingress Controller for Kubernetes 29 privatebin/nginx-fpm-alpine PrivateBin running on an Nginx, php-fpm & Al… 24 [OK] schmunk42/nginx-redirect A very simple container to redirect HTTP tra… 18 [OK] nginxinc/nginx-unprivileged Unprivileged NGINX Dockerfiles 14 centos/nginx-18-centos7 Platform for running nginx 1.8 or building n… 13 centos/nginx-112-centos7 Platform for running nginx 1.12 or building … 13 blacklabelops/nginx Dockerized Nginx Reverse Proxy Server. 13 [OK] nginx/nginx-prometheus-exporter NGINX Prometheus Exporter 12 raulr/nginx-wordpress Nginx front-end for the official wordpress:f… 12 [OK] sophos/nginx-vts-exporter Simple server that scrapes Nginx vts stats a… 7 [OK] mailu/nginx Mailu nginx frontend 6 [OK] bitnami/nginx-ingress-controller Bitnami Docker Image for NGINX Ingress Contr… 5 [OK] wodby/nginx Generic nginx 1 [OK] ansibleplaybookbundle/nginx-apb An APB to deploy NGINX 1 [OK] centos/nginx-110-centos7 Platform for running nginx 1.10 or building … 0 [root@docker01 docker]#
显示该镜像详细信息
[ { "Id": "sha256:9f38484d220fa527b1fb19747638497179500a1bed8bf0498eb788229229e6e1", "RepoTags": [ "centos:7" ], "RepoDigests": [ "centos@sha256:a799dd8a2ded4a83484bbae769d97655392b3f86533ceb7dd96bbac929809f3c" ], "Parent": "", "Comment": "", "Created": "2019-03-14T21:19:53.361167852Z", "Container": "958baf5225f586da9c70a21e911a0a875402dd22d83133d78b3b3aa6130e7892", "ContainerConfig": { "Hostname": "958baf5225f5", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd": [ "/bin/sh", "-c", "#(nop) ", "CMD ["/bin/bash"]" ], "ArgsEscaped": true, "Image": "sha256:294e8d8145287e70f07328cc09d840fad8980b801223321b983442f097aff0d8", "Volumes": null, "WorkingDir": "", "Entrypoint": null, "OnBuild": null, "Labels": { "org.label-schema.build-date": "20190305", "org.label-schema.license": "GPLv2", "org.label-schema.name": "CentOS Base Image", "org.label-schema.schema-version": "1.0", "org.label-schema.vendor": "CentOS" } }, "DockerVersion": "18.06.1-ce", "Author": "", "Config": { "Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd": [ "/bin/bash" ], "ArgsEscaped": true, "Image": "sha256:294e8d8145287e70f07328cc09d840fad8980b801223321b983442f097aff0d8", "Volumes": null, "WorkingDir": "", "Entrypoint": null, "OnBuild": null, "Labels": { "org.label-schema.build-date": "20190305", "org.label-schema.license": "GPLv2", "org.label-schema.name": "CentOS Base Image", "org.label-schema.schema-version": "1.0", "org.label-schema.vendor": "CentOS" } }, "Architecture": "amd64", "Os": "linux", "Size": 201782942, "VirtualSize": 201782942, "GraphDriver": { "Data": { "MergedDir": "/var/lib/docker/overlay2/20f145b94417a6bdb98b3f99679455f43957dc1af24ff157f4d73dc78dbb920a/merged", "UpperDir": "/var/lib/docker/overlay2/20f145b94417a6bdb98b3f99679455f43957dc1af24ff157f4d73dc78dbb920a/diff", "WorkDir": "/var/lib/docker/overlay2/20f145b94417a6bdb98b3f99679455f43957dc1af24ff157f4d73dc78dbb920a/work" }, "Name": "overlay2" }, "RootFS": { "Type": "layers", "Layers": [ "sha256:d69483a6face4499acb974449d1303591fcbb5cdce5420f36f8a6607bda11854" ] }, "Metadata": { "LastTagTime": "0001-01-01T00:00:00Z" } } ]
镜像的导入导出删除
[root@docker01 ~]# docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE centos 7 9f38484d220f 5 months ago 202MB [root@docker01 ~]# docker image save centos:7 > centos7.tar #导出镜像 [root@docker01 ~]# du -sh centos7.tar 200M centos7.tar [root@docker01 ~]# docker image rm centos:7 #删除镜像 Untagged: centos:7 Untagged: centos@sha256:a799dd8a2ded4a83484bbae769d97655392b3f86533ceb7dd96bbac929809f3c Deleted: sha256:9f38484d220fa527b1fb19747638497179500a1bed8bf0498eb788229229e6e1 Deleted: sha256:d69483a6face4499acb974449d1303591fcbb5cdce5420f36f8a6607bda11854 [root@docker01 ~]# docker image load < centos7.tar #导入镜像 d69483a6face: Loading layer [==================================================>] 209.5MB/209.5MB Loaded image: centos:7
删除所有的镜像
docker rmi $(docker images -q) 或者 [root@docker01 ~]# docker rm -f $(docker image ls | awk '{if (NR>1){print $3}}')