1、Docker介绍
1.1 帮助网站
docker 官网: http://www.docker.com
帮助文档链接: https://docs.docker.com/
docker 镜像: https://hub.docker.com/
docker 中文网站: http://www.docker.org.cn/
1.2Docker组成
Docker 主机(Host): 一个物理机或虚拟机,用于运行Docker服务进程和容器,也称为宿主机,node节点
Docker 服务端(Server): Docker守护进程,运行docker容器
Docker 客户端(Client): 客户端使用 docker 命令或其他工具调用docker API
Docker 镜像(Images): 镜像可以理解为创建实例使用的模板,本质上就是一些程序文件的集合
Docker 仓库(Registry): 保存镜像的仓库,官方仓库: https://hub.docker.com/,可以搭建私有仓库harbor
Docker 容器(Container): 容器是从镜像生成对外提供服务的一个或一组服务,其本质就是将镜像中的程序启动后生成的进程
1.3Namespace
namespace是Linux系统的底层概念,在内核层实现,即有一些不同类型的命名空间被部署在核内,各个docker容器运行在同一个docker主进程并且共用同一个宿主机系统内核,各docker容器运行在宿主机的用户空间,每个容器都要有类似于虚拟机一样的相互隔离的运行空间,但是容器技术是在一个进程内实现运行指定服务的运行环境,并且还可以保护宿主机内核不受其他进程的干扰和影响,如文件系统空间、网络空间、进程空间等,目前主要通过以下技术实现容器运行空间的相互隔离:
隔离类型 | 功能 | 系统调用参数 | 内核版本 |
---|---|---|---|
MNT Namespace(mount) | 提供磁盘挂载点和文件系统的隔离能力 | CLONE_NEWNS | 2.4.19 |
IPC Namespace(Inter-Process Communication) | 提供进程间通信的隔离能力,包括信号量,消息队列和共享内存 | CLONE_NEWIPC | 2.6.19 |
UTS Namespace(UNIX Timesharing System) | 提供内核,主机名和域名隔离能力 | CLONE_NEWUTS | 2.6.19 |
PID Namespace(Process Identification) | 提供进程隔离能力 | CLONE_NEWPID | 2.6.24 |
Net Namespace(network) | 提供网络隔离能力,包括网络设备,网络栈,端口等 | CLONE_NEWNET | 2.6.29 |
User Namespace(user) | 提供用户隔离能力,包括用户和组 | CLONE_NEWUSER | 3.8 |
1.4 Control groups
如果不对一个容器做任何资源限制,则宿主机会允许其占用无限大的内存空间,有时候会因为代码bug程序会一直申请内存,直到把宿主机内存占完,为了避免此类的问题出现,宿主机有必要对容器进行资源分配限制,比如CPU、内存等
Cgroups 最主要的作用,就是限制一个进程组能够使用的资源上限,包括CPU、内存、磁盘、网络带宽等等。此外,还能够对进程进行优先级设置,资源的计量以及资源的控制(比如:将进程挂起和恢复等操作)。
Cgroups在内核层默认已经开启,从CentOS 和 Ubuntu 不同版本对比,显然内核较新的支持的功能更多
centos7
grep -i cgroup /boot/config-3.10.0-1160.el7.x86_64
centos8
grep -i cgroup /boot/config-4.18.0-305.3.1.el8.x86_64
Ubuntu
grep CGROUP /boot/config-4.15.0-112-generic
1.5容器管理工具——docker
优势
快速部署: 短时间内可以部署成百上千个应用,更快速交付到线上
高效虚拟化: 不需要额外hypervisor支持,基于linux内核实现应用虚拟化,相比虚拟机大幅提高性能和效率
节省开支: 提高服务器利用率,降低IT支出
简化配置: 将运行环境打包保存至容器,使用时直接启动即可
环境统一: 将开发,测试,生产的应用运行环境进行标准化和统一,减少环境不一样带来的各种问题
快速迁移和扩展: 可实现跨平台运行在物理机、虚拟机、公有云等环境,良好的兼容性可以方便将应用从A宿主机迁移到B宿主机,甚至是A平台迁移到B平台
更好的实现面向服务的架构,推荐一个容器只运行一个应用,实现分布的应用模型,可以方便的进行横向扩展,符合开发中高内聚,低耦合的要求,减少不同服务之间的相互影响
缺点
多个容器共用宿主机的内核,各应用之间的隔离不如虚拟机彻底
由于和宿主机之间的进程也是隔离的,需要进入容器查看和调试容器内进程等资源,变得比较困难和繁琐
如果容器内进程需要查看和调试,需要在每个容器内都需要安装相应的工具,这也造成存储空间的重复浪费
1.6容器的核心技术
容器规范
容器技术除了的docker之外,还有coreOS的rkt,还有阿里的Pouch,为了保证容器生态的标准性和健康可持续发展,包括Linux 基金会、Docker、微软、红帽谷歌和、IBM、等公司在2015年6月共同成立了一个叫Open Container Initiative(OCI)的组织,其目的就是制定开放的标准的容器规范,目前OCI一共发布了两个规范,分别是runtime spec和 image format spec,有了这两个规范,不同的容器公司开发的容器只要兼容这两个规范,就可以保证容器的可移植性和相互可操作性。
容器runtime
runtime是真正运行容器的地方,因此为了运行不同的容器runtime需要和操作系统内核紧密合作相互在支持,以便为容器提供相应的运行环境
- runtime 类型:
Lxc: linux上早期的runtime,在 2013 年 Docker 刚发布的时候,就是采用lxc作为runtime, Docker把 LXC 复杂的容器创建与使用方式简化为 Docker 自己的一套命令体系。随着Docker的发展,原有的LXC不能满足Docker的需求,比如跨平台功能 - Libcontainer: 随着 Docker 的不断发展,重新定义容器的实现标准,将底层实现都抽象化到Libcontainer 的接口。这就意味着,底层容器的实现方式变成了一种可变的方案,无论是使用namespace、cgroups 技术抑或是使用 systemd 等其他方案,只要实现了 Libcontainer 定义的一组接口,Docker 都可以运行。这也为 Docker 实现全面的跨平台带来了可能。
- runc: 早期libcontainer是Docker公司控制的一个开源项目,OCI的成立后,Docker把libcontainer项目移交给了OCI组织,runC就是在libcontainer的基础上进化而来,目前Docker默认的runtime,runc遵守OCI规范
- rkt: 是CoreOS开发的容器runtime,也符合OCI规范,所以使用rktruntime也可以运行Docker容器
查看docker的runtime
docker info
容器管理工具
管理工具连接runtime与用户,对用户提供图形或命令方式操作,然后管理工具将用户操作传递给runtime执行。
- lxc 是lxd 的管理工具
- Runc的管理工具是docker engine,docker engine包含后台deamon和cli两部分,大家经常提到的Docker就是指的docker engine
- Rkt的管理工具是rkt cli
容器定义工具
容器定义工具允许用户定义容器的属性和内容,以方便容器能够被保存、共享和重建。
Docker image: 是docker 容器的模板,runtime依据docker image创建容器
Dockerfile: 包含N个命令的文本文件,通过dockerfile创建出docker image
ACI(App container image): 与docker image类似,是CoreOS开发的rkt容器的镜像格式
镜像仓库 Registry
统一保存镜像而且是多个不同镜像版本的地方,叫做镜像仓库
- Docker hub: docker官方的公共仓库,已经保存了大量的常用镜像,可以方便大家直接使用
- 阿里云,网易等第三方镜像的公共仓库
- Image registry: docker 官方提供的私有仓库部署工具,无web管理界面,目前使用较少
- Harbor: vmware 提供的自带web界面自带认证功能的镜像私有仓库,目前有很多公司使用
容器编排工具
当多个容器在多个主机运行的时候,单独管理容器是相当复杂而且很容易出错,而且也无法实现某一台主机宕机后容器自动迁移到其他主机从而实现高可用的目的,也无法实现动态伸缩的功能,因此需要有一种工具可以实现统一管理、动态伸缩、故障自愈、批量执行等功能,这就是容器编排引擎
容器编排通常包括容器管理、调度、集群定义和服务发现等功能
- Docker compose : docker 官方实现单机的容器的编排工具
- Docker swarm: docker 官方开发的容器编排引擎,支持overlay network
- Mesos+Marathon: Mesos是Apache下的开源分布式资源管理框架,它被称为是分布式系统的内核。Mesos最初是由加州大学伯克利分校的AMPLab开发的,后在Twitter得到广泛使用。通用的集群组员调度平台,mesos(资源分配)与marathon(容器编排平台)一起提供容器编排引擎功能
- Kubernetes: google领导开发的容器编排引擎,内部项目为Borg,且其同时支持 docker 和CoreOS,当前已成为容器编排工具事实上的标准
docker(容器)的依赖技术
容器网络:
docker自带的网络docker network仅支持管理单机的容器网络,当多主机运行的时候需要使用第三方开源网络,例如:calico、flannel等
服务发现:
容器的动态扩容特性决定了容器IP也会随之变化,因此需要有一种机制开源自动识别并将用户请求动态转发到新创建的容器上,kubernetes自带服务发现功能,需要结合kube-dns服务解析内部域名
容器监控:
可以通过原生命令docker ps/top/stats 查看容器运行状态,另外也可以使用Prometheus 、heapster等第三方监控工具监控容器的运行状态
数据管理:
容器的动态迁移会导致其在不同的Host之间迁移,因此如何保证与容器相关的数据也能随之迁移或随时访问,可以使用逻辑卷/存储挂载等方式解决
日志收集:
docker 原生的日志查看工具docker logs,但是容器内部的日志需要通过ELK等专门的日志收集分析和展示工具进行处理
2、Docker安装及基础命令介绍
2.1Docker安装准备
官方网址: https://www.docker.com/
OS系统版本选择:
Docker 目前已经支持多种操作系统的安装运行,比如Ubuntu、CentOS、Redhat、Debian、Fedora,甚至是还支持了Mac和Windows,在linux系统上需要内核版本在3.10或以上
Docker版本选择:
docker版本号之前一直是0.X版本或1.X版本,但是从2017年3月1号开始改为每个季度发布一次稳定版,其版本号规则也统一变更为YY.MM,例如17.09表示是2017年9月份发布的
Docker之前没有区分版本,但是2017年推出(将docker更名为)新的项目Moby,github地址: https://github.com/moby/moby,Moby项目属于Docker项目的全新上游,Docker将是一个隶属于的Moby的子产品,而且之后的版本之后开始区分为 CE(Docker Community Edition,社区版本)和EE(Docker Enterprise Edition,企业收费版),CE社区版本和EE企业版本都是每个季度发布一个新版本,但是EE版本提供后期安全维护1年,而CE版本是4个月,以下为官方原文:
https://blog.docker.com/2017/03/docker-enterprise-edition/
如果要布署到kubernets上,需要查看相关kubernets对docker版本要求的说明,查看kubernets支持的docker版本比如:
https://github.com/kubernetes/kubernetes/blob/v1.17.2/CHANGELOG-1.17.md
2.2 安装和删除方法
官方文档 : https://docs.docker.com/engine/install/
阿里云文档: https://developer.aliyun.com/mirror/docker-ce?spm=a2c6h.13651102.0.0.3e221b11guHCWE
2.2.1 Ubuntu 安装和删除Docker
官方文档: https://docs.docker.com/install/linux/docker-ce/ubuntu/
Ubuntu 14.04/16.04/18.04 安装docker
#更新apt包索引,并安装包以允许apt若要在HTTPS上使用镜像仓库
sudo apt-get update
sudo apt-get -y install \
ca-certificates \
curl \
gnupg \
lsb-release
#安装GPG证书
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
#写入软件源信息(lsb_release -cs表示稳定版)
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
#更新并安装Docker-CE
sudo apt-get -y update
sudo apt-get install docker-ce docker-ce-cli containerd.io
注意:这里使用阿里云的文档进行安装出现报错
并且没有成功解决,就使用官方文档进行安装了
删除docker
[root@ubuntu ~]#apt purge docker-ce
[root@ubuntu ~]#rm -rf /var/lib/docker
2.2.2centos安装和删除docker
官方文档: https://docs.docker.com/install/linux/docker-ce/centos/
CentOS 6 因内核太旧,即使支持安装docker,但会有各种问题,不建议安装
CentOS 7 的 extras 源虽然可以安装docker,但包比较旧,建议从官方源或镜像源站点下载安装docker
CentOS 8 有新技术 podman 代替 docker
因此建议在CentOS 7 上安装 docker
下载rpm包安装
官方rpm包下载地址:
https://download.docker.com/linux/centos/7/x86_64/stable/Packages/
阿里镜像下载地址:
https://mirrors.aliyun.com/docker-ce/linux/centos/7/x86_64/stable/Packages/
通过yum源安装
由于官网的yum源太慢,下面使用阿里云的Yum源进行安装
阿里云说明: https://developer.aliyun.com/mirror/docker-ce?spm=a2c6h.13651102.0.0.3e221b11sUMKNV
方案一:
rm -rf /etc/yum.repos.d/*
#CentOS 7 安装docker依赖三个yum源:Base,Extras,docker-ce
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum clean all
yum -y install docker-ce
systemctl enable --now docker
方案二(阿里云说明中的流程):
# step 1: 安装必要的一些系统工具
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
# Step 2: 添加软件源信息
sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# Step 3:修改仓库源信息
sudo sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo
# Step 4: 更新并安装Docker-CE
sudo yum makecache fast
sudo yum -y install docker-ce
# Step 4: 开启Docker服务
sudo service docker start
# 注意:
# 官方软件源默认启用了最新的软件,您可以通过编辑软件源的方式获取各个版本的软件包。例如官方并没有将测试版本的软件源置为可用,您可以通过以下方式开启。同理可以开启各种测试版本等。
# vim /etc/yum.repos.d/docker-ce.repo
# 将[docker-ce-test]下方的enabled=0修改为enabled=1
#
# 安装指定版本的Docker-CE:
# Step 1: 查找Docker-CE的版本:
# yum list docker-ce.x86_64 --showduplicates | sort -r
# Loading mirror speeds from cached hostfile
# Loaded plugins: branch, fastestmirror, langpacks
# docker-ce.x86_64 17.03.1.ce-1.el7.centos docker-ce-stable
# docker-ce.x86_64 17.03.1.ce-1.el7.centos @docker-ce-stable
# docker-ce.x86_64 17.03.0.ce-1.el7.centos docker-ce-stable
# Available Packages
# Step2: 安装指定版本的Docker-CE: (VERSION例如上面的17.03.0.ce.1-1.el7.centos)
# sudo yum -y install docker-ce-[VERSION]
#示例
[root@centos7 ~]#yum -y install docker-ce-19.03.12-3.el7
方案三(centos8配置本地yum源):
[root@centos8 ~]#tee /etc/yum.repos.d/docker.repo <<EOF
[docker]
name=docker
gpgcheck=0
baseurl=https://mirrors.aliyun.com/docker-ce/linux/centos/8/x86_64/stable/
EOF
[root@centos8 ~]#dnf -y install docker-ce
centos8安装docker出现的常见问题:
解决方案:
因为在centos8中podman替换了docker,所以直接安装docker其实是在安装podman所以此时需要使用allowerasing参数允许删除已安装的软件包来解决依赖关系
删除docker
[root@centos7 ~]#yum remove docker-ce
#删除docker资源存放的相关文件
[root@centos7 ~]#rm -rf /var/lib/docker
2.2.3二进制安装
本方法适用于无法上网或无法通过包安装方式安装的主机上安装docker
安装文档: https://docs.docker.com/install/linux/docker-ce/binaries/
二进制安装下载路径
https://download.docker.com/linux/
https://mirrors.aliyun.com/docker-ce/linux/static/stable/x86_64/
范例: 在CentOS8上实现二进制安装docker
#下载安装包
[root@localhost ~]#wget https://mirrors.aliyun.com/docker-ce/linux/static/stable/x86_64/docker-19.03.15.tgz
#安装包解压
[root@localhost ~]#mkdir /root/test
[root@localhost ~]#tar xvf docker-19.03.15.tgz -C test/
docker/
docker/dockerd
docker/docker-proxy
docker/containerd-shim
docker/docker-init
docker/docker
docker/runc
docker/ctr
docker/containerd
#将二进制文件移动到可执行路径上的某个目录,例如/usr/bin/。 如果跳过此步骤,则必须在调用docker或dockerd命令时提供可执行文件的路径
[root@localhost ~]#cp test/docker/* /usr/bin/
#启动dockerd服务(后台运行docked ,不管输出是正确的还是错误的,都丢到黑洞里面)
[root@localhost ~]#dockerd &>/dev/null &
#版本查看
[root@localhost ~]#docker version
Client: Docker Engine - Community
Version: 19.03.15
API version: 1.40
Go version: go1.13.15
Git commit: 99e3ed8
Built: Sat Jan 30 03:11:43 2021
OS/Arch: linux/amd64
Experimental: false
Server: Docker Engine - Community
Engine:
Version: 19.03.15
API version: 1.40 (minimum version 1.12)
Go version: go1.13.15
Git commit: 99e3ed8
Built: Sat Jan 30 03:18:13 2021
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: v1.3.9
GitCommit: ea765aba0d05254012b0b9e595e995c09186427f
runc:
Version: 1.0.0-rc10
GitCommit: dc9208a3303feef5b3839f4323d9beb36df0a9dd
docker-init:
Version: 0.18.0
GitCommit: fec3683
[root@centos8 ~]#pstree -p
systemd(1)─┬─NetworkManager(660)─┬─{NetworkManager}(669)
│ └─{NetworkManager}(671)
├─VGAuthService(662)
├─agetty(718)
├─atd(712)
├─auditd(625)───{auditd}(627)
├─automount(905)─┬─{automount}(912)
│ ├─{automount}(913)
│ ├─{automount}(930)
│ └─{automount}(937)
├─containerd(679)─┬─{containerd}(693)
│ ├─{containerd}(694)
│ ├─{containerd}(696)
│ ├─{containerd}(704)
│ ├─{containerd}(705)
│ ├─{containerd}(707)
│ └─{containerd}(708)
├─crond(713)
├─dbus-daemon(658)
├─dockerd(908)─┬─{dockerd}(922)
│ ├─{dockerd}(923)
│ ├─{dockerd}(925)
│ ├─{dockerd}(944)
│ ├─{dockerd}(1028)
│ ├─{dockerd}(1100)
│ └─{dockerd}(1114)
├─polkitd(659)─┬─{polkitd}(670)
│ ├─{polkitd}(672)
│ ├─{polkitd}(677)
│ ├─{polkitd}(678)
│ └─{polkitd}(701)
├─rngd(664)───{rngd}(666)
├─rsyslogd(906)─┬─{rsyslogd}(911)
│ └─{rsyslogd}(914)
├─sshd(675)───sshd(1370)───sshd(1382)───bash(1383)───pstree(1441)
├─sssd(661)─┬─sssd_be(688)
│ └─sssd_nss(703)
├─systemd(1373)───(sd-pam)(1376)
├─systemd-journal(551)
├─systemd-logind(709)
├─systemd-udevd(580)
├─tuned(674)─┬─{tuned}(915)
│ ├─{tuned}(934)
│ └─{tuned}(948)
└─vmtoolsd(663)
范例: 创建相关的service文件,此方式新版有问题
#创建docker用户组
[root@centos8 ~]#groupadd -r docker
#将Ubuntu1804或CentOS7基于包方式安装的相关文件复制到相应目录下
[root@ubuntu1804 ~]#scp /lib/systemd/system/docker.* /lib/systemd/system/containerd.service 10.0.0.8:/lib/systemd/system/
#加载服务文件,并且启动服务
[root@centos8 ~]#systemctl daemon-reload
[root@centos8 ~]#systemctl enable --now docker
2.2.4安装podman
#在CentOS8上安装docker会自动安装podman,docker工具只是一个脚本,调用了Podman
[root@centos8 ~]#dnf install docker
[root@centos8 ~]#rpm -ql podman-docker
/usr/bin/docker
[root@centos8 ~]#cat /usr/bin/docker
#!/bin/sh
[ -f /etc/containers/nodocker ] || \
echo "Emulate Docker CLI using podman. Create /etc/containers/nodocker to quiet msg." >&2
exec /usr/bin/podman "$@"
[root@centos8 ~]#podman version
Version: 1.4.2-stable2
RemoteAPI Version: 1
Go Version: go1.12.8
OS/Arch: linux/amd64
#修改拉取镜像的地址的顺序,提高速度
[root@centos8 ~]#vim /etc/containers/registries.conf
[registries.search]
registries = ['docker.io','quay.io','registry.redhat.io','registry.access.redhat.com']
2.3在不同系统上实现一键安装 docker 脚本
2.3.1基于 ubuntu 1804 的 一键安装 docker 脚本
#!/bin/bash
#Description: Install docker on Ubuntu1804
#Version:1.0
#Date:2021-11-02
COLOR="echo -e \\033[1;31m"
END="\033[m"
DOCKER_VERSION="5:19.03.5~3-0~ubuntu-bionic"
install_docker(){
#检查是否已经安装docker
dpkg -s docker-ce &> /dev/null && ${COLOR}"Docker已安装,退出"${END} && exit apt update
#如果没有安装执行下面的安装操作
sudo apt-get update
sudo apt-get -y install \
ca-certificates \
curl \
gnupg \
lsb-release
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
apt-get update
${COLOR}"Docker有以下版本"${END}
apt-cache madison docker-ce
${COLOR}"5秒后即将安装: docker-"${DOCKER_VERSION}" 版本....."${END}
${COLOR}"如果想安装其它Docker版本,请按ctrl+c键退出,修改版本再执行"${END}
sleep 5
apt -y install docker-ce=${DOCKER_VERSION} docker-ce-cli=${DOCKER_VERSION}
systemctl enable --now docker
docker version && ${COLOR}"Docker 安装成功"${END} || ${COLOR}"Docker 安装失败"${END}
}
install_docker
2.3.2基于 CentOS实现一键安装 docker 脚本
脚本一(利用阿里云的基于CentOS8的docker yum源实现)
#!/bin/bash
. /etc/init.d/functions
COLOR="echo -e \\033[1;32m"
END="\033[m"
DOCKER_VERSION="-19.03.13-3.el8"
install_docker() {
rpm -q docker-ce &> /dev/null && action "Docker已安装" && exit
${COLOR}"开始安装 Docker....."${END}
sleep 1
# step 1: 安装必要的一些系统工具
yum install -y yum-utils device-mapper-persistent-data lvm2
# Step 2: 添加软件源信息
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# Step 3:修改仓库源信息
sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo
# Step 4: 更新并安装Docker-CE
yum makecache
yum -y install docker-ce${DOCKER_VERSION} docker-ce-cli${DOCKER_VERSION}
# Step 4: 开启Docker服务
systemctl enable --now docker
# mkdir -p /etc/docker
# cat > /etc/docker/daemon.json <<EOF
#{
#"registry-mirrors": ["https://si7y70hh.mirror.aliyuncs.com"]
#}
#EOF
# systemctl enable --now docker
# docker version && ${COLOR}"Docker安装成功"${END} || ${COLOR}"Docker安装失败"${END}
}
install_docker
脚本二(基于 CentOS 7 实现一键安装docker 脚本)
#!/bin/bash
COLOR="echo -e \\033[1;31m"
END="\033[m"
VERSION="19.03.5-3.el7"
yum install -y wget
wget -P /etc/yum.repos.d/ https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo || { ${COLOR}"互联网连接失败,请检查网络配置!"${END};exit; }
yum clean all
yum -y install docker-ce-${VERSION} docker-ce-cli-${VERSION} || { ${COLOR}"Base,Extras的yum源失败,请检查yum源配置"${END};exit; }
#使用阿里做镜像加速
mkdir -p /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
"registry-mirrors": ["https://si7y70hh.mirror.aliyuncs.com"]
}
EOF
systemctl enable --now docker
docker version && ${COLOR}"Docker安装成功"${END} || ${COLOR}"Docker安装失败"${END}
2.4docker程序环境
环境配置文件(默认情况下没有这些文件,如果需要配置则自行创建文件)
/etc/sysconfig/docker-network
/etc/sysconfig/docker-storage
/etc/sysconfig/docker
Unit File:
/usr/lib/systemd/system/docker.service
docker-ce 配置文件(默认情况下不存在此文件,如果需要配置则自行创建文件):
/etc/docker/daemon.json
Docker Registry配置文件(默认情况下不存在此文件,如果需要配置则自行创建文件):
/etc/containers/registries.conf
查看Ubuntu中docker相关文件
root@ubuntu1804:/home/sx# dpkg -L docker-ce
/.
/etc
/etc/default
/etc/default/docker
/etc/init
/etc/init/docker.conf
/etc/init.d
/etc/init.d/docker
/lib
/lib/systemd
/lib/systemd/system
/lib/systemd/system/docker.service
/lib/systemd/system/docker.socket
/usr
/usr/bin
/usr/bin/docker-init
/usr/bin/docker-proxy
/usr/bin/dockerd
/usr/share
/usr/share/doc
/usr/share/doc/docker-ce
/usr/share/doc/docker-ce/README.md
/usr/share/doc/docker-ce/changelog.Debian.gz
/var
/var/lib
/var/lib/docker-engine
/var/lib/docker-engine/distribution_based_engine.json
客户端相关文件
root@ubuntu1804:/home/sx# dpkg -L docker-ce-cli
/.
/usr
/usr/bin
/usr/bin/docker
/usr/libexec
/usr/libexec/docker
/usr/libexec/docker/cli-plugins
/usr/libexec/docker/cli-plugins/docker-app
/usr/libexec/docker/cli-plugins/docker-buildx
/usr/share
/usr/share/bash-completion
/usr/share/bash-completion/completions
/usr/share/bash-completion/completions/docker
/usr/share/doc
/usr/share/doc/docker-ce-cli
/usr/share/doc/docker-ce-cli/changelog.Debian.gz
/usr/share/fish
/usr/share/fish/vendor_completions.d
/usr/share/fish/vendor_completions.d/docker.fish
/usr/share/man
/usr/share/man/man1
/usr/share/man/man1/docker-attach.1.gz
/usr/share/man/man1/docker-build.1.gz
/usr/share/man/man1/docker-builder-build.1.gz
/usr/share/man/man1/docker-builder-prune.1.gz
/usr/share/man/man1/docker-builder.1.gz
/usr/share/man/man1/docker-checkpoint-create.1.gz
/usr/share/man/man1/docker-checkpoint-ls.1.gz
/usr/share/man/man1/docker-checkpoint-rm.1.gz
/usr/share/man/man1/docker-checkpoint.1.gz
/usr/share/man/man1/docker-commit.1.gz
/usr/share/man/man1/docker-config-create.1.gz
/usr/share/man/man1/docker-config-inspect.1.gz
/usr/share/man/man1/docker-config-ls.1.gz
/usr/share/man/man1/docker-config-rm.1.gz
/usr/share/man/man1/docker-config.1.gz
/usr/share/man/man1/docker-container-attach.1.gz
/usr/share/man/man1/docker-container-commit.1.gz
/usr/share/man/man1/docker-container-cp.1.gz
/usr/share/man/man1/docker-container-create.1.gz
/usr/share/man/man1/docker-container-diff.1.gz
/usr/share/man/man1/docker-container-exec.1.gz
/usr/share/man/man1/docker-container-export.1.gz
/usr/share/man/man1/docker-container-inspect.1.gz
/usr/share/man/man1/docker-container-kill.1.gz
/usr/share/man/man1/docker-container-logs.1.gz
/usr/share/man/man1/docker-container-ls.1.gz
/usr/share/man/man1/docker-container-pause.1.gz
/usr/share/man/man1/docker-container-port.1.gz
/usr/share/man/man1/docker-container-prune.1.gz
/usr/share/man/man1/docker-container-rename.1.gz
/usr/share/man/man1/docker-container-restart.1.gz
/usr/share/man/man1/docker-container-rm.1.gz
/usr/share/man/man1/docker-container-run.1.gz
/usr/share/man/man1/docker-container-start.1.gz
/usr/share/man/man1/docker-container-stats.1.gz
/usr/share/man/man1/docker-container-stop.1.gz
/usr/share/man/man1/docker-container-top.1.gz
/usr/share/man/man1/docker-container-unpause.1.gz
/usr/share/man/man1/docker-container-update.1.gz
/usr/share/man/man1/docker-container-wait.1.gz
/usr/share/man/man1/docker-container.1.gz
/usr/share/man/man1/docker-context-create.1.gz
/usr/share/man/man1/docker-context-export.1.gz
/usr/share/man/man1/docker-context-import.1.gz
/usr/share/man/man1/docker-context-inspect.1.gz
/usr/share/man/man1/docker-context-ls.1.gz
/usr/share/man/man1/docker-context-rm.1.gz
/usr/share/man/man1/docker-context-update.1.gz
/usr/share/man/man1/docker-context-use.1.gz
/usr/share/man/man1/docker-context.1.gz
/usr/share/man/man1/docker-cp.1.gz
/usr/share/man/man1/docker-create.1.gz
/usr/share/man/man1/docker-deploy.1.gz
/usr/share/man/man1/docker-diff.1.gz
/usr/share/man/man1/docker-engine-activate.1.gz
/usr/share/man/man1/docker-engine-check.1.gz
/usr/share/man/man1/docker-engine-update.1.gz
/usr/share/man/man1/docker-engine.1.gz
/usr/share/man/man1/docker-events.1.gz
/usr/share/man/man1/docker-exec.1.gz
/usr/share/man/man1/docker-export.1.gz
/usr/share/man/man1/docker-history.1.gz
/usr/share/man/man1/docker-image-build.1.gz
/usr/share/man/man1/docker-image-history.1.gz
/usr/share/man/man1/docker-image-import.1.gz
/usr/share/man/man1/docker-image-inspect.1.gz
/usr/share/man/man1/docker-image-load.1.gz
/usr/share/man/man1/docker-image-ls.1.gz
/usr/share/man/man1/docker-image-prune.1.gz
/usr/share/man/man1/docker-image-pull.1.gz
/usr/share/man/man1/docker-image-push.1.gz
/usr/share/man/man1/docker-image-rm.1.gz
/usr/share/man/man1/docker-image-save.1.gz
/usr/share/man/man1/docker-image-tag.1.gz
/usr/share/man/man1/docker-image.1.gz
/usr/share/man/man1/docker-images.1.gz
/usr/share/man/man1/docker-import.1.gz
/usr/share/man/man1/docker-info.1.gz
/usr/share/man/man1/docker-inspect.1.gz
/usr/share/man/man1/docker-kill.1.gz
/usr/share/man/man1/docker-load.1.gz
/usr/share/man/man1/docker-login.1.gz
/usr/share/man/man1/docker-logout.1.gz
/usr/share/man/man1/docker-logs.1.gz
/usr/share/man/man1/docker-manifest-annotate.1.gz
/usr/share/man/man1/docker-manifest-create.1.gz
/usr/share/man/man1/docker-manifest-inspect.1.gz
/usr/share/man/man1/docker-manifest-push.1.gz
/usr/share/man/man1/docker-manifest.1.gz
/usr/share/man/man1/docker-network-connect.1.gz
/usr/share/man/man1/docker-network-create.1.gz
/usr/share/man/man1/docker-network-disconnect.1.gz
/usr/share/man/man1/docker-network-inspect.1.gz
/usr/share/man/man1/docker-network-ls.1.gz
/usr/share/man/man1/docker-network-prune.1.gz
/usr/share/man/man1/docker-network-rm.1.gz
/usr/share/man/man1/docker-network.1.gz
/usr/share/man/man1/docker-node-demote.1.gz
/usr/share/man/man1/docker-node-inspect.1.gz
/usr/share/man/man1/docker-node-ls.1.gz
/usr/share/man/man1/docker-node-promote.1.gz
/usr/share/man/man1/docker-node-ps.1.gz
/usr/share/man/man1/docker-node-rm.1.gz
/usr/share/man/man1/docker-node-update.1.gz
/usr/share/man/man1/docker-node.1.gz
/usr/share/man/man1/docker-pause.1.gz
/usr/share/man/man1/docker-plugin-create.1.gz
/usr/share/man/man1/docker-plugin-disable.1.gz
/usr/share/man/man1/docker-plugin-enable.1.gz
/usr/share/man/man1/docker-plugin-inspect.1.gz
/usr/share/man/man1/docker-plugin-install.1.gz
/usr/share/man/man1/docker-plugin-ls.1.gz
/usr/share/man/man1/docker-plugin-push.1.gz
/usr/share/man/man1/docker-plugin-rm.1.gz
/usr/share/man/man1/docker-plugin-set.1.gz
/usr/share/man/man1/docker-plugin-upgrade.1.gz
/usr/share/man/man1/docker-plugin.1.gz
/usr/share/man/man1/docker-port.1.gz
/usr/share/man/man1/docker-ps.1.gz
/usr/share/man/man1/docker-pull.1.gz
/usr/share/man/man1/docker-push.1.gz
/usr/share/man/man1/docker-rename.1.gz
/usr/share/man/man1/docker-restart.1.gz
/usr/share/man/man1/docker-rm.1.gz
/usr/share/man/man1/docker-rmi.1.gz
/usr/share/man/man1/docker-run.1.gz
/usr/share/man/man1/docker-save.1.gz
/usr/share/man/man1/docker-search.1.gz
/usr/share/man/man1/docker-secret-create.1.gz
/usr/share/man/man1/docker-secret-inspect.1.gz
/usr/share/man/man1/docker-secret-ls.1.gz
/usr/share/man/man1/docker-secret-rm.1.gz
/usr/share/man/man1/docker-secret.1.gz
/usr/share/man/man1/docker-service-create.1.gz
/usr/share/man/man1/docker-service-inspect.1.gz
/usr/share/man/man1/docker-service-logs.1.gz
/usr/share/man/man1/docker-service-ls.1.gz
/usr/share/man/man1/docker-service-ps.1.gz
/usr/share/man/man1/docker-service-rm.1.gz
/usr/share/man/man1/docker-service-rollback.1.gz
/usr/share/man/man1/docker-service-scale.1.gz
/usr/share/man/man1/docker-service-update.1.gz
/usr/share/man/man1/docker-service.1.gz
/usr/share/man/man1/docker-stack-deploy.1.gz
/usr/share/man/man1/docker-stack-ls.1.gz
/usr/share/man/man1/docker-stack-ps.1.gz
/usr/share/man/man1/docker-stack-rm.1.gz
/usr/share/man/man1/docker-stack-services.1.gz
/usr/share/man/man1/docker-stack.1.gz
/usr/share/man/man1/docker-start.1.gz
/usr/share/man/man1/docker-stats.1.gz
/usr/share/man/man1/docker-stop.1.gz
/usr/share/man/man1/docker-swarm-ca.1.gz
/usr/share/man/man1/docker-swarm-init.1.gz
/usr/share/man/man1/docker-swarm-join-token.1.gz
/usr/share/man/man1/docker-swarm-join.1.gz
/usr/share/man/man1/docker-swarm-leave.1.gz
/usr/share/man/man1/docker-swarm-unlock-key.1.gz
/usr/share/man/man1/docker-swarm-unlock.1.gz
/usr/share/man/man1/docker-swarm-update.1.gz
/usr/share/man/man1/docker-swarm.1.gz
/usr/share/man/man1/docker-system-df.1.gz
/usr/share/man/man1/docker-system-events.1.gz
/usr/share/man/man1/docker-system-info.1.gz
/usr/share/man/man1/docker-system-prune.1.gz
/usr/share/man/man1/docker-system.1.gz
/usr/share/man/man1/docker-tag.1.gz
/usr/share/man/man1/docker-top.1.gz
/usr/share/man/man1/docker-trust-inspect.1.gz
/usr/share/man/man1/docker-trust-key-generate.1.gz
/usr/share/man/man1/docker-trust-key-load.1.gz
/usr/share/man/man1/docker-trust-key.1.gz
/usr/share/man/man1/docker-trust-revoke.1.gz
/usr/share/man/man1/docker-trust-sign.1.gz
/usr/share/man/man1/docker-trust-signer-add.1.gz
/usr/share/man/man1/docker-trust-signer-remove.1.gz
/usr/share/man/man1/docker-trust-signer.1.gz
/usr/share/man/man1/docker-trust.1.gz
/usr/share/man/man1/docker-unpause.1.gz
/usr/share/man/man1/docker-update.1.gz
/usr/share/man/man1/docker-version.1.gz
/usr/share/man/man1/docker-volume-create.1.gz
/usr/share/man/man1/docker-volume-inspect.1.gz
/usr/share/man/man1/docker-volume-ls.1.gz
/usr/share/man/man1/docker-volume-prune.1.gz
/usr/share/man/man1/docker-volume-rm.1.gz
/usr/share/man/man1/docker-volume.1.gz
/usr/share/man/man1/docker-wait.1.gz
/usr/share/man/man1/docker.1.gz
/usr/share/man/man5
/usr/share/man/man5/Dockerfile.5.gz
/usr/share/man/man5/docker-config-json.5.gz
/usr/share/man/man8
/usr/share/man/man8/dockerd.8.gz
/usr/share/zsh
/usr/share/zsh/vendor-completions
/usr/share/zsh/vendor-completions/_docker
查看centos中docker相关文件
[root@CT7test1 ~]# rpm -ql docker-ce
/usr/bin/docker-init
/usr/bin/docker-proxy
/usr/bin/dockerd
/usr/lib/systemd/system/docker.service
/usr/lib/systemd/system/docker.socket
/var/lib/docker-engine/distribution_based_engine.json
客户端相关文件
[root@CT7test1 ~]# rpm -ql docker-ce
/usr/bin/docker-init
/usr/bin/docker-proxy
/usr/bin/dockerd
/usr/lib/systemd/system/docker.service
/usr/lib/systemd/system/docker.socket
/var/lib/docker-engine/distribution_based_engine.json
[root@CT7test1 ~]# rpm -ql docker-ce-cli
/usr/bin/docker
/usr/libexec/docker/cli-plugins/docker-app
/usr/libexec/docker/cli-plugins/docker-buildx
/usr/share/bash-completion/completions/docker
/usr/share/doc/docker-ce-cli-19.03.5
/usr/share/doc/docker-ce-cli-19.03.5/LICENSE
/usr/share/doc/docker-ce-cli-19.03.5/MAINTAINERS
/usr/share/doc/docker-ce-cli-19.03.5/NOTICE
/usr/share/doc/docker-ce-cli-19.03.5/README.md
/usr/share/fish/vendor_completions.d/docker.fish
/usr/share/man/man1/docker-attach.1.gz
/usr/share/man/man1/docker-build.1.gz
/usr/share/man/man1/docker-builder-build.1.gz
/usr/share/man/man1/docker-builder-prune.1.gz
/usr/share/man/man1/docker-builder.1.gz
/usr/share/man/man1/docker-checkpoint-create.1.gz
/usr/share/man/man1/docker-checkpoint-ls.1.gz
/usr/share/man/man1/docker-checkpoint-rm.1.gz
/usr/share/man/man1/docker-checkpoint.1.gz
/usr/share/man/man1/docker-commit.1.gz
/usr/share/man/man1/docker-config-create.1.gz
/usr/share/man/man1/docker-config-inspect.1.gz
/usr/share/man/man1/docker-config-ls.1.gz
/usr/share/man/man1/docker-config-rm.1.gz
/usr/share/man/man1/docker-config.1.gz
/usr/share/man/man1/docker-container-attach.1.gz
/usr/share/man/man1/docker-container-commit.1.gz
/usr/share/man/man1/docker-container-cp.1.gz
/usr/share/man/man1/docker-container-create.1.gz
/usr/share/man/man1/docker-container-diff.1.gz
/usr/share/man/man1/docker-container-exec.1.gz
/usr/share/man/man1/docker-container-export.1.gz
/usr/share/man/man1/docker-container-inspect.1.gz
/usr/share/man/man1/docker-container-kill.1.gz
/usr/share/man/man1/docker-container-logs.1.gz
/usr/share/man/man1/docker-container-ls.1.gz
/usr/share/man/man1/docker-container-pause.1.gz
/usr/share/man/man1/docker-container-port.1.gz
/usr/share/man/man1/docker-container-prune.1.gz
/usr/share/man/man1/docker-container-rename.1.gz
/usr/share/man/man1/docker-container-restart.1.gz
/usr/share/man/man1/docker-container-rm.1.gz
/usr/share/man/man1/docker-container-run.1.gz
/usr/share/man/man1/docker-container-start.1.gz
/usr/share/man/man1/docker-container-stats.1.gz
/usr/share/man/man1/docker-container-stop.1.gz
/usr/share/man/man1/docker-container-top.1.gz
/usr/share/man/man1/docker-container-unpause.1.gz
/usr/share/man/man1/docker-container-update.1.gz
/usr/share/man/man1/docker-container-wait.1.gz
/usr/share/man/man1/docker-container.1.gz
/usr/share/man/man1/docker-context-create.1.gz
/usr/share/man/man1/docker-context-export.1.gz
/usr/share/man/man1/docker-context-import.1.gz
/usr/share/man/man1/docker-context-inspect.1.gz
/usr/share/man/man1/docker-context-ls.1.gz
/usr/share/man/man1/docker-context-rm.1.gz
/usr/share/man/man1/docker-context-update.1.gz
/usr/share/man/man1/docker-context-use.1.gz
/usr/share/man/man1/docker-context.1.gz
/usr/share/man/man1/docker-cp.1.gz
/usr/share/man/man1/docker-create.1.gz
/usr/share/man/man1/docker-deploy.1.gz
/usr/share/man/man1/docker-diff.1.gz
/usr/share/man/man1/docker-engine-activate.1.gz
/usr/share/man/man1/docker-engine-check.1.gz
/usr/share/man/man1/docker-engine-update.1.gz
/usr/share/man/man1/docker-engine.1.gz
/usr/share/man/man1/docker-events.1.gz
/usr/share/man/man1/docker-exec.1.gz
/usr/share/man/man1/docker-export.1.gz
/usr/share/man/man1/docker-history.1.gz
/usr/share/man/man1/docker-image-build.1.gz
/usr/share/man/man1/docker-image-history.1.gz
/usr/share/man/man1/docker-image-import.1.gz
/usr/share/man/man1/docker-image-inspect.1.gz
/usr/share/man/man1/docker-image-load.1.gz
/usr/share/man/man1/docker-image-ls.1.gz
/usr/share/man/man1/docker-image-prune.1.gz
/usr/share/man/man1/docker-image-pull.1.gz
/usr/share/man/man1/docker-image-push.1.gz
/usr/share/man/man1/docker-image-rm.1.gz
/usr/share/man/man1/docker-image-save.1.gz
/usr/share/man/man1/docker-image-tag.1.gz
/usr/share/man/man1/docker-image.1.gz
/usr/share/man/man1/docker-images.1.gz
/usr/share/man/man1/docker-import.1.gz
/usr/share/man/man1/docker-info.1.gz
/usr/share/man/man1/docker-inspect.1.gz
/usr/share/man/man1/docker-kill.1.gz
/usr/share/man/man1/docker-load.1.gz
/usr/share/man/man1/docker-login.1.gz
/usr/share/man/man1/docker-logout.1.gz
/usr/share/man/man1/docker-logs.1.gz
/usr/share/man/man1/docker-manifest-annotate.1.gz
/usr/share/man/man1/docker-manifest-create.1.gz
/usr/share/man/man1/docker-manifest-inspect.1.gz
/usr/share/man/man1/docker-manifest-push.1.gz
/usr/share/man/man1/docker-manifest.1.gz
/usr/share/man/man1/docker-network-connect.1.gz
/usr/share/man/man1/docker-network-create.1.gz
/usr/share/man/man1/docker-network-disconnect.1.gz
/usr/share/man/man1/docker-network-inspect.1.gz
/usr/share/man/man1/docker-network-ls.1.gz
/usr/share/man/man1/docker-network-prune.1.gz
/usr/share/man/man1/docker-network-rm.1.gz
/usr/share/man/man1/docker-network.1.gz
/usr/share/man/man1/docker-node-demote.1.gz
/usr/share/man/man1/docker-node-inspect.1.gz
/usr/share/man/man1/docker-node-ls.1.gz
/usr/share/man/man1/docker-node-promote.1.gz
/usr/share/man/man1/docker-node-ps.1.gz
/usr/share/man/man1/docker-node-rm.1.gz
/usr/share/man/man1/docker-node-update.1.gz
/usr/share/man/man1/docker-node.1.gz
/usr/share/man/man1/docker-pause.1.gz
/usr/share/man/man1/docker-plugin-create.1.gz
/usr/share/man/man1/docker-plugin-disable.1.gz
/usr/share/man/man1/docker-plugin-enable.1.gz
/usr/share/man/man1/docker-plugin-inspect.1.gz
/usr/share/man/man1/docker-plugin-install.1.gz
/usr/share/man/man1/docker-plugin-ls.1.gz
/usr/share/man/man1/docker-plugin-push.1.gz
/usr/share/man/man1/docker-plugin-rm.1.gz
/usr/share/man/man1/docker-plugin-set.1.gz
/usr/share/man/man1/docker-plugin-upgrade.1.gz
/usr/share/man/man1/docker-plugin.1.gz
/usr/share/man/man1/docker-port.1.gz
/usr/share/man/man1/docker-ps.1.gz
/usr/share/man/man1/docker-pull.1.gz
/usr/share/man/man1/docker-push.1.gz
/usr/share/man/man1/docker-rename.1.gz
/usr/share/man/man1/docker-restart.1.gz
/usr/share/man/man1/docker-rm.1.gz
/usr/share/man/man1/docker-rmi.1.gz
/usr/share/man/man1/docker-run.1.gz
/usr/share/man/man1/docker-save.1.gz
/usr/share/man/man1/docker-search.1.gz
/usr/share/man/man1/docker-secret-create.1.gz
/usr/share/man/man1/docker-secret-inspect.1.gz
/usr/share/man/man1/docker-secret-ls.1.gz
/usr/share/man/man1/docker-secret-rm.1.gz
/usr/share/man/man1/docker-secret.1.gz
/usr/share/man/man1/docker-service-create.1.gz
/usr/share/man/man1/docker-service-inspect.1.gz
/usr/share/man/man1/docker-service-logs.1.gz
/usr/share/man/man1/docker-service-ls.1.gz
/usr/share/man/man1/docker-service-ps.1.gz
/usr/share/man/man1/docker-service-rm.1.gz
/usr/share/man/man1/docker-service-rollback.1.gz
/usr/share/man/man1/docker-service-scale.1.gz
/usr/share/man/man1/docker-service-update.1.gz
/usr/share/man/man1/docker-service.1.gz
/usr/share/man/man1/docker-stack-deploy.1.gz
/usr/share/man/man1/docker-stack-ls.1.gz
/usr/share/man/man1/docker-stack-ps.1.gz
/usr/share/man/man1/docker-stack-rm.1.gz
/usr/share/man/man1/docker-stack-services.1.gz
/usr/share/man/man1/docker-stack.1.gz
/usr/share/man/man1/docker-start.1.gz
/usr/share/man/man1/docker-stats.1.gz
/usr/share/man/man1/docker-stop.1.gz
/usr/share/man/man1/docker-swarm-ca.1.gz
/usr/share/man/man1/docker-swarm-init.1.gz
/usr/share/man/man1/docker-swarm-join-token.1.gz
/usr/share/man/man1/docker-swarm-join.1.gz
/usr/share/man/man1/docker-swarm-leave.1.gz
/usr/share/man/man1/docker-swarm-unlock-key.1.gz
/usr/share/man/man1/docker-swarm-unlock.1.gz
/usr/share/man/man1/docker-swarm-update.1.gz
/usr/share/man/man1/docker-swarm.1.gz
/usr/share/man/man1/docker-system-df.1.gz
/usr/share/man/man1/docker-system-events.1.gz
/usr/share/man/man1/docker-system-info.1.gz
/usr/share/man/man1/docker-system-prune.1.gz
/usr/share/man/man1/docker-system.1.gz
/usr/share/man/man1/docker-tag.1.gz
/usr/share/man/man1/docker-top.1.gz
/usr/share/man/man1/docker-trust-inspect.1.gz
/usr/share/man/man1/docker-trust-key-generate.1.gz
/usr/share/man/man1/docker-trust-key-load.1.gz
/usr/share/man/man1/docker-trust-key.1.gz
/usr/share/man/man1/docker-trust-revoke.1.gz
/usr/share/man/man1/docker-trust-sign.1.gz
/usr/share/man/man1/docker-trust-signer-add.1.gz
/usr/share/man/man1/docker-trust-signer-remove.1.gz
/usr/share/man/man1/docker-trust-signer.1.gz
/usr/share/man/man1/docker-trust.1.gz
/usr/share/man/man1/docker-unpause.1.gz
/usr/share/man/man1/docker-update.1.gz
/usr/share/man/man1/docker-version.1.gz
/usr/share/man/man1/docker-volume-create.1.gz
/usr/share/man/man1/docker-volume-inspect.1.gz
/usr/share/man/man1/docker-volume-ls.1.gz
/usr/share/man/man1/docker-volume-prune.1.gz
/usr/share/man/man1/docker-volume-rm.1.gz
/usr/share/man/man1/docker-volume.1.gz
/usr/share/man/man1/docker-wait.1.gz
/usr/share/man/man1/docker.1.gz
/usr/share/man/man5/Dockerfile.5.gz
/usr/share/man/man5/docker-config-json.5.gz
/usr/share/man/man8/dockerd.8.gz
/usr/share/zsh/vendor-completions/_docker
2.5docker命令帮助
docker 命令是最常使用的docker 客户端命令,其后面可以加不同的参数以实现不同的功能
docker 命令格式
docker [OPTIONS] COMMAND
COMMAND分为
Management Commands #指定管理的资源对象类型,较新的命令用法,将命令按资源类型进行分类,方便使用
Commands #对不同资源操作的命令不分类,使用容易产生混乱
docker 命令有很多子命令,可以用下面方法查看帮助
#docker 命令帮助
man docker
docker
docker --help
#docker 子命令帮助
man docker-COMMAND
docker COMMAND --help
官方文档: https://docs.docker.com/reference/
2.6查看docker相关信息
2.6.1查看docker版本
root@ubuntu1804:/home/sx# docker version
Client: Docker Engine - Community
Version: 19.03.5
API version: 1.40
Go version: go1.12.12
Git commit: 633a0ea838
Built: Wed Nov 13 07:29:52 2019
OS/Arch: linux/amd64
Experimental: false
Server: Docker Engine - Community
Engine:
Version: 19.03.5
API version: 1.40 (minimum version 1.12)
Go version: go1.12.12
Git commit: 633a0ea838
Built: Wed Nov 13 07:28:22 2019
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.4.11
GitCommit: 5b46e404f6b9f661a205e28d59c982d3634148f8
runc:
Version: 1.0.2
GitCommit: v1.0.2-0-g52b36a2
docker-init:
Version: 0.18.0
GitCommit: fec3683
root@ubuntu1804:/home/sx#
2.6.2查看docker详解信息
root@ubuntu1804:/home/sx# docker info
Client:
Debug Mode: false #client 端是否开启 debug
Server:
Containers: 0 #当前主机运行的容器总数
Running: 0 #有几个容器是正在运行的
Paused: 0 #有几个容器是暂停的
Stopped: 0 #有几个容器是停止的
Images: 0 #当前服务器的镜像数
Server Version: 19.03.5 #服务端版本
Storage Driver: overlay2 #正在使用的存储引擎
Backing Filesystem: extfs #后端文件系统,即服务器的磁盘文件系统
Supports d_type: true #是否支持 d_type
Native Overlay Diff: true #是否支持差异数据存储
Logging Driver: json-file #日志类型
Cgroup Driver: cgroupfs #Cgroups 类型
Plugins: #插件
Volume: local #卷
Network: bridge host ipvlan macvlan null overlay # overlay 跨主机通信
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog # 日志类型
Swarm: inactive #是否支持 swarm
Runtimes: runc #已安装的容器运行时
Default Runtime: runc #默认使用的容器运行时
Init Binary: docker-init #初始化容器的守护进程,即 pid 为 1 的进程
containerd version: 5b46e404f6b9f661a205e28d59c982d3634148f8 #版本
runc version: v1.0.2-0-g52b36a2 #runc 版本
init version: fec3683 #init 版本
Security Options: #安全选项
apparmor #安全模块,https://docs.docker.com/engine/security/apparmor/
seccomp #安全计算模块,即制容器操作,https://docs.docker.com/engine/security/seccomp/
Profile: default #默认的配置文件
Kernel Version: 4.15.0-112-generic #宿主机内核版本
Operating System: Ubuntu 18.04.5 LTS #宿主机操作系统
OSType: linux #宿主机操作系统类型
Architecture: x86_64 #宿主机架构
CPUs: 2 #宿主机 CPU 数量
Total Memory: 962.2MiB #宿主机总内存
Name: ubuntu1804 #宿主机 hostname
ID: 4V7J:72BA:H34E:C2T5:UG7Y:TROY:I3EV:5ZJ2:M565:UIGO:DVRS:7SI7 #宿主机 ID
Docker Root Dir: /var/lib/docker #宿主机关于docker数据的保存目录
Debug Mode: false #server 端是否开启 debug
Registry: https://index.docker.io/v1/ #仓库路径
Labels:
Experimental: false #是否测试版
Insecure Registries:
127.0.0.0/8 #非安全的镜像仓库
Live Restore Enabled: false#是否开启活动重启 (重启docker-daemon 不关闭容器 )
WARNING: No swap limit support #系统警告信息 (没有开启 swap 资源限制 )
解决上述SWAP报警提示
root@ubuntu1804:/home/sx# vim /etc/default/grub
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
# info -f grub -n 'Simple configuration'
GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=2
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT=""
GRUB_CMDLINE_LINUX="" #修改此行为下面内容
GRUB_CMDLINE_LINUX="net.ifnames=0 biosdevname=0 swapaccount=1"
root@ubuntu1804:/home/sx# update-grub
Sourcing file `/etc/default/grub'
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-4.15.0-112-generic
Found initrd image: /boot/initrd.img-4.15.0-112-generic
done
root@ubuntu1804:/home/sx# reboot
2.6.3查看docker0网卡
在docker安装启动之后,默认会生成一个名称为docker0的网卡并且默认IP地址为172.17.0.1的网卡
#Ubuntu中网卡配置
root@ubuntu1804:/home/sx# ip a
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 fq_codel state UP group default qlen 1000
link/ether 00:0c:29:42:f2:be brd ff:ff:ff:ff:ff:ff
inet 10.0.0.110/24 brd 10.0.0.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe42:f2be/64 scope link
valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:c4:e3:4e:3d 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
#centos7中网卡配置
[root@CT7test1 ~]# ip a
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: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:4d:ec:b7 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.7/24 brd 10.0.0.255 scope global noprefixroute ens33
valid_lft forever preferred_lft forever
inet6 fe80::d885:8055:9f9a:8c10/64 scope link noprefixroute
valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:1a:1a:e6:db 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
#centos8中网卡配置
[root@localhost ~]#ip a
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: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:95:b7:a2 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.11/24 brd 10.0.0.255 scope global noprefixroute ens33
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe95:b7a2/64 scope link noprefixroute
valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
link/ether 52:54:00:b0:ee:b7 brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state DOWN group default qlen 1000
link/ether 52:54:00:b0:ee:b7 brd ff:ff:ff:ff:ff:ff
5: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:ab:ff:e3:02 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
[root@localhost ~]#route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.0.1 0.0.0.0 UG 100 0 0 ens33
10.0.0.0 0.0.0.0 255.255.255.0 U 100 0 0 ens33
172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0
192.168.122.0 0.0.0.0 255.255.255.0 U 0 0 0 virbr0
2.6.4docker存储引擎
注意:如需修改查看文档进行修改,学习过程中无需关注
官方文档关于存储引擎的相关文档:
https://docs.docker.com/storage/storagedriver/
https://docs.docker.com/storage/storagedriver/select-storage-driver/
docker提供以下存储驱动程序:
- AUFS: (Advanced Mult-Layered Unification Filesystem,版本2之前旧称AnotherUnionFS)是一种 Union FS ,是文件级的存储驱动。Aufs是之前的UnionFS的重新实现,2006年由JunjiroOkajima开发
所谓 UnionFS就是把不同物理位置的目录合并 mount 到同一个目录中。简单来说就是支持将不同目录挂载到一个虚拟文件系统下的。这种可以层层地叠加修改文件。无论底下有多少都是只读的,最上系统可写的。当需要修改一个文件时, AUFS 创建该文件的一个副本,使用 CoW 将文件从只读层复制到可写进行修改,结果也保存在Docker 中,底下的只读层就是 image,可写层就是Container
aufs 被拒绝合并到主线 Linux 。其代码被批评为”dense, unreadable, uncommented 密集、不可读、未注释”。 相反,OverlayFS被合并到 Linux 内核中。在多次尝试将 aufs 合并到主线内核失败后,作者放弃了AUFS 是 Docker 18.06 及更早版本的首选存储驱动程序,在内核 3.13 上运行 Ubuntu 14.04 时不支持 overlay2
-
Overlay: 一种 Union FS 文件系统, Linux 内核 3.18 后支持
-
Overlay2: Overlay 的升级版,到目前为止,所有 Linux 发行版推荐使用的存储类 型,也是docker默认使用的存储引擎为overlay2,需要磁盘分区支持d-type功能,因此需要系统磁盘的额外支持,相对AUFS来说Overlay2 有以下优势: 更简单地设计; 从3.18开始就进入了Linux内核主线;资源消耗更少
-
devicemapper: 因为CentOS 7.2和RHEL 7.2 的之前版本内核版本不支持 overlay2,默认使用的存储驱动程序,最大数据容量只支持100GB且性能不佳,当前较新版本的CentOS 已经支持overlay2, 因此推荐使用 overlay2,另外此存储引擎已在Docker Engine 18.09中弃用
-
ZFS(Sun -2005)/btrfs(Oracle-2007): 目前没有广泛使用
-
vfs: 用于测试环境,适用于无法使用 copy-on -writewrite 时的情况。 此存储驱动程序的性能很差,通常不建议用于生产
修改存储引擎参考文档:
https://docs.docker.com/storage/storagedriver/overlayfs-driver/
在centos7修改存储引擎
[root@centos7 ~]#vim /lib/systemd/system/docker.service
.....
ExecStart=/usr/bin/dockerd -s overlay2 -H fd:// --
containerd=/run/containerd/containerd.sock
......
#创建新的xfs分区,添加ftype特性,否则默认无法启动docker服务
[root@centos7 ~]#mkfs.xfs -n ftype=1 /dev/sdb
[root@centos7 ~]#mount /dev/sdb /var/lib/docker
[root@centos7 ~]#systemctl daemon-reload
[root@centos7 ~]#systemctl restart docker
注意:修改存储引擎会导致所有容器丢失,所以先备份再修改
查看默认存储引擎
#查看Ubuntu1804的默认存储引擎
[root@ubuntu1804 ~]#docker info |grep Storage
WARNING: No swap limit support
Storage Driver: overlay2
#查看CentOS7.6的默认存储引擎
[root@centos7 ~]#docker info |grep Storage
WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled
Storage Driver: overlay2
Docker官方推荐首选存储引擎为overlay2,其次为devicemapper,但是devicemapper存在使用空间方面的一些限制,虽然可以通过后期配置解决,但是官方依然推荐使用overlay2,以下是生产故障事例:
https://www.cnblogs.com/youruncloud/p/5736718.html
如果docker数据目录是一块单独的磁盘分区而且是xfs格式的,那么需要在格式化的时候加上参数-n ftype=1(启用此功能表示节点文件类型存入在目录结构中), 示例: mkfs.xfs -n ftype=1 devname ,否则后期在无法启动容器,并会报错不支持 d_type
[root@centos7 ~]#xfs_info /data
meta-data=/dev/mapper/centos-root isize=512 agcount=4, agsize=3276800 blks
= sectsz=512 attr=2, projid32bit=1
= crc=1 finobt=0 spinodes=0
data = bsize=4096 blocks=13107200, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=1
log =internal bsize=4096 blocks=6400, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
[root@centos7 ~]#xfs_info /data
meta-data=/dev/mapper/centos-root isize=512 agcount=4, agsize=3276800 blks
= sectsz=512 attr=2, projid32bit=1
= crc=1 finobt=0 spinodes=0
data = bsize=4096 blocks=13107200, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0 #CentOS7.2之前版本此特性默认ftype=0
log =internal bsize=4096 blocks=6400, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
ext4文件系统无需此d_type特性
aufs实现联合文件系统挂载
[root@ubuntu1804 ~]#cat /proc/filesystems
nodev sysfs
nodev rootfs
nodev ramfs
nodev bdev
nodev proc
nodev cpuset
nodev cgroup
nodev cgroup2
nodev tmpfs
nodev devtmpfs
nodev configfs
nodev debugfs
nodev tracefs
nodev securityfs
nodev sockfs
nodev dax
nodev bpf
nodev pipefs
nodev hugetlbfs
nodev devpts
ext3
ext2
ext4
squashfs
vfat
nodev ecryptfs
fuseblk
nodev fuse
nodev fusectl
nodev pstore
nodev mqueue
btrfs
nodev autofs
nodev rpc_pipefs
nodev nfsd
nodev overlay
nodev aufs
[root@ubuntu1804 ~]#grep -i aufs /boot/config-4.15.0-29-generic
CONFIG_AUFS_FS=m
CONFIG_AUFS_BRANCH_MAX_127=y
# CONFIG_AUFS_BRANCH_MAX_511 is not set
# CONFIG_AUFS_BRANCH_MAX_1023 is not set
# CONFIG_AUFS_BRANCH_MAX_32767 is not set
CONFIG_AUFS_SBILIST=y
# CONFIG_AUFS_HNOTIFY is not set
CONFIG_AUFS_EXPORT=y
CONFIG_AUFS_INO_T_64=y
CONFIG_AUFS_XATTR=y
# CONFIG_AUFS_FHSM is not set
# CONFIG_AUFS_RDU is not set
CONFIG_AUFS_DIRREN=y
# CONFIG_AUFS_SHWH is not set
# CONFIG_AUFS_BR_RAMFS is not set
# CONFIG_AUFS_BR_FUSE is not set
CONFIG_AUFS_BR_HFSPLUS=y
CONFIG_AUFS_BDEV_LOOP=y
# CONFIG_AUFS_DEBUG is not set
[root@ubuntu1804 ~]#mkdir dir{1,2}
[root@ubuntu1804 ~]#echo here is dir1 > dir1/file1
[root@ubuntu1804 ~]#echo here is dir2 > dir2/file2
[root@ubuntu1804 ~]#mkdir /data/aufs
[root@ubuntu1804 ~]#mount -t aufs -o br=/root/dir1=ro:/root/dir2=rw none
/data/aufs
[root@ubuntu1804 ~]#ll /data/aufs/
total 16
drwxr-xr-x 4 root root 4096 Jan 25 16:22 ./
drwxr-xr-x 4 root root 4096 Jan 25 16:22 ../
-rw-r--r-- 1 root root 13 Jan 25 16:22 file1
-rw-r--r-- 1 root root 13 Jan 25 16:22 file2
[root@ubuntu1804 ~]#cat /data/aufs/file1
here is dir1
[root@ubuntu1804 ~]#cat /data/aufs/file2
here is dir2
[root@ubuntu1804 ~]#df -T
Filesystem Type 1K-blocks Used Available Use% Mounted on
udev devtmpfs 462560 0 462560 0% /dev
tmpfs tmpfs 98512 10296 88216 11% /run
/dev/sda2 ext4 47799020 2770244 42570972 7% /
tmpfs tmpfs 492552 0 492552 0% /dev/shm
tmpfs tmpfs 5120 0 5120 0% /run/lock
tmpfs tmpfs 492552 0 492552 0% /sys/fs/cgroup
/dev/sda3 ext4 19091540 45084 18053588 1% /data
/dev/sda1 ext4 944120 77112 801832 9% /boot
tmpfs tmpfs 98508 0 98508 0% /run/user/0
none aufs 47799020 2770244 42570972 7% /data/aufs
[root@ubuntu1804 ~]#echo write to file1 >> /data/aufs/file1
-bash: /data/aufs/file1: Read-only file system
[root@ubuntu1804 ~]#echo write to file2 >> /data/aufs/file2
[root@ubuntu1804 ~]#cat /data/aufs/file1
here is dir1
[root@ubuntu1804 ~]#cat /data/aufs/file2
here is dir2
write to file2
[root@ubuntu1804 ~]#umount /data/aufs
[root@ubuntu1804 ~]#mv dir1/file1 dir1/file2
[root@ubuntu1804 ~]#cat dir1/file2
here is dir1
[root@ubuntu1804 ~]#cat dir2/file2
here is dir2
write to file2
[root@ubuntu1804 ~]#mount -t aufs -o br=/root/dir1=ro:/root/dir2=rw none /data/aufs
[root@ubuntu1804 ~]#ls /data/aufs -l
total 4
-rw-r--r-- 1 root root 13 Jan 25 16:22 file2
[root@ubuntu1804 ~]#cat /data/aufs/file2
here is dir1
[root@ubuntu1804 ~]#
修改存储引擎
[root@ubuntu1804 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED
SIZE
nginx latest 5ad3bd0e67a9 3 days ago
127MB
alpine latest e7d92cdc71fe 7 days ago
5.59MB
centos centos8.1.1911 470671670cac 7 days ago
237MB
centos latest 470671670cac 7 days ago
237MB
busybox latest 6d5fcfe5ff17 4 weeks ago
1.22MB
hello-world latest fce289e99eb9 12 months ago
1.84kB
[root@ubuntu1804 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
d4741f815199 busybox "sh" 41 hours ago
Exited (137) 23 hours ago flamboyant_moser
5dee9be9afdb nginx "nginx -g 'daemon of…" 2 days ago
Exited (0) 23 hours ago lucid_lichterman
[root@ubuntu1804 ~]#docker info |grep "Storage Driver"
Storage Driver: overlay2
[root@ubuntu1804 ~]#systemctl stop docker
Warning: Stopping docker.service, but it can still be activated by:
docker.socket
[root@ubuntu1804 ~]#vim /etc/docker/daemon.json
[root@ubuntu1804 ~]#cat /etc/docker/daemon.json
{
"storage-driver": "aufs"
}
[root@ubuntu1804 ~]#systemctl restart docker
[root@ubuntu1804 ~]#docker info |grep aufs
WARNING: the aufs storage-driver is deprecated, and will be removed in a future
release.
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
[root@ubuntu1804 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED
SIZE
[root@ubuntu1804 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
[root@ubuntu1804 ~]#vim /etc/docker/daemon.json
{
"storage-driver": "aufs"
}
[root@ubuntu1804 ~]#ls /var/lib/docker
aufs builder buildkit containers image network overlay2 plugins runtimes
swarm tmp trust volumes
[root@ubuntu1804 ~]#ls /var/lib/docker/aufs/
diff layers mnt
[root@ubuntu1804 ~]#ll /var/lib/docker/aufs/
total 20
drwx------ 5 root root 4096 Jan 25 16:46 ./
drwx--x--x 15 root root 4096 Jan 25 16:46 ../
drwx------ 2 root root 4096 Jan 25 16:46 diff/
drwx------ 2 root root 4096 Jan 25 16:46 layers/
drwx------ 2 root root 4096 Jan 25 16:46 mnt/
[root@ubuntu1804 ~]#vim /etc/docker/daemon.json
[root@ubuntu1804 ~]#cat /etc/docker/daemon.json
{
"registry-mirrors": ["https://si7y70hh.mirror.aliyuncs.com"]
}
[root@ubuntu1804 ~]#
[root@ubuntu1804 ~]#systemctl restart docker
[root@ubuntu1804 ~]#ll /var/lib/docker/aufs/
total 20
drwx------ 5 root root 4096 Jan 25 16:46 ./
drwx--x--x 15 root root 4096 Jan 25 16:48 ../
drwx------ 2 root root 4096 Jan 25 16:46 diff/
drwx------ 2 root root 4096 Jan 25 16:46 layers/
drwx------ 2 root root 4096 Jan 25 16:46 mnt/
[root@ubuntu1804 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
d4741f815199 busybox "sh" 41 hours ago
Exited (137) 23 hours ago flamboyant_moser
5dee9be9afdb nginx "nginx -g 'daemon of…" 2 days ago
Exited (0) 23 hours ago lucid_lichterman
[root@ubuntu1804 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED
SIZE
nginx latest 5ad3bd0e67a9 3 days ago
127MB
alpine latest e7d92cdc71fe 7 days ago
5.59MB
centos centos8.1.1911 470671670cac 7 days ago
237MB
centos latest 470671670cac 7 days ago
237MB
busybox latest 6d5fcfe5ff17 4 weeks ago
1.22MB
hello-world latest fce289e99eb9 12 months ago
1.84kB
[root@ubuntu1804 ~]#
2.6.5 docker 服务进程
查看主机进程树
[root@CT7test1 ~]# pstree -p
systemd(1)─┬─NetworkManager(723)─┬─{NetworkManager}(740)
│ └─{NetworkManager}(742)
├─VGAuthService(660)
├─agetty(689)
├─auditd(634)───{auditd}(635)
├─containerd(1880)─┬─{containerd}(1882)
│ ├─{containerd}(1883)
│ ├─{containerd}(1884)
│ ├─{containerd}(1885)
│ ├─{containerd}(1886)
│ └─{containerd}(1888)
├─crond(686)
├─dbus-daemon(663)───{dbus-daemon}(671)
├─dockerd(1889)─┬─{dockerd}(1890)
│ ├─{dockerd}(1891)
│ ├─{dockerd}(1892)
│ ├─{dockerd}(1893)
│ ├─{dockerd}(1894)
│ ├─{dockerd}(1896)
│ └─{dockerd}(1897)
├─firewalld(711)───{firewalld}(846)
├─lvmetad(509)
├─master(1256)─┬─pickup(12957)
│ └─qmgr(1273)
├─polkitd(657)─┬─{polkitd}(670)
│ ├─{polkitd}(672)
│ ├─{polkitd}(674)
│ ├─{polkitd}(684)
│ ├─{polkitd}(693)
│ └─{polkitd}(701)
├─rsyslogd(1021)─┬─{rsyslogd}(1112)
│ └─{rsyslogd}(1113)
├─sshd(1017)─┬─sshd(1612)───bash(1616)
│ └─sshd(1682)───bash(1686)───pstree(13057)
├─systemd-journal(482)
├─systemd-logind(673)
├─systemd-udevd(520)
├─tuned(1018)─┬─{tuned}(1429)
│ ├─{tuned}(1430)
│ ├─{tuned}(1445)
│ └─{tuned}(1447)
└─vmtoolsd(661)─┬─{vmtoolsd}(676)
└─{vmtoolsd}(682)
[root@localhost ~]#ps aux | grep -E 'containerd|docker'
root 42519 0.1 3.5 1492840 64900 ? Sl 06:32 0:37 dockerd
root 42530 0.6 2.2 1541496 40672 ? Ssl 06:32 3:33 containerd --config /var/run/docker/containerd/containerd.toml --log-level info
root 43420 0.3 1.9 1319788 35348 ? Ssl 07:13 1:42 /usr/bin/containerd
root 48324 0.0 0.1 12268 2408 pts/1 S+ 15:23 0:00 grep --color=auto -E containerd|docker
18.06及之前的docker版本,进程关系:
18.06之后版本的docker版本,进程关系:
docke进程之间的关系
docker 相关的四个进程:
- dockerd: 服务器程序,被client直接访问,其父进程为宿主机的systemd守护进程。
- docker-proxy: 每个进程docker-proxy实现对应一个需要网络通信的容器,管理宿主机和容器的之间端口映射,其父进程为dockerd,如果容器不需要网络则无需启动
- containerd: 被dockerd进程调用以实现与runc交互
- containerd-shim: 真正运行容器的载体,每个容器对应一个containerd-shim进程,其父进程为containerd
containerd-shim命令使用
[root@ubuntu1804 ~]#containerd-shim -h
Usage of containerd-shim:
-address string
grpc address back to main containerd
-containerd-binary containerd publish
path to containerd binary (used for containerd publish) (default
"containerd")
-criu string
path to criu binary
-debug
enable debug output in logs
-namespace string
namespace that owns the shim
-runtime-root string
root directory for the runtime (default "/run/containerd/runc")
-socket string
abstract socket path to serve
-systemd-cgroup
set runtime to use systemd-cgroup
-workdir string
path used to storge large temporary data
容器的创建与管理过程
通信流程:
- dockerd通过grpc和 containerd模块通信,dockerd由libcontainerd负责和containerd进行交换,dockerd和containerd 通信socket文件: /run/containerd/containerd.sock
- containerd在dockerd启动时被启动,然后containerd启动grpc请求监听,containerd处理grpc请求,根据请求做相应动作
- 若是run, start或是exec 容器,containerd 拉起一个container-shim , 并进行相应的操作
- container-shim别拉起后,start/exec/create拉起runC进程,通过exit、control文件
podman 的进程结构
podman没有dockerd服务进程,所以当无容器启动时,无需启动任何进程,而容器启动时,会做为conmon的子进程
[root@centos8 ~]#podman version
Version: 1.4.2-stable2
RemoteAPI Version: 1
Go Version: go1.12.8
OS/Arch: linux/amd64
[root@centos8 ~]#podman run -d -p 80:80 docker.io/library/nginx
d8877293635c599a82ab5cb82c942cd86baf7c5810dd824154b15b0a88e76be8
[root@centos8 ~]#ss -tlnp
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
users:(("conmon",pid=5173,fd=5))
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
users:(("sshd",pid=687,fd=4))
LISTEN 0 128 [::]:22 [::]:*
users:(("sshd",pid=687,fd=6))
[root@centos8 ~]#pstree -p
systemd(1)─┬─NetworkManager(660)─┬─{NetworkManager}(680)
│ └─{NetworkManager}(682)
├─VGAuthService(663)
├─agetty(805)
├─anacron(2793)
├─atd(799)
├─auditd(616)───{auditd}(617)
├─automount(816)─┬─{automount}(821)
│ ├─{automount}(822)
│ ├─{automount}(829)
│ └─{automount}(837)
├─conmon(5173)─┬─nginx(5183)───nginx(5194)
│ └─{conmon}(5175)
├─crond(797)
├─dbus-daemon(658)
├─polkitd(665)─┬─{polkitd}(679)
│ ├─{polkitd}(683)
│ ├─{polkitd}(694)
│ ├─{polkitd}(695)
│ └─{polkitd}(750)
├─rngd(661)───{rngd}(673)
├─rsyslogd(814)─┬─{rsyslogd}(818)
│ └─{rsyslogd}(820)
├─sshd(687)─┬─sshd(1166)───sshd(1243)───bash(1244)
│ └─sshd(1306)───sshd(1308)───bash(1309)───pstree(5198)
├─sssd(659)─┬─sssd_be(722)
│ └─sssd_nss(749)
├─systemd(1234)───(sd-pam)(1237)
├─systemd-journal(543)
├─systemd-logind(794)
├─systemd-udevd(575)
├─tuned(692)─┬─{tuned}(1080)
│ ├─{tuned}(1089)
│ └─{tuned}(1097)
└─vmtoolsd(664)───{vmtoolsd}(762)
2.7服务管理
docker 服务基于C/S 结构,可以实现基于本地和远程方式进行管理
#Dockerd守护进程启动选项
-H tcp://host:port
unix:///path/to/socket,
fd://* or fd://socketfd
#守护进程默认配置:
-H unix:///var/run/docker.sock
#使用Docker客户端命令选项
-H tcp://host:port
unix:///path/to/socket,
fd://* or fd://socketfd
客户端默认配置:
-H unix:///var/run/docker.sock
#docker客户端也可以使用环境变量DOCKER_ HOST,代替-H选项
export DOCKER_HOST="tcp://docker-server:2375"
通过UDS访问docker
[root@ubuntu1804 ~]#cat /lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
BindsTo=containerd.service
After=network-online.target firewalld.service containerd.service
Wants=network-online.target
Requires=docker.socket
[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 -H fd:// --containerd=/run/containerd/containerd.sock
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always
# Note that StartLimit* options were moved from "Service" to "Unit" in systemd
229.
# Both the old, and new location are accepted by systemd 229 and up, so using
the old location
# to make them work for either version of systemd.
StartLimitBurst=3
# Note that StartLimitInterval was renamed to StartLimitIntervalSec in systemd
230.
# Both the old, and new name are accepted by systemd 230 and up, so using the
old name to make
# this option work for either version of systemd.
StartLimitInterval=60s
# 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
# Comment TasksMax if your systemd version does not support it.
# Only systemd 226 and above support this option.
TasksMax=infinity
# 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
[Install]
WantedBy=multi-user.target
[root@ubuntu1804 ~]#systemctl status docker
● docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset:
enabled)
Active: active (running) since Wed 2020-07-22 14:06:46 CST; 5h 50min ago
Docs: https://docs.docker.com
Main PID: 1138 (dockerd)
Tasks: 17
CGroup: /system.slice/docker.service
└─1138 /usr/bin/dockerd -H fd:// --
containerd=/run/containerd/containerd.sock
docker服务添加标签
[root@ubuntu1804 ~]#vim /lib/systemd/system/docker.service
#修改下面行
ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
--label="name=docker1"
[root@ubuntu1804 ~]#systemctl daemon-reload
[root@ubuntu1804 ~]#systemctl restart docker
[root@ubuntu1804 ~]#docker info
Client:
Debug Mode: false
Server:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 5
Server Version: 19.03.12
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 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:
apparmor
seccomp
Profile: default
Kernel Version: 4.15.0-111-generic
Operating System: Ubuntu 18.04.4 LTS
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 2.908GiB
Name: ubuntu1804.magedu.org
ID: LVU6:OXD3:TAPB:KDNQ:YRSN:XTAS:3V32:IERB:2DM6:4CDK:CRO6:ZKAW
Docker Root Dir: /var/lib/docker
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
name=docker1 #此处显示添加的标签
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://si7y70hh.mirror.aliyuncs.com/
Live Restore Enabled: false
WARNING: No swap limit support
开启docker的远程访问
#方法1
[root@ubuntu1804 ~]#vim /lib/systemd/system/docker.service
#修改下面行
ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:2375 --
containerd=/run/containerd/containerd.sock --label="name=docker1"
#方法2
[root@ubuntu1804 ~]#vim /lib/systemd/system/docker.service
ExecStart=/usr/bin/dockerd --containerd=/run/containerd/containerd.sock
[root@ubuntu1804 ~]#vim /etc/docker/daemon.json
{
"hosts": ["tcp://0.0.0.0:2375", "fd://"]
}
[root@ubuntu1804 ~]#systemctl daemon-reload
[root@ubuntu1804 ~]#systemctl restart docker
[root@ubuntu1804 ~]#ss -tnlp|grep 2375
LISTEN 0 128 *:2375 *:*
users:(("dockerd",pid=9964,fd=3))
[root@ubuntu1804 ~]#ps -ef | grep docker
root 9964 1 0 20:33 ? 00:00:00 /usr/bin/dockerd -H fd:// -H
tcp://0.0.0.0:2375 --containerd=/run/containerd/containerd.sock --
label=name=docker1
root 10187 2854 0 20:37 pts/1 00:00:00 grep --color=auto docker
[root@ubuntu1804 ~]#ll /var/run/docker.sock
srw-rw---- 1 root docker 0 Jul 22 20:33 /var/run/docker.sock=
#实现远程访问方式1
[root@centos7 ~]#curl http://10.0.0.100:2375/info
#实现远程访问方式2
[root@centos7 ~]#docker -H tcp://10.0.0.100:2375 info
Client:
Debug Mode: false
Server:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 5
Server Version: 19.03.12
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 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:
apparmor
seccomp
Profile: default
Kernel Version: 4.15.0-111-generic
Operating System: Ubuntu 18.04.4 LTS
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 2.908GiB
Name: ubuntu1804.magedu.org
ID: LVU6:OXD3:TAPB:KDNQ:YRSN:XTAS:3V32:IERB:2DM6:4CDK:CRO6:ZKAW
Docker Root Dir: /var/lib/docker
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
name=docker1
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://si7y70hh.mirror.aliyuncs.com/
Live Restore Enabled: false
WARNING: API is accessible on http://0.0.0.0:2375 without encryption.
Access to the remote API is equivalent to root access on the host.
Refer
to the 'Docker daemon attack surface' section in the documentation for
more information:
https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface
WARNING: No swap limit support
#实现远程访问方式3
[root@centos7 ~]#export DOCKER_HOST="tcp://10.0.0.100:2375"
[root@centos7 ~]#docker info
Client:
Debug Mode: false
Server:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 5
Server Version: 19.03.12
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 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:
apparmor
seccomp
Profile: default
Kernel Version: 4.15.0-111-generic
Operating System: Ubuntu 18.04.4 LTS
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 2.908GiB
Name: ubuntu1804.magedu.org
ID: LVU6:OXD3:TAPB:KDNQ:YRSN:XTAS:3V32:IERB:2DM6:4CDK:CRO6:ZKAW
Docker Root Dir: /var/lib/docker
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
name=docker1
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://si7y70hh.mirror.aliyuncs.com/
Live Restore Enabled: false
WARNING: API is accessible on http://0.0.0.0:2375 without encryption.
Access to the remote API is equivalent to root access on the host.
Refer
to the 'Docker daemon attack surface' section in the documentation for
more information:
https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface
WARNING: No swap limit support
#恢复连接本机
[root@centos7 ~]#unset DOCKER_HOST
[root@centos7 ~]#docker info
Client:
Debug Mode: false
Server:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 19.03.5
Storage Driver: overlay2
Backing Filesystem: xfs
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-1127.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 972.3MiB
Name: centos7.wangxiaochun.com
ID: USO2:CGRA:LIV3:SWOQ:5AWX:EN6W:4AUZ:XYZ7:LL6K:SUQ5:HANV:TX5L
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
Registry Mirrors:
https://si7y70hh.mirror.aliyuncs.com/
Live Restore Enabled: false
3、镜像管理
3.1镜像结构和原理
镜像即创建容器的模版,含有启动容器所需要的文件系统及所需要的内容,因此镜像主要用于方便和快速的创建并启动容器
镜像里面是一层层的文件系统,叫做 Union FS(联合文件系统),联合文件系统,可以将几层目录挂载到一起(就像千层饼,洋葱头,俄罗斯套娃一样),形成一个虚拟文件系统,虚拟文件系统的目录结构就像普通 linux 的目录结构一样,镜像通过这些文件再加上宿主机的内核共同提供了一个 linux 的虚拟环境,每一层文件系统叫做一层 layer,联合文件系统可以对每一层文件系统设置三种权限,只读(readonly)、读写(readwrite)和写出(whiteout-able),但是镜像中每一层文件系统都是只读的,构建镜像的时候,从一个最基本的操作系统开始,每个构建提交的操作都相当于做一层的修改,增加了一层文件系统,一层层往上叠加,上层的修改会覆盖底层该位置的可见性,这也很容易理解,就像上层把底层遮住了一样,当使用镜像的时候,我们只会看到一个完全的整体,不知道里面有几层,实际上也不需要知道里面有几层,结构如下:
一个典型的 Linux文件系统由 bootfs 和 rootfs 两部分组成
bootfs(boot file system) 主要包含bootloader和kernel,bootloader主要用于引导加载 kernel,Linux刚启动时会加载bootfs文件系统,当boot加载完成后,kernel 被加载到内存中后接管系统的控制权,bootfs会被 umount 掉
rootfs (root file system) 包含的就是典型 Linux 系统中的/dev,/proc,/bin,/etc 等标准目录和文件,不同的 linux 发行版(如 ubuntu 和 CentOS ) 主要在 rootfs 这一层会有所区别。
一般的镜像通常都比较小,官方提供的Ubuntu镜像只有60MB多点,而 CentOS 基础镜像也只有200MB左右,一些其他版本的镜像甚至只有几MB,比如: busybox 才1.22MB,alpine镜像也只有5M左右。镜像直接调用宿主机的内核,镜像中只提供 rootfs,也就是只需要包括最基本的命令,配置文件和程序库等相关文件就可以了。
下图就是有两个不同的镜像在一个宿主机内核上实现不同的rootfs。
#下载镜像
[root@CT7test1 ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
b380bbd43752: Pull complete
fca7e12d1754: Pull complete
745ab57616cb: Pull complete
a4723e260b6f: Pull complete
1c84ebdff681: Pull complete
858292fd2e56: Pull complete
Digest: sha256:644a70516a26004c97d0d85c7fe1d0c3a67ea8ab7ddf4aff193d9f301670cf36
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
#查看镜像分层历史
[root@CT7test1 ~]# docker image history nginx
IMAGE CREATED CREATED BY SIZE COMMENT
87a94228f133 3 weeks ago /bin/sh -c #(nop) CMD ["nginx" "-g" "daemon… 0B
<missing> 3 weeks ago /bin/sh -c #(nop) STOPSIGNAL SIGQUIT 0B
<missing> 3 weeks ago /bin/sh -c #(nop) EXPOSE 80 0B
<missing> 3 weeks ago /bin/sh -c #(nop) ENTRYPOINT ["/docker-entr… 0B
<missing> 3 weeks ago /bin/sh -c #(nop) COPY file:09a214a3e07c919a… 4.61kB
<missing> 3 weeks ago /bin/sh -c #(nop) COPY file:0fd5fca330dcd6a7… 1.04kB
<missing> 3 weeks ago /bin/sh -c #(nop) COPY file:0b866ff3fc1ef5b0… 1.96kB
<missing> 3 weeks ago /bin/sh -c #(nop) COPY file:65504f71f5855ca0… 1.2kB
<missing> 3 weeks ago /bin/sh -c set -x && addgroup --system -… 64MB
<missing> 3 weeks ago /bin/sh -c #(nop) ENV PKG_RELEASE=1~buster 0B
<missing> 3 weeks ago /bin/sh -c #(nop) ENV NJS_VERSION=0.6.2 0B
<missing> 3 weeks ago /bin/sh -c #(nop) ENV NGINX_VERSION=1.21.3 0B
<missing> 3 weeks ago /bin/sh -c #(nop) LABEL maintainer=NGINX Do… 0B
<missing> 3 weeks ago /bin/sh -c #(nop) CMD ["bash"] 0B
<missing> 3 weeks ago /bin/sh -c #(nop) ADD file:910392427fdf089bc… 69.3MB
#查看Docker对象的低级信息
[root@CT7test1 ~]# docker inspect nginx:latest
[
{
"Id": "sha256:87a94228f133e2da99cb16d653cd1373c5b4e8689956386c1c12b60a20421a02",
"RepoTags": [
"nginx:latest"
],
"RepoDigests": [
"nginx@sha256:644a70516a26004c97d0d85c7fe1d0c3a67ea8ab7ddf4aff193d9f301670cf36"
],
"Parent": "",
"Comment": "",
"Created": "2021-10-12T02:03:40.360294686Z",
"Container": "21fd1c6cb532225ca7e04c77f6592e220574b919aec07021663576ef438e0fee",
"ContainerConfig": {
"Hostname": "21fd1c6cb532",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"80/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"NGINX_VERSION=1.21.3",
"NJS_VERSION=0.6.2",
"PKG_RELEASE=1~buster"
],
"Cmd": [
"/bin/sh",
"-c",
"#(nop) ",
"CMD [\"nginx\" \"-g\" \"daemon off;\"]"
],
"Image": "sha256:e30f1b92b2c67fbe72fb24af7353a945f6df4f48d9064d47bf0f51674311251e",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": [
"/docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": {
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
},
"StopSignal": "SIGQUIT"
},
"DockerVersion": "20.10.7",
"Author": "",
"Config": {
"Hostname": "",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"80/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"NGINX_VERSION=1.21.3",
"NJS_VERSION=0.6.2",
"PKG_RELEASE=1~buster"
],
"Cmd": [
"nginx",
"-g",
"daemon off;"
],
"Image": "sha256:e30f1b92b2c67fbe72fb24af7353a945f6df4f48d9064d47bf0f51674311251e",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": [
"/docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": {
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
},
"StopSignal": "SIGQUIT"
},
"Architecture": "amd64",
"Os": "linux",
"Size": 133277153,
"VirtualSize": 133277153,
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/4ef9a37d1cd58d9e02492c4fed928eaace855984fd92d90c8c57ce242bfa49aa/diff:/var/lib/docker/overlay2/ae93bdeccfbdf2550eb8b8f818f0232a97ffae5846abb080db4c35029d2555cc/diff:/var/lib/docker/overlay2/69ad398e93773d55652b4ced61603f9e8db01a0ee62d2f8b910ecdc96d2f4af7/diff:/var/lib/docker/overlay2/09981ea0b9ee05d22669b350570b96adf090c38aad056ae99e5159faff5f6e16/diff:/var/lib/docker/overlay2/7bc4007a70ed3f369d55d823904ed8a8e476bed1d25d62e0514f7c70941aa41c/diff",
"MergedDir": "/var/lib/docker/overlay2/1746f36aa67429fb486367c3d667da23bceb0b2cbe722c0f94a07c7896c21ee8/merged",
"UpperDir": "/var/lib/docker/overlay2/1746f36aa67429fb486367c3d667da23bceb0b2cbe722c0f94a07c7896c21ee8/diff",
"WorkDir": "/var/lib/docker/overlay2/1746f36aa67429fb486367c3d667da23bceb0b2cbe722c0f94a07c7896c21ee8/work"
},
"Name": "overlay2"
},
"RootFS": {
"Type": "layers",
"Layers": [
"sha256:e81bff2725dbc0bf2003db10272fef362e882eb96353055778a66cda430cf81b",
"sha256:43f4e41372e42dd32309f6a7bdce03cf2d65b3ca34b1036be946d53c35b503ab",
"sha256:788e89a4d186f3614bfa74254524bc2e2c6de103698aeb1cb044f8e8339a90bd",
"sha256:f8e880dfc4ef19e78853c3f132166a4760a220c5ad15b9ee03b22da9c490ae3b",
"sha256:f7e00b807643e512b85ef8c9f5244667c337c314fa29572206c1b0f3ae7bf122",
"sha256:9959a332cf6e41253a9cd0c715fa74b01db1621b4d16f98f4155a2ed5365da4a"
]
},
"Metadata": {
"LastTagTime": "0001-01-01T00:00:00Z"
}
}
]
#将镜像打包
[root@CT7test1 ~]# docker save nginx -o nginx.tar
[root@CT7test1 ~]# ll
total 134332
-rw-------. 1 root root 1310 Oct 13 16:57 anaconda-ks.cfg
-rw-r--r--. 1 root root 677 Nov 2 14:06 install_docker_centos7.sh
-rw-------. 1 root root 137544192 Nov 2 16:01 nginx.tar
3.2搜索镜像
3.2.1 官方网站进行镜像的搜索
官网: http://hub.docker.com
在官方的docker 仓库中搜索指定名称的docker镜像,有软件官方提供的镜像(official image)也会有很多三方镜像。
3.2.2 执行docker search命令进行搜索
格式如下
Usage: docker search [OPTIONS] TERM
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
说明:
OFFICIAL: 官方
AUTOMATED: 使用第三方docker服务来帮助编译镜像,可以在互联网上面直接拉取到镜像,减少了繁琐的编译过程
[root@CT7test1 ~]# docker search centos
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
centos The official build of CentOS. 6836 [OK]
ansible/centos7-ansible Ansible on Centos7 135 [OK]
consol/centos-xfce-vnc Centos container with "headless" VNC session… 132 [OK]
jdeathe/centos-ssh OpenSSH / Supervisor / EPEL/IUS/SCL Repos - … 121 [OK]
centos/systemd systemd enabled base container. 105 [OK]
centos/mysql-57-centos7 MySQL 5.7 SQL database server 91
imagine10255/centos6-lnmp-php56 centos6-lnmp-php56 58 [OK]
tutum/centos Simple CentOS docker image with SSH access 48
centos/postgresql-96-centos7 PostgreSQL is an advanced Object-Relational … 45
centos/httpd-24-centos7 Platform for running Apache httpd 2.4 or bui… 40
kinogmt/centos-ssh CentOS with SSH 29 [OK]
guyton/centos6 From official centos6 container with full up… 10 [OK]
nathonfowlie/centos-jre Latest CentOS image with the JRE pre-install… 8 [OK]
centos/tools Docker image that has systems administration… 7 [OK]
drecom/centos-ruby centos ruby 6 [OK]
mamohr/centos-java Oracle Java 8 Docker image based on Centos 7 3 [OK]
darksheer/centos Base Centos Image -- Updated hourly 3 [OK]
dokken/centos-7 CentOS 7 image for kitchen-dokken 2
amd64/centos The official build of CentOS. 2
miko2u/centos6 CentOS6 日本語環境 2 [OK]
mcnaughton/centos-base centos base image 1 [OK]
blacklabelops/centos CentOS Base Image! Built and Updates Daily! 1 [OK]
starlabio/centos-native-build Our CentOS image for native builds 0 [OK]
smartentry/centos centos with smartentry 0 [OK]
jelastic/centosvps An image of the CentOS Elastic VPS maintaine… 0
选择性下载
#搜索点赞100个以上的镜像
#旧语法
[root@CT7test1 ~]# docker search -s 100 centos
Flag --stars has been deprecated, use --filter=stars=3 instead
NAME DESCRIPTION STARS FICIAL AUTOMATED
centos The official build of CentOS. 6836 K]
ansible/centos7-ansible Ansible on Centos7 135 [OK]
consol/centos-xfce-vnc Centos container with "headless" VNC session… 132 [OK]
jdeathe/centos-ssh OpenSSH / Supervisor / EPEL/IUS/SCL Repos - … 121 [OK]
centos/systemd systemd enabled base container. 105 [OK]
#新语法
[root@CT7test1 ~]# docker search --filter=stars=100 centos
NAME DESCRIPTION STARS FICIAL AUTOMATED
centos The official build of CentOS. 6836 K]
ansible/centos7-ansible Ansible on Centos7 135 [OK]
consol/centos-xfce-vnc Centos container with "headless" VNC session… 132 [OK]
jdeathe/centos-ssh OpenSSH / Supervisor / EPEL/IUS/SCL Repos - … 121 [OK]
centos/systemd systemd enabled base container. 105 [OK]
3.3alpine介绍
Alpine 操作系统是一个面向安全的轻型 Linux 发行版。它不同于通常 Linux 发行版,Alpine 采用了musl libc 和 busybox 以减小系统的体积和运行时资源消耗,但功能上比 busybox 又完善的多,因此得到开源社区越来越多的青睐。在保持瘦身的同时,Alpine 还提供了自己的包管理工具 apk,可以通过https://pkgs.alpinelinux.org/packages 网站上查询包信息,也可以直接通过 apk 命令直接查询和安装各种软件。
Alpine 由非商业组织维护的,支持广泛场景的 Linux发行版,它特别为资深/重度Linux用户而优化,关注安全,性能和资源效能。Alpine 镜像可以适用于更多常用场景,并且是一个优秀的可以适用于生产的基础系统/环境。
Alpine Docker 镜像也继承了 Alpine Linux 发行版的这些优势。相比于其他 Docker 镜像,它的容量非常小,仅仅只有 5 MB 左右(对比 Ubuntu 系列镜像接近 200 MB),且拥有非常友好的包管理机制。官方镜像来自 docker-alpine 项目。
目前 Docker 官方已开始推荐使用 Alpine 替代之前的 Ubuntu 做为基础镜像环境。这样会带来多个好处。包括镜像下载速度加快,镜像安全性提高,主机之间的切换更方便,占用更少磁盘空间等。
下表是官方镜像的大小比较:
REPOSITORY TAG IMAGE ID VIRTUAL SIZE
alpine latest 4e38e38c8ce0 4.799 MB
debian latest 4d6ce913b130 84.98 MB
ubuntu latest b39b81afc8ca 188.3 MB
centos latest 8efe422e6104 210 MB
Alpine 官网: https://www.alpinelinux.org/
Alpine 官方仓库: https://github.com/alpinelinux
Alpine 官方镜像: https://hub.docker.com/_/alpine/
Alpine 官方镜像仓库: https://github.com/gliderlabs/docker-alpine
Alpine 阿里云的镜像仓库: https://mirrors.aliyun.com/alpine/
alpine管理软件
#修改源替换成阿里源,将里面 dl-cdn.alpinelinux.org 的 改成 mirrors.aliyun.com
vi /etc/apk/repositories
http://mirrors.aliyun.com/alpine/v3.8/main/
http://mirrors.aliyun.com/alpine/v3.8/community/
#更新源
apk update
#安装软件
apk add vim
#删除软件
apk del openssh openntp vim
3.4Debian(ubuntu)系统建议安装的基础包
在很多软件官方提供的镜像都使用的是Debian(ubuntu)的系统,比如:nginx,tomcat,mysql,httpd 等,但镜像内缺少很多常用的调试工具.当需要进入容器内进行调试管理时,可以安装以下常用工具包
# apt update #安装软件前需要先更新索引
# apt install procps #提供top,ps,free等命令
# apt install psmisc #提供pstree,killall等命令
# apt install iputils-ping #提供ping命令
# apt install net-tools #提供netstat网络工具等
3.5下载镜像
从 docker 仓库将镜像下载到本地,命令格式如下:
docker pull [OPTIONS] NAME[:TAG|@DIGEST]
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
NAME: 是镜像名,一般的形式 仓库服务器:端口/项目名称/镜像名称
:TAG: 即版本号,如果不指定:TAG,则下载最新版镜像
镜像下载说明
root@ubuntu1804:~# docker pull hello-world
Using default tag: latest #默认下载最新版本
latest: Pulling from library/hello-world
2db29710123e: Pull complete #分层下载
Digest: sha256:37a0b92b08d4919615c3ee023f7ddb068d12b8387475d64c622ac30f45c29c51 #摘要
Status: Downloaded newer image for hello-world:latest
docker.io/library/hello-world:latest #下载的完整地址
镜像下载保存的路径:
/var/lib/docker/overlay2/镜像ID
注意: 镜像下载完成后,会自动解压缩,比官网显示的可能会大很多,如: centos8.1.1911下载时只有70MB,下载完后显示237MB
#下载hello-world镜像后查看镜像下载后保存路径
root@ubuntu1804:~# du -sh /var/lib/docker/overlay2/
40K /var/lib/docker/overlay2/
root@ubuntu1804:~# ls /var/lib/docker/overlay2/
ef3c9e0d87acecf57dfef36e1167ba345e71abf5b22ffeba81049f048686a8a3 l
#下载centos后再次查看镜像下载后保存路径
root@ubuntu1804:~# docker pull centos:centos8.1.1911
centos8.1.1911: Pulling from library/centos
8a29a15cefae: Pull complete
Digest: sha256:fe8d824220415eed5477b63addf40fb06c3b049404242b31982106ac204f6700
Status: Downloaded newer image for centos:centos8.1.1911
docker.io/library/centos:centos8.1.1911
root@ubuntu1804:~# ls /var/lib/docker/overlay2/
5f2722f01379e8231d4df39e4e3a69a446466ed2f8595e3f91d9bde62db90772 l
ef3c9e0d87acecf57dfef36e1167ba345e71abf5b22ffeba81049f048686a8a3
root@ubuntu1804:~# du -sh /var/lib/docker/overlay2/
252M /var/lib/docker/overlay2/
root@ubuntu1804:~# du -sh /var/lib/docker/overlay2/*
252M /var/lib/docker/overlay2/5f2722f01379e8231d4df39e4e3a69a446466ed2f8595e3f91d9bde62db90772
28K /var/lib/docker/overlay2/ef3c9e0d87acecf57dfef36e1167ba345e71abf5b22ffeba81049f048686a8a3
12K /var/lib/docker/overlay2/l
#l目录下存放的就是镜像文件的软链接
root@ubuntu1804:~# ls -l /var/lib/docker/overlay2/l
total 8
lrwxrwxrwx 1 root root 72 Nov 3 07:57 I7VAHTTML2C5ZVJIBXPVA65MDW -> ../5f2722f01379e8231d4df39e4e3a69a446466ed2f8595e3f91d9bde62db90772/diff
lrwxrwxrwx 1 root root 72 Nov 3 07:45 OKXNGYNB7WIULOIF4BK4FYAGJU -> ../ef3c9e0d87acecf57dfef36e1167ba345e71abf5b22ffeba81049f048686a8a3/diff
#查看镜像
root@ubuntu1804:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
centos centos8.1.1911 470671670cac 21 months ago 237MB
指定TAG下载特定版本镜像
root@ubuntu1804:~# docker pull httpd:bullseye
bullseye: Pulling from library/httpd
7d63c13d9b9b: Pull complete
ca52f3eeea66: Pull complete
448256567156: Pull complete
21d69ac90caf: Pull complete
462e88bc3074: Pull complete
Digest: sha256:f70876d78442771406d7245b8d3425e8b0a86891c79811af94fb2e12af0fadeb
Status: Downloaded newer image for httpd:bullseye
docker.io/library/httpd:bullseye
root@ubuntu1804:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
httpd bullseye 1132a4fc88fa 12 days ago 143MB
指定DIGEST下载特定版本的镜像(相对麻烦基本不用)
root@ubuntu1804:~# docker pull alpine@sha256:e15947432b813e8ffa90165da919953e2ce850bef511a0ad1287d7cb86de84b5
sha256:e15947432b813e8ffa90165da919953e2ce850bef511a0ad1287d7cb86de84b5: Pulling from library/alpine
4e9f2cdf4387: Pull complete
Digest: sha256:e15947432b813e8ffa90165da919953e2ce850bef511a0ad1287d7cb86de84b5
Status: Downloaded newer image for alpine@sha256:e15947432b813e8ffa90165da919953e2ce850bef511a0ad1287d7cb86de84b5
docker.io/library/alpine@sha256:e15947432b813e8ffa90165da919953e2ce850bef511a0ad1287d7cb86de84b5
root@ubuntu1804:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
httpd bullseye 1132a4fc88fa 12 days ago 143MB
alpine <none> 12adea71a33b 2 months ago 5.61MB
3.6docker镜像加速配置
docker 镜像官方的下载站点是: https://hub.docker.com/
从国内下载官方的镜像站点有时候会很慢,因此可以更改docker配置文件添加一个加速器,可以通过加速器达到加速下载镜像的目的
国内有许多公司都提供了docker 加速镜像,比如: 阿里云,腾讯云,网易云,以下以阿里云为例
3.6.1阿里云获取加速地址
浏览器打开http://cr.console.aliyun.com,注册或登录阿里云账号,点击左侧的镜像加速器,将会得到一个专属的加速地址,而且下面有使用配置说明:
3.6.2docker镜像加速配置
1. 安装/升级Docker客户端
推荐安装1.10.0以上版本的Docker客户端,参考文档docker-ce
2. 配置镜像加速器
针对Docker客户端版本大于 1.10.0 的用户
您可以通过修改daemon配置文件/etc/docker/daemon.json来使用加速器
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://eg3wr73p.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker
#网易云: http://hub-mirror.c.163.com/
#腾讯云: https://mirror.ccs.tencentyun.com
root@ubuntu1804:~# docker info | tail
ID: 4V7J:72BA:H34E:C2T5:UG7Y:TROY:I3EV:5ZJ2:M565:UIGO:DVRS:7SI7
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
root@ubuntu1804:~# mkdir -p /etc/docker
root@ubuntu1804:~# tee /etc/docker/daemon.json <<-'EOF'
> {
> "registry-mirrors": ["https://eg3wr73p.mirror.aliyuncs.com"]
> }
> EOF
{
"registry-mirrors": ["https://eg3wr73p.mirror.aliyuncs.com"]
}
root@ubuntu1804:~# systemctl daemon-reload
root@ubuntu1804:~# systemctl restart docker
root@ubuntu1804:~# docker info | tail
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://eg3wr73p.mirror.aliyuncs.com/
Live Restore Enabled: false
3.7查看本地镜像
docker images 可以查看下载至本地的镜像
格式:
docker images [OPTIONS] [REPOSITORY[:TAG]]
docker image ls [OPTIONS] [REPOSITORY[:TAG]]
#常用选项:
-q, --quiet Only show numeric IDs
-a, --all Show all images (default hides intermediate images)
--digests Show digests
--no-trunc Don't truncate output
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print images using a Go template
执行结果的显示信息说明:
REPOSITORY #镜像所属的仓库名称
TAG #镜像版本号(标识符),默认为latest
IMAGE ID #镜像唯一ID标识,如果ID相同,说明是同一个镜像有多个名称
CREATED #镜像在仓库中被创建时间
VIRTUAL SIZE #镜像的大小
#显示所有图像(默认隐藏中间图像)
root@ubuntu1804:~# docker images -a
REPOSITORY TAG IMAGE ID CREATED SIZE
httpd bullseye 1132a4fc88fa 12 days ago 143MB
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
alpine <none> 12adea71a33b 2 months ago 5.61MB
centos centos8.1.1911 470671670cac 21 months ago 237MB
#默认为-a选项
root@ubuntu1804:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
httpd bullseye 1132a4fc88fa 12 days ago 143MB
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
alpine <none> 12adea71a33b 2 months ago 5.61MB
centos centos8.1.1911 470671670cac 21 months ago 237MB
#只显示镜像ID
root@ubuntu1804:~# docker images -q
1132a4fc88fa
feb5d9fea6a5
12adea71a33b
470671670cac
#显示完整的ImageID
root@ubuntu1804:~# docker images --no-trunc
REPOSITORY TAG IMAGE ID CREATED SIZE
httpd bullseye sha256:1132a4fc88faaf5c19959f03535c1356d3004ced1978cb9c3f32e73d9c139532 12 days ago 143MB
hello-world latest sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412 5 weeks ago 13.3kB
alpine <none> sha256:12adea71a33bcce0925f5b2e951992cc2d8b69f4051122e93d5c35000e9b9e28 2 months ago 5.61MB
centos centos8.1.1911 sha256:470671670cac686c7cf0081e0b37da2e9f4f768ddc5f6a26102ccd1c6954c1ee 21 months ago 237MB
#只查看指定REPOSITORY的镜像
root@ubuntu1804:~# docker images httpd
REPOSITORY TAG IMAGE ID CREATED SIZE
httpd bullseye 1132a4fc88fa 12 days ago 143MB
#查看指定镜像的详细信息(此处使用镜像ID)
root@ubuntu1804:~# docker image inspect 1132a4fc88fa
[
{
"Id": "sha256:1132a4fc88faaf5c19959f03535c1356d3004ced1978cb9c3f32e73d9c139532",
"RepoTags": [
"httpd:bullseye"
],
"RepoDigests": [
"httpd@sha256:f70876d78442771406d7245b8d3425e8b0a86891c79811af94fb2e12af0fadeb"
],
"Parent": "",
"Comment": "",
"Created": "2021-10-21T23:37:11.283670489Z",
"Container": "116379462b4e920f9cdf0291a61327ecb028b2be4ebc9776b7b4c068e5088a7d",
"ContainerConfig": {
"Hostname": "116379462b4e",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"80/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/apache2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"HTTPD_PREFIX=/usr/local/apache2",
"HTTPD_VERSION=2.4.51",
"HTTPD_SHA256=20e01d81fecf077690a4439e3969a9b22a09a8d43c525356e863407741b838f4",
"HTTPD_PATCHES="
],
"Cmd": [
"/bin/sh",
"-c",
"#(nop) ",
"CMD [\"httpd-foreground\"]"
],
"Image": "sha256:e98023b63ac1be5cb86a845b3ba8b31e2b5b11bdf0cf17251e4ead0b692c4179",
"Volumes": null,
"WorkingDir": "/usr/local/apache2",
"Entrypoint": null,
"OnBuild": null,
"Labels": {},
"StopSignal": "SIGWINCH"
},
"DockerVersion": "20.10.7",
"Author": "",
"Config": {
"Hostname": "",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"80/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/apache2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"HTTPD_PREFIX=/usr/local/apache2",
"HTTPD_VERSION=2.4.51",
"HTTPD_SHA256=20e01d81fecf077690a4439e3969a9b22a09a8d43c525356e863407741b838f4",
"HTTPD_PATCHES="
],
"Cmd": [
"httpd-foreground"
],
"Image": "sha256:e98023b63ac1be5cb86a845b3ba8b31e2b5b11bdf0cf17251e4ead0b692c4179",
"Volumes": null,
"WorkingDir": "/usr/local/apache2",
"Entrypoint": null,
"OnBuild": null,
"Labels": null,
"StopSignal": "SIGWINCH"
},
"Architecture": "amd64",
"Os": "linux",
"Size": 143471612,
"VirtualSize": 143471612,
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/3551f5d25d81290a589900fe6a8ef64d5701d1dfacce21058da8f86679947cc2/diff:/var/lib/docker/overlay2/90316df61625f5c7c85fddfa3caef173f29d29d862577bdc6376b39239ab7389/diff:/var/lib/docker/overlay2/5e7b819ffff4d979bd0c5df8707a569ed928dbd1b6091b6cd237504855d3d9fd/diff:/var/lib/docker/overlay2/7ea3a704d1fdfdba12ddf3e1b9fdedc75330b7f9645378623fd4b4b278be7d20/diff",
"MergedDir": "/var/lib/docker/overlay2/9bd6b4c5b956ecfee578c70e681c2cbce8e3f0caaf712698f7734a499cfbe9c6/merged",
"UpperDir": "/var/lib/docker/overlay2/9bd6b4c5b956ecfee578c70e681c2cbce8e3f0caaf712698f7734a499cfbe9c6/diff",
"WorkDir": "/var/lib/docker/overlay2/9bd6b4c5b956ecfee578c70e681c2cbce8e3f0caaf712698f7734a499cfbe9c6/work"
},
"Name": "overlay2"
},
"RootFS": {
"Type": "layers",
"Layers": [
"sha256:e8b689711f21f9301c40bf2131ce1a1905c3aa09def1de5ec43cf0adf652576e",
"sha256:7511c367f47aaabefb9af479612cc56c32ba57081a5a9f15ccb9221554210932",
"sha256:ecd2b49ef24384330f9392951608e1d35e9f16a5de113e25d6d95b734ad7fafc",
"sha256:c86537ee54f93994c13fb72e5c6b7b399eb1b7c51683de3e381dd0141ec6a313",
"sha256:4dcdec0b7a0eaf4dec50e484e54440d73071ae77a99eee69e20b6ffcc18ee640"
]
},
"Metadata": {
"LastTagTime": "0001-01-01T00:00:00Z"
}
}
]
#查看指定镜像的详细信息(此处使用镜像所属仓库名称)
root@ubuntu1804:~# docker image inspect httpd
[]
Error: No such image: httpd
3.8镜像导出
利用docker save命令可以将从本地镜像导出为一个打包 tar文件,然后复制到其他服务器进行导入使用(主要用于某些场合设备无法上网,通过可以上网的设备下载镜像后导出上传在内网中进行使用)
格式:
docker save [OPTIONS] IMAGE [IMAGE...]
选项:
-o, --output string Write to a file, instead of STDOUT
常见用法:
docker save -o /path/file.tar IMAGE1 IMAGE2 ...
docker save IMAGE1 IMAGE2 ... > /path/file.tar
#镜像导出
root@ubuntu1804:~# docker save hello-world:latest alpine -o /root/all1.tar
或者
root@ubuntu1804:~# docker save hello-world:latest alpine > /root/all2.tar
root@ubuntu1804:~# ll /root/all*
-rw-r--r-- 1 root root 5910016 Nov 3 08:57 /root/all2.tar
-rw------- 1 root root 5910016 Nov 3 08:56 /root/all1.tar
注意:虽然这两种方式都可以进行镜像导出,但是还是存在区别,二者生成的文件的文件权限并不相同
3.9镜像导入
利用docker load命令可以将镜像导出的压缩文件再导入
格式:
docker load [OPTIONS]
#选项
-i, --input string Read from tar archive file, instead of STDIN
-q, --quiet Suppress the load output
#将镜像包上传到目标设备
root@ubuntu1804:~# scp /root/all1.tar 10.0.0.7:/root
The authenticity of host '10.0.0.7 (10.0.0.7)' can't be established.
ECDSA key fingerprint is SHA256:EhRn7J0u9r+JJyuwB4lfsRaW9BK32qKlMYndwzOndWI.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.7' (ECDSA) to the list of known hosts.
root@10.0.0.7's password:
all1.tar 100% 5772KB 77.4MB/s 00:00
[root@CT7test1 ~]# ll
total 140104
-rw-r--r--. 1 root root 5910016 Nov 3 09:05 all1.tar
-rw-------. 1 root root 1310 Oct 13 16:57 anaconda-ks.cfg
-rw-r--r--. 1 root root 677 Nov 2 14:06 install_docker_centos7.sh
-rw-------. 1 root root 137544192 Nov 2 16:01 nginx.tar
#镜像导入
[root@CT7test1 ~]# docker load -i /root/all1.tar
e07ee1baac5f: Loading layer 14.85kB/14.85kB
Loaded image: hello-world:latest
f1dd685eb59e: Loading layer 5.88MB/5.88MB
Loaded image ID: sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412
Loaded image ID: sha256:12adea71a33bcce0925f5b2e951992cc2d8b69f4051122e93d5c35000e9b9e28
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 87a94228f133 3 weeks ago 133MB
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
<none> <none> 12adea71a33b 2 months ago 5.61MB
或者
[root@CT7test1 ~]# docker load < /root/all1.tar
注意:对于TAG为none的镜像来说,将镜像导出再导入发现镜像所属仓库名称也变成了none
3.10镜像删除
docker rmi 命令可以删除本地镜像
格式
docker rmi [OPTIONS] IMAGE [IMAGE...]
docker image rm [OPTIONS] IMAGE [IMAGE...]
#选项:
-f, --force Force removal of the image
--no-prune Do not delete untagged parents
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 87a94228f133 3 weeks ago 133MB
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
<none> <none> 12adea71a33b 2 months ago 5.61MB
#通过镜像所属仓库名称和TAG进行删除
[root@CT7test1 ~]# docker rmi hello-world:latest
Untagged: hello-world:latest
Deleted: sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412
Deleted: sha256:e07ee1baac5fae6a26f30cabfe54a36d3402f96afda318fe0a96cec4ca393359
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 87a94228f133 3 weeks ago 133MB
<none> <none> 12adea71a33b 2 months ago 5.61MB
#通过镜像ID进行删除
[root@CT7test1 ~]# docker rmi 12adea71a33b
Deleted: sha256:12adea71a33bcce0925f5b2e951992cc2d8b69f4051122e93d5c35000e9b9e28
Deleted: sha256:f1dd685eb59e7d19dd353b02c4679d9fafd21ccffe1f51960e6c3645f3ceb0cd
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 87a94228f133 3 weeks ago 133MB
#同时删除多个镜像
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 87a94228f133 3 weeks ago 133MB
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
<none> <none> 12adea71a33b 2 months ago 5.61MB
[root@CT7test1 ~]# docker rmi hello-world 12adea71a33b
Untagged: hello-world:latest
Deleted: sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412
Deleted: sha256:e07ee1baac5fae6a26f30cabfe54a36d3402f96afda318fe0a96cec4ca393359
Deleted: sha256:12adea71a33bcce0925f5b2e951992cc2d8b69f4051122e93d5c35000e9b9e28
Deleted: sha256:f1dd685eb59e7d19dd353b02c4679d9fafd21ccffe1f51960e6c3645f3ceb0cd
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 87a94228f133 3 weeks ago 133MB
#强制删除正在使用的镜像,也会删除对应的容器(课件闪说会删除对应容器,但是尝试发现并不会删除)
[root@CT7test1 ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
88a9a9c400e4 httpd "httpd-foreground" About a minute ago Up About a minute 80/tcp awesome_cori
[root@CT7test1 ~]# docker rmi httpd:latest
Error response from daemon: conflict: unable to remove repository reference "httpd:latest" (must force) - container 88a9a9c400e4 is using its referenced image 1132a4fc88fa
[root@CT7test1 ~]# docker rmi -f httpd:latest
Untagged: httpd:latest
Untagged: httpd@sha256:f70876d78442771406d7245b8d3425e8b0a86891c79811af94fb2e12af0fadeb
[root@CT7test1 ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
88a9a9c400e4 httpd "httpd-foreground" About a minute ago Up About a minute 80/tcp awesome_cori
#删除所有镜像
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
<none> <none> 12adea71a33b 2 months ago 5.61MB
[root@CT7test1 ~]# docker rmi -f `docker images -q`
Untagged: hello-world:latest
Deleted: sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412
Deleted: sha256:e07ee1baac5fae6a26f30cabfe54a36d3402f96afda318fe0a96cec4ca393359
Deleted: sha256:12adea71a33bcce0925f5b2e951992cc2d8b69f4051122e93d5c35000e9b9e28
Deleted: sha256:f1dd685eb59e7d19dd353b02c4679d9fafd21ccffe1f51960e6c3645f3ceb0cd
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
3.11镜像打标签
docker tag 可以给镜像打标签,类似于起别名,但通常要遵守一定的命名规范,才可以上传到指定的仓库
格式
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
#TARGET_IMAGE[:TAG]格式一般形式
仓库主机FQDN或IP[:端口]/项目名(或用户名)/image名字:版本
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
[root@CT7test1 ~]# docker tag hello-world hello-world:test
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
hello-world test feb5d9fea6a5 5 weeks ago 13.3kB
命令总结:
docker search centos #搜索镜像
docker pull alpine #下载镜像
docker images #查看镜像
docker save > /opt/centos.tar #centos #导出镜像
docker load -i centos-latest.tar.xz #导入本地镜像
docker rmi 镜像ID/镜像名称 #删除指定ID的镜像,此镜像对应容器正启动镜像不能被删除,除非将容器全部关闭
4、容器操作基本命令
容器生命周期
容器相关命令
[root@CT7test1 ~]# docker container
Usage: docker container COMMAND
Manage containers
Commands:
attach Attach local standard input, output, and error streams to a running container
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
exec Run a command in a running container
export Export a container's filesystem as a tar archive
inspect Display detailed information on one or more containers
kill Kill one or more running containers
logs Fetch the logs of a container
ls List containers
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
prune Remove all stopped containers
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
run Run a command in a new container
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
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
wait Block until one or more containers stop, then print their exit codes
Run 'docker container COMMAND --help' for more information on a command.
[root@CT7test1 ~]#
4.1启动容器
docker run 可以启动容器,进入到容器,并随机生成容器ID和名称
[root@CT7test1 ~]# docker pull hello-world
Using default tag: latest
latest: Pulling from library/hello-world
2db29710123e: Pull complete
Digest: sha256:37a0b92b08d4919615c3ee023f7ddb068d12b8387475d64c622ac30f45c29c51
Status: Downloaded newer image for hello-world:latest
docker.io/library/hello-world:latest
[root@CT7test1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 5 weeks ago 13.3kB
[root@CT7test1 ~]# docker run hello-world
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
[root@CT7test1 ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
42fc1681d5f3 hello-world "/hello" 16 seconds ago Exited (0) 15 seconds ago pedantic_payne
启动容器的流程
启动容器用法
帮助: man docker-run
命令格式:
docker run [选项] [镜像名] [shell命令] [参数]
#选项:
-i, --interactive Keep STDIN open even if not attached,通常和-t一起使用
-t, --tty 分配pseudo-TTY,通常和-i一起使用,注意对应的容器必须运行shell才支持进入
-d, --detach Run container in background and print container ID,台后运行,默认前台
--name string Assign a name to the container
--h, --hostname string Container host name
--rm Automatically remove the container when it exits
-p, --publish list Publish a container's port(s) to the host
-P, --publish-all Publish all exposed ports to random ports
--dns list Set custom DNS servers
--entrypoint string Overwrite the default ENTRYPOINT of the image
--restart policy
--privileged Give extended privileges to container
-e, --env=[] Set environment variables
--env-file=[] Read in a line delimited file of environment variables
–restart 可以指定四种不同的policy
policy | 说明 |
---|---|
no | Default is no,Do not automatically restart the container when it exits. |
on-failure[:max-retries] | on-failure[:max-retries] Restart only if the container exits with a non-zero exit status. Optionally, limit the number of restart retries the Docker daemon attempts |
always | Always restart the container regardless of the exit status. When you specify always, the Docker daemon will try to restart the container indefinitely. The container will also always start on daemon startup, regardless of thecurrent state of the container. |
unless-stopped | Always restart the container regardless of the exit status, but do not start it on daemon startup if the container has been put to a stopped state before. |
注意: 容器启动后,如果容器内没有前台运行的进程,将自动退出停止
从容器内退出,并停止容器
exit
从容器内退出,且容器不停止
同时按三个键,ctrl+p+q
运行容器
[root@CT7test1 ~]# docker run hello-world
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
[root@CT7test1 ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
42fc1681d5f3 hello-world "/hello" 16 seconds ago Exited (0) 15 seconds ago pedantic_payne
一次性运行容器中命令
#启动的容器在执行完shell命令就退出,用于测试
[root@CT7test1 ~]# docker run alpine echo 'test'
test
[root@CT7test1 ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b40a39e9b53f alpine "echo test" 23 seconds ago Exited (0) 22 seconds ago gracious_greider
运行交互式容器并退出
[root@CT7test1 ~]# docker run -it alpine
/ #
/ #
/ # ll
/bin/sh: ll: not found
/ # ls
bin etc lib mnt proc run srv tmp var
dev home media opt root sbin sys usr
/ # exit
#没用exit退出容器时查看进程显示为up
[root@CT7test1 ~]# docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9f8cfa57c0ee alpine "/bin/sh" 18 seconds ago Up 18 seconds brave_blackburn
#用exit退出后容器也停止
[root@CT7test1 ~]# docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9f8cfa57c0ee alpine "/bin/sh" 40 seconds ago Exited (0) 3 seconds ago brave_blackburn
[root@CT7test1 ~]# docker run -it alpine
/ #
/ #
/ #
/ # 同时按下三个键:ctrl+p+q,退出容器
/ # [root@CT7test1 ~]#
#此时查看容器进程依旧为up
[root@CT7test1 ~]# docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
db7e0adef478 alpine "/bin/sh" About a minute ago Up About a minute keen_wozniak
设置容器内的主机名
[root@CT7test1 ~]# docker run -it -h haha alpine
/ # hostname
haha
/ #
/ # cat /etc/host
hostname hosts
/ # cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3 haha
/ #
一次性运行容器,退出后立即删除,用于测试
[root@CT7test1 ~]# docker run --rm alpine cat /etc/issue
Welcome to Alpine Linux 3.14
Kernel \r on an \m (\l)
[root@CT7test1 ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a2004bf1bb75 alpine "/bin/sh" 3 minutes ago Exited (0) 37 seconds ago quizzical_khorana
指定容器名称
[root@CT7test1 ~]# docker run -it --name a1 -h haha alpine
/ #
/ #
[root@CT7test1 ~]# docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4e23b160bc5d alpine "/bin/sh" 27 seconds ago Up 26 seconds a1
守护式容器:
- 能够长期运行
- 无需交互式会话
- 适合运行应用程序和服务
启动前台守护式容器(默认)
root@ubuntu1804:~# docker run nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
b380bbd43752: Pull complete
fca7e12d1754: Pull complete
745ab57616cb: Pull complete
a4723e260b6f: Pull complete
1c84ebdff681: Pull complete
858292fd2e56: Pull complete
Digest: sha256:644a70516a26004c97d0d85c7fe1d0c3a67ea8ab7ddf4aff193d9f301670cf36
Status: Downloaded newer image for nginx:latest
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/11/03 03:18:01 [notice] 1#1: using the "epoll" event method
2021/11/03 03:18:01 [notice] 1#1: nginx/1.21.3
2021/11/03 03:18:01 [notice] 1#1: built by gcc 8.3.0 (Debian 8.3.0-6)
2021/11/03 03:18:01 [notice] 1#1: OS: Linux 4.15.0-112-generic
2021/11/03 03:18:01 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/11/03 03:18:01 [notice] 1#1: start worker processes
2021/11/03 03:18:01 [notice] 1#1: start worker process 30
2021/11/03 03:18:01 [notice] 1#1: start worker process 31
...
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
852549c95e98 nginx "/docker-entrypoint.…" About a minute ago Up About a minute 80/tcp optimistic_yonath
#ctrl+c中断运行后
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
852549c95e98 nginx "/docker-entrypoint.…" 2 minutes ago Exited (0) 39 seconds ago optimistic_yonath
启动后台守护式容器
root@ubuntu1804:~# docker run -d nginx
ccde50c919e26880ea7604e53a63fc6095e3ec2e43eea26769a2b5ffa3ffefb2
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ccde50c919e2 nginx "/docker-entrypoint.…" 14 seconds ago Up 13 seconds 80/tcp zen_lumiere
开机自动运行容器
#后台守护运行nginx
root@ubuntu1804:~# docker run -d --name nginx -p 80:80 nginx
afeac74633c5ee520592fc89248379b30a3b068411b9bb5e290021add33c3d1f
root@ubuntu1804:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
afeac74633c5 nginx "/docker-entrypoint.…" 7 seconds ago Up 6 seconds 0.0.0.0:80->80/tcp nginx
#重启设备
root@ubuntu1804:~# reboot
root@ubuntu1804:/home/sx# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
*后台守护的进程在设备重启后没有自动运行
#设置容器总是运行
#直接进行配置提示容器名nginx已经被使用,虽然不在执行了但是存在
root@ubuntu1804:~# docker run -d --name nginx --restart always -p 80:80 nginx
docker: Error response from daemon: Conflict. The container name "/nginx" is already in use by container "afeac74633c5ee520592fc89248379b30a3b068411b9bb5e290021add33c3d1f". You have to remove (or rename) that container to be able to reuse that name.
See 'docker run --help'.
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
afeac74633c5 nginx "/docker-entrypoint.…" 6 minutes ago Exited (0) 6 minutes ago nginx
#删除进程
root@ubuntu1804:~# docker rm -f afeac74633c5
afeac74633c5
#再次配置
root@ubuntu1804:~# docker run -d --name nginx --restart always -p 80:80 nginx
1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de
root@ubuntu1804:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1ef6b018d6c9 nginx "/docker-entrypoint.…" 6 seconds ago Up 5 seconds 0.0.0.0:80->80/tcp nginx
#重启设备
root@ubuntu1804:~# reboot
root@ubuntu1804:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1ef6b018d6c9 nginx "/docker-entrypoint.…" 3 minutes ago Up 40 seconds 0.0.0.0:80->80/tcp nginx
#此时直接开机自动运行
–privileged 选项
大约在0.6版,–privileged 选项被引入docker。使用该参数,container内的root拥有真正的root权限。
否则,container内的root只是外部的一个普通用户权限。privileged启动的容器,可以看到很多host上的设备,并且可以执行mount。甚至允许你在docker容器中启动docker容器。
注意:这个其实是很危险的,因为可以通过容器对宿主机进行修改,所以通常是不会使用此选项的
[root@centos8 ~]#podman run -it centos
[root@382ab09932a7 /]#cat /etc/redhat-release
CentOS Linux release 8.1.1911 (Core)
[root@382ab09932a7 /]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 200G 0 disk
|-sda1 8:1 0 1G 0 part
|-sda2 8:2 0 100G 0 part
|-sda3 8:3 0 50G 0 part
|-sda4 8:4 0 1K 0 part
`-sda5 8:5 0 2G 0 part [SWAP]
sr0 11:0 1 7G 0 rom
[root@382ab09932a7 /]# mount /dev/sda3 /mnt
mount: /mnt: permission denied.
[root@382ab09932a7 /]# exit
exit
#利用--privileged 选项运行容器
[root@centos8 ~]#podman run -it --privileged centos
#可以看到宿主机的设备
[root@a6391a8f82e3 /]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 200G 0 disk
|-sda1 8:1 0 1G 0 part
|-sda2 8:2 0 100G 0 part
|-sda3 8:3 0 50G 0 part
|-sda4 8:4 0 1K 0 part
`-sda5 8:5 0 2G 0 part [SWAP]
sr0 11:0 1 7G 0 rom
[root@a6391a8f82e3 /]# df
Filesystem 1K-blocks Used Available Use% Mounted on
overlay 104806400 2754832 102051568 3% /
tmpfs 65536 0 65536 0% /dev
tmpfs 408092 5892 402200 2% /etc/hosts
shm 64000 0 64000 0% /dev/shm
tmpfs 408092 0 408092 0% /sys/fs/cgroup
[root@a6391a8f82e3 /]# mount /dev/sda3 /mnt
[root@a6391a8f82e3 /]# df
Filesystem 1K-blocks Used Available Use% Mounted on
overlay 104806400 2754632 102051768 3% /
tmpfs 65536 0 65536 0% /dev
tmpfs 408092 5892 402200 2% /etc/hosts
shm 64000 0 64000 0% /dev/shm
tmpfs 408092 0 408092 0% /sys/fs/cgroup
/dev/sda3 52403200 619068 51784132 2% /mnt
[root@a6391a8f82e3 /]# touch /mnt/containter.txt
[root@a6391a8f82e3 /]# echo container data > /mnt/containter.txt
[root@a6391a8f82e3 /]# cat /mnt/containter.txt
container data
[root@a6391a8f82e3 /]#
#在宿主机查看是否生成文件
[root@centos8 ~]#lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 200G 0 disk
├─sda1 8:1 0 1G 0 part /boot
├─sda2 8:2 0 100G 0 part /
├─sda3 8:3 0 50G 0 part /data
├─sda4 8:4 0 1K 0 part
└─sda5 8:5 0 2G 0 part [SWAP]
sr0 11:0 1 7G 0 rom
[root@centos8 ~]#ll /data/containter.txt
-rw-r--r-- 1 root root 25 Feb 29 12:26 /data/containter.txt
[root@centos8 ~]#cat /data/containter.txt
container data
[root@centos8 ~]#echo host data >> /data/containter.txt
[root@centos8 ~]#cat /data/containter.txt
container data
host data
#在容器内可看文件是否发生变化
[root@a6391a8f82e3 /]# cat /mnt/containter.txt
container data
host data
运行docker官方文档容器
[root@centos8 ~]#podman run -it -d -p 4000:4000 docs/docker.github.io:latest
[root@centos8 ~]#podman images docs/docker.github.io
REPOSITORY TAG IMAGE ID CREATED SIZE
docker.io/docs/docker.github.io latest ffd9131eeee7 2 days ago 1.99 GB
#用浏览器访问http://localhost:4000/可以看到下面docker文档资料
4.2查看容器信息
4.2.1显示当前存在容器
格式
docker ps [OPTIONS]
docker container ls [OPTIONS]
选项:
-a, --all Show all containers (default shows just running)
-q, --quiet Only display numeric IDs
-s, --size Display total file sizes
-f, --filter filter Filter output based on conditions provided
-l, --latest Show the latest created container (includes all states)
-n, --last int Show n last created containers (includes all states)
(default -1)
#显示运行的容器
root@ubuntu1804:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1ef6b018d6c9 nginx "/docker-entrypoint.…" 3 hours ago Up 3 hours 0.0.0.0:80->80/tcp nginx
#显示全部容器,包括退出状态的容器
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1ef6b018d6c9 nginx "/docker-entrypoint.…" 3 hours ago Up 3 hours 0.0.0.0:80->80/tcp nginx
cebc316cec5d alpine "/bin/sh" 3 hours ago Exited (0) 3 hours ago hungry_brown
326b926a793d nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago bold_antonelli
ccde50c919e2 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago zen_lumiere
30b7a5e0e033 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago gallant_lalande
1e13a0a4c0a9 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago romantic_ramanujan
852549c95e98 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago optimistic_yonath
3704cda01653 httpd "httpd-foreground" 5 hours ago Exited (0) 5 hours ago cocky_hamilton
b414bc9c6d91 httpd "httpd-foreground" 5 hours ago Exited (0) 5 hours ago condescending_heisenberg
root@ubuntu1804:~#
#只显示容器ID
root@ubuntu1804:~# docker ps -a -q
1ef6b018d6c9
cebc316cec5d
326b926a793d
ccde50c919e2
30b7a5e0e033
1e13a0a4c0a9
852549c95e98
3704cda01653
b414bc9c6d91
#显示容器大小
root@ubuntu1804:~# docker ps -a -s
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE
1ef6b018d6c9 nginx "/docker-entrypoint.…" 3 hours ago Up 3 hours 0.0.0.0:80->80/tcp nginx 1.09kB (virtual 133MB)
cebc316cec5d alpine "/bin/sh" 3 hours ago Exited (0) 3 hours ago hungry_brown 5B (virtual 5.6MB)
326b926a793d nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago bold_antonelli 1.09kB (virtual 133MB)
ccde50c919e2 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago zen_lumiere 1.09kB (virtual 133MB)
30b7a5e0e033 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago gallant_lalande 1.09kB (virtual 133MB)
1e13a0a4c0a9 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago romantic_ramanujan 1.09kB (virtual 133MB)
852549c95e98 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago optimistic_yonath 1.09kB (virtual 133MB)
3704cda01653 httpd "httpd-foreground" 5 hours ago Exited (0) 5 hours ago cocky_hamilton 0B (virtual 143MB)
b414bc9c6d91 httpd "httpd-foreground" 5 hours ago Exited (0) 5 hours ago condescending_heisenberg 0B (virtual 143MB)
#显示最新创建的容器(停止的容器也能显示)
root@ubuntu1804:~# docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1ef6b018d6c9 nginx "/docker-entrypoint.…" 3 hours ago Up 3 hours 0.0.0.0:80->80/tcp nginx
#显示指定状态的容器
#显示name=nginx的容器
root@ubuntu1804:~# docker ps -f 'name=nginx'
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1ef6b018d6c9 nginx "/docker-entrypoint.…" 3 hours ago Up 3 hours 0.0.0.0:80->80/tcp nginx
#显示状态为exited的容器
root@ubuntu1804:~# docker ps -f 'status=exited'
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
cebc316cec5d alpine "/bin/sh" 3 hours ago Exited (0) 3 hours ago hungry_brown
326b926a793d nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago bold_antonelli
ccde50c919e2 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago zen_lumiere
30b7a5e0e033 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago gallant_lalande
1e13a0a4c0a9 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago romantic_ramanujan
852549c95e98 nginx "/docker-entrypoint.…" 3 hours ago Exited (0) 3 hours ago optimistic_yonath
3704cda01653 httpd "httpd-foreground" 5 hours ago Exited (0) 5 hours ago cocky_hamilton
b414bc9c6d91 httpd "httpd-foreground" 5 hours ago Exited (0) 5 hours ago condescending_heisenberg
4.2.2查看容器内的进程
docker top CONTAINER [ps OPTIONS]
root@ubuntu1804:~# docker top 1ef6b018d6c9
UID PID PPID C STIME TTY TIME CMD
root 1252 1225 0 11:39 ? 00:00:00 nginx: master process nginx -g daemon off;
systemd+ 1316 1252 0 11:39 ? 00:00:00 nginx: worker process
systemd+ 1317 1252 0 11:39 ? 00:00:00 nginx: worker process
root@ubuntu1804:~# docker run -d alpine /bin/sh -c 'i=1;while true;do echo hello$i;let i++;sleep 1;done'
cf9e44f5760f8b759bc6584557a347d4548dae6701d135f1ac77d453b557edaf
root@ubuntu1804:~# docker top cf9e
UID PID PPID C STIME TTY TIME CMD
root 1919 1889 0 14:47 ? 00:00:00 /bin/sh -c i=1;while true;do echo hello$i;let i++;sleep 1;done
root 1994 1919 0 14:47 ? 00:00:00 sleep 1
4.2.3查看容器资源使用情况
格式
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
root@ubuntu1804:~# docker stats cf9e
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
cf9e44f5760f hungry_kapitsa 0.06% 1.363MiB / 962.2MiB 0.14% 866B / 0B 1.25MB / 0B 2
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
cf9e44f5760f hungry_kapitsa 0.06% 1.348MiB / 962.2MiB 0.14% 866B / 0B 1.25MB / 0B 2
4.2.4查看容器的详细信息
docker inspect 可以查看docker各种对象的详细信息,包括:镜像,容器,网络等
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
Options:
-f, --format string Format the output using the given Go template
-s, --size Display total file sizes if the type is container
注意:-f选项使用说明https://blog.csdn.net/m0_45406092/article/details/103671832
root@ubuntu1804:~# docker inspect 1ef6b018d6c9
[
{
"Id": "1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de",
"Created": "2021-11-03T03:36:18.248605535Z",
"Path": "/docker-entrypoint.sh",
"Args": [
"nginx",
"-g",
"daemon off;"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 2176,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-11-03T23:32:19.696218339Z",
"FinishedAt": "2021-11-03T06:55:10.219725948Z"
},
"Image": "sha256:87a94228f133e2da99cb16d653cd1373c5b4e8689956386c1c12b60a20421a02",
"ResolvConfPath": "/var/lib/docker/containers/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de/hostname",
"HostsPath": "/var/lib/docker/containers/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de/hosts",
"LogPath": "/var/lib/docker/containers/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de-json.log",
"Name": "/nginx",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "docker-default",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "default",
"PortBindings": {
"80/tcp": [
{
"HostIp": "",
"HostPort": "80"
}
]
},
"RestartPolicy": {
"Name": "always",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"Capabilities": null,
"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": [
0,
0
],
"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": false,
"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/cb49e1b87a299238049a559bc5317e829902a985c64880d20804c2f293653f5b-init/diff:/var/lib/docker/overlay2/9c7c84a53201e3eb0d7531b3cb70aca2cc80e65b96e16b290ac9100b4ec6a534/diff:/var/lib/docker/overlay2/d3456c263c1f544e75df39521844a33effe0db8ac521910d29c63593e37fd8b0/diff:/var/lib/docker/overlay2/5da51653852b78c39111efb11fb3716783bc14978fda657c99793e3a9c9673d5/diff:/var/lib/docker/overlay2/534ad811a360bf27cd45def798ae3bcfac0ac7394140c686a591f11470f71f99/diff:/var/lib/docker/overlay2/aca2b98286fc902a37a3fa550ef5aedf2aabb94d064ee5d771eb8d9da7d76b8c/diff:/var/lib/docker/overlay2/8948f42093ba558ac9e7d8b8f4ea186621c2bf0ec7f3508427c1e1f8f8740d7f/diff",
"MergedDir": "/var/lib/docker/overlay2/cb49e1b87a299238049a559bc5317e829902a985c64880d20804c2f293653f5b/merged",
"UpperDir": "/var/lib/docker/overlay2/cb49e1b87a299238049a559bc5317e829902a985c64880d20804c2f293653f5b/diff",
"WorkDir": "/var/lib/docker/overlay2/cb49e1b87a299238049a559bc5317e829902a985c64880d20804c2f293653f5b/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "1ef6b018d6c9",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"80/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"NGINX_VERSION=1.21.3",
"NJS_VERSION=0.6.2",
"PKG_RELEASE=1~buster"
],
"Cmd": [
"nginx",
"-g",
"daemon off;"
],
"Image": "nginx",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": [
"/docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": {
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
},
"StopSignal": "SIGQUIT"
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "aa472f8ac44783d164d3f68d6cb3cc91d014840c06a15e84880c363063808711",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"80/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "80"
}
]
},
"SandboxKey": "/var/run/docker/netns/aa472f8ac447",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "f4f1965de1700d8fd18d950f9053d89a1abecef0d3ae2e9708064c124045de97",
"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": "bd72601d45f070484445293f7985809020229422f7867bbf09bfaf8ce149f7c3",
"EndpointID": "f4f1965de1700d8fd18d950f9053d89a1abecef0d3ae2e9708064c124045de97",
"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
}
}
}
}
]
root@ubuntu1804:~# docker inspect nginx
[
{
"Id": "1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de",
"Created": "2021-11-03T03:36:18.248605535Z",
"Path": "/docker-entrypoint.sh",
"Args": [
"nginx",
"-g",
"daemon off;"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 2176,
"ExitCode": 0,
"Error": "",
"StartedAt": "2021-11-03T23:32:19.696218339Z",
"FinishedAt": "2021-11-03T06:55:10.219725948Z"
},
"Image": "sha256:87a94228f133e2da99cb16d653cd1373c5b4e8689956386c1c12b60a20421a02",
"ResolvConfPath": "/var/lib/docker/containers/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de/hostname",
"HostsPath": "/var/lib/docker/containers/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de/hosts",
"LogPath": "/var/lib/docker/containers/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de/1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de-json.log",
"Name": "/nginx",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "docker-default",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "default",
"PortBindings": {
"80/tcp": [
{
"HostIp": "",
"HostPort": "80"
}
]
},
"RestartPolicy": {
"Name": "always",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"Capabilities": null,
"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": [
0,
0
],
"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": false,
"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/cb49e1b87a299238049a559bc5317e829902a985c64880d20804c2f293653f5b-init/diff:/var/lib/docker/overlay2/9c7c84a53201e3eb0d7531b3cb70aca2cc80e65b96e16b290ac9100b4ec6a534/diff:/var/lib/docker/overlay2/d3456c263c1f544e75df39521844a33effe0db8ac521910d29c63593e37fd8b0/diff:/var/lib/docker/overlay2/5da51653852b78c39111efb11fb3716783bc14978fda657c99793e3a9c9673d5/diff:/var/lib/docker/overlay2/534ad811a360bf27cd45def798ae3bcfac0ac7394140c686a591f11470f71f99/diff:/var/lib/docker/overlay2/aca2b98286fc902a37a3fa550ef5aedf2aabb94d064ee5d771eb8d9da7d76b8c/diff:/var/lib/docker/overlay2/8948f42093ba558ac9e7d8b8f4ea186621c2bf0ec7f3508427c1e1f8f8740d7f/diff",
"MergedDir": "/var/lib/docker/overlay2/cb49e1b87a299238049a559bc5317e829902a985c64880d20804c2f293653f5b/merged",
"UpperDir": "/var/lib/docker/overlay2/cb49e1b87a299238049a559bc5317e829902a985c64880d20804c2f293653f5b/diff",
"WorkDir": "/var/lib/docker/overlay2/cb49e1b87a299238049a559bc5317e829902a985c64880d20804c2f293653f5b/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "1ef6b018d6c9",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"80/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"NGINX_VERSION=1.21.3",
"NJS_VERSION=0.6.2",
"PKG_RELEASE=1~buster"
],
"Cmd": [
"nginx",
"-g",
"daemon off;"
],
"Image": "nginx",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": [
"/docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": {
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
},
"StopSignal": "SIGQUIT"
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "aa472f8ac44783d164d3f68d6cb3cc91d014840c06a15e84880c363063808711",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"80/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "80"
}
]
},
"SandboxKey": "/var/run/docker/netns/aa472f8ac447",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "f4f1965de1700d8fd18d950f9053d89a1abecef0d3ae2e9708064c124045de97",
"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": "bd72601d45f070484445293f7985809020229422f7867bbf09bfaf8ce149f7c3",
"EndpointID": "f4f1965de1700d8fd18d950f9053d89a1abecef0d3ae2e9708064c124045de97",
"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
}
}
}
}
]
#选择性查看
root@ubuntu1804:~# docker inspect -f "{{.State.Pid}}" nginx
2176
4.3删除容器
docker rm 可以删除容器,即使容器正在运行当中,也可以被强制删除掉
格式
docker rm [OPTIONS] CONTAINER [CONTAINER...]
docker container rm [OPTIONS] CONTAINER [CONTAINER...]
#选项:
-f, --force Force the removal of a running container (uses SIGKILL)
-v, --volumes Remove the volumes associated with the container
#删除停止的容器
docker container prune [OPTIONS]
Options:
--filter filter Provide filter values (e.g. 'until=<timestamp>')
-f, --force Do not prompt for confirmation
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
cf9e44f5760f alpine "/bin/sh -c 'i=1;whi…" 17 hours ago Exited (137) 17 hours ago hungry_kapitsa
1ef6b018d6c9 nginx "/docker-entrypoint.…" 20 hours ago Up 20 minutes 0.0.0.0:80->80/tcp nginx
cebc316cec5d alpine "/bin/sh" 20 hours ago Exited (0) 20 hours ago hungry_brown
#指定容器id进行删除
root@ubuntu1804:~# docker rm cf9e44f5760f
cf9e44f5760f
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1ef6b018d6c9 nginx "/docker-entrypoint.…" 20 hours ago Up 21 minutes 0.0.0.0:80->80/tcp nginx
cebc316cec5d alpine "/bin/sh" 20 hours ago Exited (0) 20 hours ago hungry_brown
#指定容器名进行删除
root@ubuntu1804:~# docker rm hungry_brown
hungry_brown
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1ef6b018d6c9 nginx "/docker-entrypoint.…" 20 hours ago Up 22 minutes 0.0.0.0:80->80/tcp nginx
#删除正在运行的容器
root@ubuntu1804:~# docker rm nginx
Error response from daemon: You cannot remove a running container 1ef6b018d6c94fd1bfd85b698dc285778b23a1e7468251f7fa89e166150ed0de. Stop the container before attempting removal or force remove
root@ubuntu1804:~# docker rm -f nginx
nginx
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
#删除所有容器
root@ubuntu1804:~# docker rm -f `docker ps -a -q`
326b926a793d
ccde50c919e2
30b7a5e0e033
1e13a0a4c0a9
852549c95e98
3704cda01653
b414bc9c6d91
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
#删除指定状态的容器
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e8e586314a54 hello-world "/hello" 7 seconds ago Exited (0) 6 seconds ago musing_nobel
b5d5f064e1e4 nginx "/docker-entrypoint.…" 19 seconds ago Up 18 seconds 80/tcp hopeful_greider
e5ddcae9d607 httpd "httpd-foreground" 34 seconds ago Exited (0) 27 seconds ago magical_mayer
root@ubuntu1804:~# docker rm -f `docker ps -qf status=exited`
e8e586314a54
e5ddcae9d607
#说明:-q选项只显示id,-f选项根据提供的条件进行过滤输出
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b5d5f064e1e4 nginx "/docker-entrypoint.…" 3 minutes ago Up 3 minutes 80/tcp hopeful_greider
#删除所有停止的容器
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
43a76849f318 alpine "/bin/sh" 9 seconds ago Exited (0) 8 seconds ago sleepy_poincare
4e8e0e68fdf4 hello-world "/hello" 15 seconds ago Exited (0) 14 seconds ago lucid_banzai
0e7ad56bf036 nginx "/docker-entrypoint.…" 31 seconds ago Up 30 seconds 0.0.0.0:80->80/tcp nginx
b5d5f064e1e4 nginx "/docker-entrypoint.…" 8 minutes ago Up 8 minutes 80/tcp hopeful_greider
root@ubuntu1804:~# docker container prune -f
Deleted Containers:
43a76849f3181a589fca60a902021ee57dbdb168a4465de7d5878fcf7c75a176
4e8e0e68fdf4b92ae1a075ab3af172167d0820069cdc54d94922a18a773a8b84
Total reclaimed space: 0B
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0e7ad56bf036 nginx "/docker-entrypoint.…" About a minute ago Up About a minute 0.0.0.0:80->80/tcp nginx
b5d5f064e1e4 nginx "/docker-entrypoint.…" 9 minutes ago Up 9 minutes 80/tcp hopeful_greider
4.4容器的启动和停止
格式
docker start|stop|restart|pause|unpause 容器ID
批量正常启动或关闭所有容器
docker start $(docker ps -a -q)
docker stop $(docker ps -a -q)
root@ubuntu1804:~# docker ps -a
\CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
213003ccd025 httpd "httpd-foreground" 2 seconds ago Up 1 second 80/tcp kind_bell
0e7ad56bf036 nginx "/docker-entrypoint.…" 9 minutes ago Up 9 minutes 0.0.0.0:80->80/tcp nginx
b5d5f064e1e4 nginx "/docker-entrypoint.…" 17 minutes ago Up 17 minutes 80/tcp hopeful_greider
#停止容器
root@ubuntu1804:~# docker stop 213003ccd025
213003ccd025
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
213003ccd025 httpd "httpd-foreground" 31 seconds ago Exited (0) 2 seconds ago kind_bell
0e7ad56bf036 nginx "/docker-entrypoint.…" 9 minutes ago Up 9 minutes 0.0.0.0:80->80/tcp nginx
b5d5f064e1e4 nginx "/docker-entrypoint.…" 18 minutes ago Up 17 minutes 80/tcp hopeful_greider
#启动容器
root@ubuntu1804:~# docker start 213003ccd025
213003ccd025
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
213003ccd025 httpd "httpd-foreground" 56 seconds ago Up 2 seconds 80/tcp kind_bell
0e7ad56bf036 nginx "/docker-entrypoint.…" 10 minutes ago Up 10 minutes 0.0.0.0:80->80/tcp nginx
b5d5f064e1e4 nginx "/docker-entrypoint.…" 18 minutes ago Up 18 minutes 80/tcp hopeful_greider
root@ubuntu1804:~#
#运行并进入容器
root@ubuntu1804:~# docker run --name=a1 -it alpine
/ #
/ # exit
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
de6319842a1a alpine "/bin/sh" 15 seconds ago Exited (0) 5 seconds ago a1
root@ubuntu1804:~# docker start a1
a1
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
de6319842a1a alpine "/bin/sh" 34 seconds ago Up 5 seconds a1
root@ubuntu1804:~# docker stop a1
a1
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
de6319842a1a alpine "/bin/sh" About a minute ago Exited (137) 3 seconds ago a1
#启动并进入容器
root@ubuntu1804:~# docker start -i a1
/ #
/ #
/ # exit
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
de6319842a1a alpine "/bin/sh" About a minute ago Exited (127) 7 seconds ago a1
#启动和停止所有容器
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
de6319842a1a alpine "/bin/sh" About a minute ago Exited (127) 7 seconds ago a1
213003ccd025 httpd "httpd-foreground" 9 minutes ago Up 8 minutes 80/tcp kind_bell
0e7ad56bf036 nginx "/docker-entrypoint.…" 18 minutes ago Up 18 minutes 0.0.0.0:80->80/tcp nginx
b5d5f064e1e4 nginx "/docker-entrypoint.…" 26 minutes ago Up 26 minutes 80/tcp hopeful_greider
root@ubuntu1804:~# docker stop `docker ps -aq`
de6319842a1a
213003ccd025
0e7ad56bf036
b5d5f064e1e4
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
de6319842a1a alpine "/bin/sh" 5 minutes ago Exited (127) 4 minutes ago a1
213003ccd025 httpd "httpd-foreground" 13 minutes ago Exited (0) 4 seconds ago kind_bell
0e7ad56bf036 nginx "/docker-entrypoint.…" 22 minutes ago Exited (0) 5 seconds ago nginx
b5d5f064e1e4 nginx "/docker-entrypoint.…" 30 minutes ago Exited (0) 5 seconds ago hopeful_greider
root@ubuntu1804:~# docker start `docker ps -aq`
de6319842a1a
213003ccd025
0e7ad56bf036
b5d5f064e1e4
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
de6319842a1a alpine "/bin/sh" 6 minutes ago Up 4 seconds a1
213003ccd025 httpd "httpd-foreground" 13 minutes ago Up 3 seconds 80/tcp kind_bell
0e7ad56bf036 nginx "/docker-entrypoint.…" 22 minutes ago Up 3 seconds 0.0.0.0:80->80/tcp nginx
b5d5f064e1e4 nginx "/docker-entrypoint.…" 30 minutes ago Up 2 seconds 80/tcp hopeful_greider
root@ubuntu1804:~#
#容器中进程的暂停与开启
root@ubuntu1804:~# docker run -d --name=nginx --restart always nginx
06175bf7e396a4b7e45eb310fe5d285f386ce24793b75869d99e77ccec8e28b7
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
06175bf7e396 nginx "/docker-entrypoint.…" 7 seconds ago Up 6 seconds 80/tcp nginx
root@ubuntu1804:~# docker top nginx
UID PID PPID C STIME TTY TIME CMD
root 9150 9125 0 08:44 ? 00:00:00 nginx: master process nginx -g daemon off;
systemd+ 9215 9150 0 08:44 ? 00:00:00 nginx: worker process
systemd+ 9216 9150 0 08:44 ? 00:00:00 nginx: worker process
root@ubuntu1804:~# ps aux | grep nginx
root 9150 0.0 0.5 10660 5852 ? Ss 08:44 0:00 nginx: master process nginx -g daemon off;
systemd+ 9215 0.0 0.2 11096 2544 ? S 08:44 0:00 nginx: worker process
systemd+ 9216 0.0 0.2 11096 2544 ? S 08:44 0:00 nginx: worker process
root 9430 0.0 0.1 14428 1088 pts/0 S+ 08:47 0:00 grep --color=auto nginx
#暂停容器中的进程
root@ubuntu1804:~# docker pause nginx
nginx
root@ubuntu1804:~# docker top nginx
UID PID PPID C STIME TTY TIME CMD
root 9150 9125 0 08:44 ? 00:00:00 nginx: master process nginx -g daemon off;
systemd+ 9215 9150 0 08:44 ? 00:00:00 nginx: worker process
systemd+ 9216 9150 0 08:44 ? 00:00:00 nginx: worker process
root@ubuntu1804:~# ps aux | grep nginx
root 9150 0.0 0.5 10660 5852 ? Ds 08:44 0:00 nginx: master process nginx -g daemon off;
systemd+ 9215 0.0 0.2 11096 2544 ? D 08:44 0:00 nginx: worker process
systemd+ 9216 0.0 0.2 11096 2544 ? D 08:44 0:00 nginx: worker process
root 9370 0.0 0.1 14428 1088 pts/0 S+ 08:46 0:00 grep --color=auto nginx
#开启容器中的进程
root@ubuntu1804:~# docker unpause nginx
nginx
root@ubuntu1804:~# ps aux | grep nginx
root 9150 0.0 0.5 10660 5852 ? Ss 08:44 0:00 nginx: master process nginx -g daemon off;
systemd+ 9215 0.0 0.2 11096 2544 ? S 08:44 0:00 nginx: worker process
systemd+ 9216 0.0 0.2 11096 2544 ? S 08:44 0:00 nginx: worker process
root 9430 0.0 0.1 14428 1088 pts/0 S+ 08:47 0:00 grep --color=auto nginx
4.5给正在运行的容器发信号
docker kill 可以给容器发信号,默认号SIGKILL,即9信号
格式
docker kill [OPTIONS] CONTAINER [CONTAINER...]
#选项:
-s, --signal string Signal to send to the container (default "KILL")
#关闭指定容器
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
06175bf7e396 nginx "/docker-entrypoint.…" 12 minutes ago Up 12 minutes 80/tcp nginx
root@ubuntu1804:~# docker kill nginx
nginx
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
06175bf7e396 nginx "/docker-entrypoint.…" 12 minutes ago Exited (137) 4 seconds ago nginx
#关闭所有容器
root@ubuntu1804:~# docker kill `docker ps -aq`
4.6进入正在运行的容器
4.6.1使用attach命令
docker attach 容器名,attach 类似于vnc,操作会在同一个容器的多个会话界面同步显示,所有使用此方式进入容器的操作都是同步显示的,且使用exit退出后容器自动关闭,不推荐使用,需要进入到有shell环境的容器
格式
docker attach [OPTIONS] CONTAINER
[root@ubuntu1804 ~]#docker run -it centos
[root@94a5c5c69b14 /]# cat /etc/redhat-release
CentOS Linux release 8.1.1911 (Core) #ctrl+p+q 退出
[root@94a5c5c69b14 /]# [root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
94a5c5c69b14 centos "/bin/bash" 14 seconds ago Up 14 seconds unruffled_ellis
[root@ubuntu1804 ~]#docker attach 94a5
[root@94a5c5c69b14 /]#cat /etc/redhat-release
#同时在第二个终端attach到同一个容器,执行命令,可以在前一终端看到显示图面是同步的
[root@ubuntu1804 ~]#docker attach 94a5
[root@94a5c5c69b14 /]#cat /etc/redhat-release
CentOS Linux release 8.1.1911 (Core)
[root@92a8279611a9 /]# exit #两个终端都同时退出
exit
[root@ubuntu1804 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
92a8279611a9 centos "/bin/bash" 4 minutes ago Exited (0) 39 seconds ago agitated_tesla
4.6.2使用exec命令
在运行中的容器启动新进程,可以执行单次命令,以及进入容器
测试环境使用此方式,使用exit退出,但容器还在运行,此为推荐方式
格式
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
常用选项:
-d, --detach Detached mode: run command in the background
-e, --env list Set environment variables
-i, --interactive Keep STDIN open even if not attached
-t, --tty Allocate a pseudo-TTY
#常见用法
docker exec -it 容器ID sh|bash
[root@ubuntu1804 ~]#docker run -itd centos
24788f69cec65e1f511387c1bae354a66e5b7ae29261e68957bc6dcc4818af6b
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
24788f69cec6 centos "/bin/bash" 3 seconds ago Up 1 second keen_jennings
#执行一次性命令
[root@ubuntu1804 ~]#docker exec 2478 cat /etc/redhat-release
CentOS Linux release 8.1.1911 (Core)
#进入容器,执行命令,exit退出但容器不停止
[root@ubuntu1804 ~]#docker exec -it 2478 bash
[root@24788f69cec6 /]# cat /etc/redhat-release
CentOS Linux release 8.1.1911 (Core)
[root@24788f69cec6 /]# exit
exit
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
24788f69cec6 centos "/bin/bash" 4 minutes ago Up 4 minutes keen_jennings
4.6.3 使用nsenter命令
nsenter命令需要通过PID进入到容器内部,且退出后仍然正常运行: 不过需要事先使用docker inspect获取到容器的PID, 目前此方式使用较少,此工具来自于util-linux包
#安装nsenter命令
yum -y install util-linux #CentOS
apt -y install util-linux #Ubuntu
#获取容器的IP
docker inspect -f "{{.NetworkSettings.IPAddress}}" 容器ID
#获取到某个docker容器的PID,可以通过PID进入到容器内
docker inspect -f "{{.State.Pid}}" 容器ID
nsenter -t PID -m -u -i -n -p
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ba792a7e0747 centos "/bin/bash" 17 minutes ago Up 17 minutes festive_babbage
[root@ubuntu1804 ~]#docker inspect -f {{.State}} ba792a7e0747
{running true false false false false 20536 0 2020-01-26T10:44:16.123961829Z0001-01-01T00:00:00Z <nil>}
[root@ubuntu1804 ~]#docker inspect -f {{.State.Status}} ba792a7e0747
running
[root@ubuntu1804 ~]#docker inspect -f {{.State.Pid}} ba792a7e0747
20536
[root@ubuntu1804 ~]#nsenter -t 20536 -m -u -i -n -p
[root@ba792a7e0747 /]# ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.3 12024 3172 pts/0 Ss+ 10:44 0:00 /bin/bash
root 46 0.0 0.3 12028 3312 ? S 11:02 0:00 -bash
root 61 0.0 0.3 43960 3352 ? R+ 11:02 0:00 ps aux
[root@ba792a7e0747 /]# exit
logout
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ba792a7e0747 centos "/bin/bash" 18 minutes ago Up 18 minutes festive_babbage
4.6.4 脚本方式
将nsenter命令写入到脚本进行调用,方便进入容器看日志或排错
[root@ubuntu1804 ~]#vim docker-in.sh
[root@ubuntu1804 ~]#cat docker-in.sh
#!/bin/bash
docker_in(){
NAME_ID=$1
PID=$(docker inspect -f "{{.State.Pid}}" ${NAME_ID})
nsenter -t ${PID} -m -u -i -n -p
}
docker_in $1
[root@ubuntu1804 ~]#chmod +x docker-in.sh
[root@ubuntu1804 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ba792a7e0747 centos "/bin/bash" 20 minutes ago Up 20 minutes festive_babbage
[root@ubuntu1804 ~]#./docker-in.sh ba792a7e0747
[root@ba792a7e0747 /]# cat /etc/redhat-release
CentOS Linux release 8.1.1911 (Core)
[root@ba792a7e0747 /]# exit
logout
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ba792a7e0747 centos "/bin/bash" 23 minutes ago Up 23 minutes festive_babbage
4.7暴露所有容器端口
容器启动后,默认处于预定义的NAT网络中,所以外部网络的主机无法直接访问容器中网络服务
docker run -P 可以将事先容器预定义的所有端口映射宿主机的网卡的随机端口,默认从32768开始使用随机端口 时,当停止容器后再启动可能会导致端口发生变化
-P , --publish-all= true | false默认为false
#示例:
docker run -P docker.io/nginx #映射容器所有暴露端口至随机本地端口
#状态查看
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
root@ubuntu1804:~# ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.53%lo:53 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
#配置端口暴露
root@ubuntu1804:~# docker run -P nginx
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/11/04 02:43:50 [notice] 1#1: using the "epoll" event method
2021/11/04 02:43:50 [notice] 1#1: nginx/1.21.3
2021/11/04 02:43:50 [notice] 1#1: built by gcc 8.3.0 (Debian 8.3.0-6)
2021/11/04 02:43:50 [notice] 1#1: OS: Linux 4.15.0-112-generic
2021/11/04 02:43:50 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/11/04 02:43:50 [notice] 1#1: start worker processes
2021/11/04 02:43:50 [notice] 1#1: start worker process 30
2021/11/04 02:43:50 [notice] 1#1: start worker process 31
#前台启动的会话窗口无法进行其他操作,除非退出,但是退出后容器也会退出。所以重新打开一个终端
#查看宿主机上的端口信息
root@ubuntu1804:~# ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.53%lo:53 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 128 *:32773 *:*
#发现多了一个监听端口32773
#访问本地的32773端口
root@ubuntu1804:~# curl 127.0.0.1:32773
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
#这是一个nginx的默认页面
#查看端口映射关系
root@ubuntu1804:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1fd9f55e6598 nginx "/docker-entrypoint.…" 54 seconds ago Up 53 seconds 0.0.0.0:32773->80/tcp quizzical_chaum
root@ubuntu1804:~# docker port 1fd
80/tcp -> 0.0.0.0:32773
#查看iptables规则
root@ubuntu1804:~# iptables -vnL -t nat
Chain PREROUTING (policy ACCEPT 2 packets, 281 bytes)
pkts bytes target prot opt in out source destination
4 1484 DOCKER all -- * * 0.0.0.0/0 0.0.0.0/0 ADDRTYPE match dst-type LOCAL
Chain INPUT (policy ACCEPT 2 packets, 281 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 7 packets, 490 bytes)
pkts bytes target prot opt in out source destination
0 0 DOCKER all -- * * 0.0.0.0/0 !127.0.0.0/8 ADDRTYPE match dst-type LOCAL
Chain POSTROUTING (policy ACCEPT 7 packets, 490 bytes)
pkts bytes target prot opt in out source destination
0 0 MASQUERADE all -- * !docker0 172.17.0.0/16 0.0.0.0/0
0 0 MASQUERADE tcp -- * * 172.17.0.2 172.17.0.2 tcp dpt:80
Chain DOCKER (2 references)
pkts bytes target prot opt in out source destination
0 0 RETURN all -- docker0 * 0.0.0.0/0 0.0.0.0/0
0 0 DNAT tcp -- !docker0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:32773 to:172.17.0.2:80
#在链docker中自动生成了一条dnat条目tcp dpt:32773 to:172.17.0.2:80
#远程主机访问容器中的nginx服务
[root@localhost ~]#curl 10.0.0.110:32773
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
#可以进行访问
#回到之前的会话窗口,同时按两个键 ctrl+c 退出容器
2021/11/04 02:54:44 [notice] 31#31: exiting
2021/11/04 02:54:44 [notice] 30#30: exiting
2021/11/04 02:54:44 [notice] 30#30: exit
2021/11/04 02:54:44 [notice] 31#31: exit
2021/11/04 02:54:44 [notice] 1#1: signal 17 (SIGCHLD) received from 30
2021/11/04 02:54:44 [notice] 1#1: worker process 30 exited with code 0
2021/11/04 02:54:44 [notice] 1#1: worker process 31 exited with code 0
2021/11/04 02:54:44 [notice] 1#1: exit
root@ubuntu1804:~#
#再次查看iptabls表
root@ubuntu1804:~# iptables -vnL -t nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
5 1544 DOCKER all -- * * 0.0.0.0/0 0.0.0.0/0 ADDRTYPE match dst-type LOCAL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 2 packets, 152 bytes)
pkts bytes target prot opt in out source destination
0 0 DOCKER all -- * * 0.0.0.0/0 !127.0.0.0/8 ADDRTYPE match dst-type LOCAL
Chain POSTROUTING (policy ACCEPT 2 packets, 152 bytes)
pkts bytes target prot opt in out source destination
0 0 MASQUERADE all -- * !docker0 172.17.0.0/16 0.0.0.0/0
Chain DOCKER (2 references)
pkts bytes target prot opt in out source destination
0 0 RETURN all -- docker0 * 0.0.0.0/0 0.0.0.0/0
#之前生成的dnat条目消失了
#再次访问nginx服务
[root@localhost ~]#curl 10.0.0.110:32773
curl: (7) Failed to connect to 10.0.0.110 port 32773: Connection refused
#无法正常访问了
#默认情况下同一宿主机的多个容器是可以相互访问的,因为都是同网段。如果不希望这些容器可以互相访问可以使用iptables进行阻止
[root@ubuntu1804 ~]#iptables -I DOCKER -s 10.0.0.8 -d 172.17.0.2 -p tcp --dport 80 -j REJECT
4.8指定端口映射
docker run -p 可以将容器的预定义的指定端口映射到宿主机的相应端口
注意: 多个容器映射到宿主机的端口不能冲突,但容器内使用的端口可以相同
方式1: 容器80端口映射宿主机本地随机端口
docker run -p 80 --name nginx-test-port1 nginx
方式2: 容器80端口映射到宿主机本地端口81
docker run -p 81:80 --name nginx-test-port2 nginx
方式3: 宿主机本地IP:宿主机本地端口:容器端口
docker run -p 10.0.0.100:82:80 --name nginx-test-port3 docker.io/nginx
方式4: 宿主机本地IP:宿主机本地随机端口:容器端口,默认从32768开始
docker run -p 10.0.0.100::80 --name nginx-test-port4 docker.io/nginx
方式5: 宿主机本机ip:宿主机本地端口:容器端口/协议,默认为tcp协议
docker run -p 10.0.0.100:83:80/udp --name nginx-test-port5 docker.io/nginx
方式6: 一次性映射多个端口+协议
docker run -p 8080:80/tcp -p 8443:443/tcp -p 53:53/udp --name nginx-test-port6 nginx
注意:
docker run -P 暴露所有容器端口 宿主机需要知道容器中哪些端口被暴露出来,如果容器中没有说明哪些端口暴露那么-P选项没用用
docker run -p 指定端口进行映射 宿主机无需知道容器中哪些端口被暴露出来,因为都是自己手动指定的
4.9查看容器的日志
docker logs 可以查看容器中运行的进程在控制台输出的日志信息
格式
docker logs [OPTIONS] CONTAINER
选项:
--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)
root@ubuntu1804:~# docker run alpine /bin/sh -c 'i=1;while true;do echo hello$i;let i++;sleep 2;done'
hello1
hello2
hello3
hello4
hello5
hello6
hello7
hello8
hello9
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d55b52c46b06 alpine "/bin/sh -c 'i=1;whi…" 42 seconds ago Up 41 seconds affectionate_roentgen
root@ubuntu1804:~# docker logs d55b52c46b06
hello1
hello2
hello3
hello4
hello5
hello6
hello7
hello8
hello9
root@ubuntu1804:~# docker logs --tail 5 d55b52c46b06
hello5
hello6
hello7
hello8
hello9
#查看一次
root@ubuntu1804:~# docker run -d --name nginx-test -p 80:80 nginx
8e569d2a4c6efcd98471252968454927892f05458f49121084d4ec3e04296d73
root@ubuntu1804:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8e569d2a4c6e nginx "/docker-entrypoint.…" 6 seconds ago Up 5 seconds 0.0.0.0:80->80/tcp nginx-test
root@ubuntu1804:~# docker logs nginx-test
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/11/04 08:27:55 [notice] 1#1: using the "epoll" event method
2021/11/04 08:27:55 [notice] 1#1: nginx/1.21.3
2021/11/04 08:27:55 [notice] 1#1: built by gcc 8.3.0 (Debian 8.3.0-6)
2021/11/04 08:27:55 [notice] 1#1: OS: Linux 4.15.0-112-generic
2021/11/04 08:27:55 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/11/04 08:27:55 [notice] 1#1: start worker processes
2021/11/04 08:27:55 [notice] 1#1: start worker process 31
2021/11/04 08:27:55 [notice] 1#1: start worker process 32
#持续查看
root@ubuntu1804:~# docker logs -f nginx-test
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/11/04 08:27:55 [notice] 1#1: using the "epoll" event method
2021/11/04 08:27:55 [notice] 1#1: nginx/1.21.3
2021/11/04 08:27:55 [notice] 1#1: built by gcc 8.3.0 (Debian 8.3.0-6)
2021/11/04 08:27:55 [notice] 1#1: OS: Linux 4.15.0-112-generic
2021/11/04 08:27:55 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/11/04 08:27:55 [notice] 1#1: start worker processes
2021/11/04 08:27:55 [notice] 1#1: start worker process 31
2021/11/04 08:27:55 [notice] 1#1: start worker process 32
10.0.0.11 - - [04/Nov/2021:08:28:59 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.61.1" "-"
#进行访问
[root@localhost ~]#curl 10.0.0.110:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
4.10传递运行命令
容器需要有一个前台运行的进程才能保持容器的运行,通过传递运行参数是一种方式,另外也可以在构建镜像的时候指定容器启动时运行的前台命令
容器里的PID为1的守护进程的实现方式
- 服务类: 如: Nginx,Tomcat,Apache ,但服务不能停
- 命令类: 如: tail -f /etc/hosts ,主要用于测试环境,注意: 不要tail -f <服务访问日志> 会产生不必要的磁盘IO
[root@ubuntu1804 ~]#docker run -d alpine
6ec8989f572a41d2d0c7d2cb12ac31de14de38af0a01af405f81dbfcf534b716
[root@ubuntu1804 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6ec8989f572a alpine "/bin/sh" 3 seconds ago Exited (0) 2 seconds ago gallant_albattani
[root@ubuntu1804 ~]#docker run -d alpine tail -f /etc/hosts
2bc9fa486769a2335f7e9aa67c7d3e7f091ba9b76d38dff868b8fd648251b576
[root@ubuntu1804 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2bc9fa486769 alpine "tail -f /etc/hosts" 3 seconds ago Up 2 seconds stupefied_keldysh
6ec8989f572a alpine "/bin/sh" 23 seconds ago Exited (0) 22 seconds ago gallant_albattani
[root@ubuntu1804 ~]#docker exec -it 2bc9fa486769 sh
/ # ps aux
PID USER TIME COMMAND
1 root 0:00 tail -f /etc/hosts
11 root 0:00 sh
17 root 0:00 ps aux
/ # exit
[root@ubuntu1804 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1e30dfc283da alpine "tail -f /etc/hosts" About a minute ago Up About a minute kind_mcclintock
4.11 容器内部的hosts文件
容器会自动将容器的ID加入自已的/etc/hosts文件中,并解析成容器的IP
[root@ubuntu1804 ~]#docker run -it centos /bin/bash
[root@598262a87c46 /]# cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2 598262a87c46 #默认会将实例的ID 添加到自己的hosts文件
[root@598262a87c46 /]# hostname
598262a87c46
[root@598262a87c46 /]# ping 598262a87c46
PING 598262a87c46 (172.17.0.2) 56(84) bytes of data.
64 bytes from 598262a87c46 (172.17.0.2): icmp_seq=1 ttl=64 time=0.118 ms
64 bytes from 598262a87c46 (172.17.0.2): icmp_seq=2 ttl=64 time=0.085 ms
^C
--- 598262a87c46 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 3ms
rtt min/avg/max/mdev = 0.085/0.101/0.118/0.019 ms
#在另一个会话执行
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
598262a87c46 centos "/bin/bash" 14 seconds ago Up 12 seconds optimistic_wiles
#修改容器的host文件
[root@ubuntu1804 ~]#docker run -it --rm --add-host www.haha.com:6.6.6.6 --add-host www.lala.org:8.8.8.8 busybox
/ # cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
6.6.6.6 www.haha.com
8.8.8.8 www.lala.org
172.17.0.2 449bf0468efd
4.12 指定容器DNS
容器的dns服务器,默认采用宿主机的dns 地址,可以用下面方式指定其它的DNS地址
- 将dns地址配置在宿主机
- 在容器启动时加选项 –dns=x.x.x.x
- 在/etc/docker/daemon.json 文件中指定
#容器的DNS默认从宿主机的DNS获取
[root@ubuntu1804 ~]#systemd-resolve --status|grep -A1 -i "DNS Servers"
DNS Servers: 180.76.76.76
223.6.6.6
[root@ubuntu1804 ~]#docker run -it --rm centos bash
[root@1364f98c4227 /]# cat /etc/resolv.conf
nameserver 180.76.76.76
nameserver 223.6.6.6
[root@1364f98c4227 /]# exit
exit
#指定dns地址
[root@ubuntu1804 ~]#docker run -it --rm --dns 1.1.1.1 --dns 8.8.8.8 centos bash
[root@ef9cacc74b58 /]# cat /etc/resolv.conf
nameserver 1.1.1.1
nameserver 8.8.8.8
[root@ef9cacc74b58 /]# exit
exit
#指定domain名
[root@ubuntu1804 ~]#docker run -it --rm --dns 1.1.1.1 --dns 8.8.8.8 --dns-search a.com --dns-search b.com busybox
/ # cat /etc/resolv.conf
search a.com b.com
nameserver 1.1.1.1
nameserver 8.8.8.8
/ #
#配置文件指定DNS和domain名
[root@ubuntu1804 ~]#vim /etc/docker/daemon.json
[root@ubuntu1804 ~]#cat /etc/docker/daemon.json
{
"storage-driver": "overlay2",
"registry-mirrors": ["https://si7y70hh.mirror.aliyuncs.com"],
"dns" : [ "114.114.114.114", "119.29.29.29"],
"dns-search": [ "haha.com", "lala.org"]
}
[root@ubuntu1804 ~]#systemctl restart docker
[root@ubuntu1804 ~]#docker run -it --rm centos bash
[root@7a2d8fac6f6b /]# cat /etc/resolv.conf
search haha.com lala.org
nameserver 114.114.114.114
nameserver 119.29.29.29
[root@7a2d8fac6f6b /]# exit
exit
#用--dns指定优先级更高
[root@ubuntu1804 ~]#docker run -it --rm --dns 8.8.8.8 --dns 8.8.4.4 centos bash
[root@80ffe3547b87 /]# cat /etc/resolv.conf
search haha.com lala.org
nameserver 8.8.8.8
nameserver 8.8.4.4
[root@80ffe3547b87 /]# exit
exit
4.13 容器内和宿主机之间复制文件
格式
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
Options:
-a, --archive Archive mode (copy all uid/gid information)
-L, --follow-link Always follow symbol link in SRC_PATH
[root@ubuntu1804 ~]#docker run -itd centos
1311fe67e6708dac71c01f7d1752a6dcb5e85c2f1fa4ac2efcef9edfe4fb6bb5
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1311fe67e670 centos "/bin/bash" 2 seconds ago Up 2 seconds elegant_khorana
#将容器内文件复制到宿主机
[root@ubuntu1804 ~]#docker cp -a 1311:/etc/centos-release .
[root@ubuntu1804 ~]#cat centos-release
CentOS Linux release 8.1.1911 (Core)
#将宿主机文件复制到容器内
[root@ubuntu1804 ~]#docker cp /etc/issue 1311:/root/
[root@ubuntu1804 ~]#docker exec 1311 cat /root/issue
Ubuntu 18.04.1 LTS \n \l
4.14 使用 systemd 控制容器运行
[root@ubuntu1804 ~]#cat /lib/systemd/system/hello.service
[Unit]
Description=Hello World
After=docker.service
Requires=docker.service
[Service]
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker kill busybox-hello
ExecStartPre=-/usr/bin/docker rm busybox-hello
ExecStartPre=/usr/bin/docker pull busybox
ExecStart=/usr/bin/docker run --name busybox-hello busybox /bin/sh -c "while true; do echo Hello World; sleep 1; done"
ExecStop=/usr/bin/docker kill busybox-hello
[Install]
WantedBy=multi-user.target
[root@ubuntu1804 ~]#systemctl daemon-reload
[root@ubuntu1804 ~]#systemctl enable --now hello.service
4.15 传递环境变量
有些容器运行时,需要传递变量,可以使用 -e <参数> 或 –env-file <参数文件> 实现
变量参考链接: https://hub.docker.com/_/mysql
#传递变量创建MySQL
#MySQL容器运行时需要指定root的口令
[root@ubuntu1804 ~]#docker run --name mysql01 mysql:5.7.32
2020-11-16 01:43:13+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.32-1debian10 started.
2020-11-16 01:43:13+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2020-11-16 01:43:13+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.32-1debian10 started.
2020-11-16 01:43:13+00:00 [ERROR] [Entrypoint]: Database is uninitialized and password option is not specified
You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD
[root@ubuntu1804 ~]#docker run --name mysql-test1 -v /data/mysql:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_DATABASE=wordpress -e MYSQL_USER=wpuser -e MYSQL_PASSWORD=123456 -d -p 3306:3306 mysql:5.7.30
[root@ubuntu1804 ~]#docker run --name mysql-test2 -v /root/mysql/:/etc/mysql/conf.d -v /data/mysql2:/var/lib/mysql --env-file=env.list -d -p 3307:3306 mysql:5.7.30
[root@ubuntu1804 ~]#cat mysql/mysql-test.cnf
[mysqld]
server-id=100
log-bin=mysql-bin
[root@ubuntu1804 ~]#cat env.list
MYSQL_ROOT_PASSWORD=123456
MYSQL_DATABASE=wordpress
MYSQL_USER=wpuser
MYSQL_PASSWORD=wppass
4.16 podman 管理容器
#安装httpd
[root@centos8 ~]#podman pull httpd
[root@centos8 ~]#podman run -d --name web -p 80:80 httpd
[root@centos8 ~]#curl 127.0.0.1
<html><body><h1>It works!</h1></body></html>
[root@centos8 ~]#podman exec -it web /bin/sh
# ls
bin build cgi-bin conf error htdocs icons include logs modules
# cd htdocs
# cat index.html
<html><body><h1>It works!</h1></body></html>
# echo welcome to test > index.html
# exit
[root@centos8 ~]#curl 127.0.0.1
welcome to test
#安装nginx
[root@centos8 ~]#podman run -dt -p 80:80 --name nginx -v /data:/data -e
NGINX_VERSION=1.16 nginx:1.16.0
[root@centos8 ~]#podman stop nginx
#将容器设为开机启动
[root@centos8 ~]#vim /lib/systemd/system/nginx_podman.service
[root@centos8 ~]#cat /lib/systemd/system/nginx_podman.service
[Unit]
Description=Podman Nginx Service
After=network.target
After=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/podman start -a nginx # -a, --attach Attach container's
STDOUT and STDERR
ExecStop=/usr/bin/podman stop -t 10 nginx
Restart=always
[Install]
WantedBy=multi-user.target
[root@centos8 ~]#systemctl daemon-reload
[root@centos8 ~]#systemctl enable --now nginx_podman.service
[root@centos8 ~]#curl 127.0.0.1
#podman 查看日志7
[root@centos8 ~]#podman logs nginx
10.0.0.8 - - [24/Feb/2020:14:19:45 +0000] "GET / HTTP/1.1" 200 612 "-"
"curl/7.61.1" "-"
10.0.0.1 - - [24/Feb/2020:14:25:54 +0000] "GET / HTTP/1.1" 200 612 "-"
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/79.0.3945.117 Safari/537.36" "-"
[root@centos8 ~]#podman port nginx
80/tcp -> 0.0.0.0:80
[root@centos8 ~]#ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@centos8 ~]#systemctl stop nginx_podman.service
[root@centos8 ~]#ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
#查看进程信息
[root@centos8 ~]#systemctl start nginx_podman.service
[root@centos8 ~]#pstree -p
systemd(1)─┬─NetworkManager(664)─┬─{NetworkManager}(698)
│ └─{NetworkManager}(699)
├─VGAuthService(659)
├─agetty(766)
├─atd(763)
├─auditd(626)───{auditd}(627)
├─automount(789)─┬─{automount}(796)
│ ├─{automount}(797)
│ ├─{automount}(805)
│ └─{automount}(822)
├─conmon(2378)─┬─nginx(2388)───nginx(2401)
│ └─{conmon}(2380)
├─crond(762)
├─dbus-daemon(661)
├─podman(2308)─┬─{podman}(2309)
│ ├─{podman}(2310)
│ ├─{podman}(2311)
│ ├─{podman}(2312)
│ ├─{podman}(2313)
│ ├─{podman}(2316)
│ ├─{podman}(2321)
│ ├─{podman}(2326)
│ └─{podman}(2399)
├─polkitd(668)─┬─{polkitd}(697)
│ ├─{polkitd}(700)
│ ├─{polkitd}(703)
│ ├─{polkitd}(704)
│ └─{polkitd}(754)
├─rngd(667)───{rngd}(677)
├─rsyslogd(788)─┬─{rsyslogd}(795)
│ └─{rsyslogd}(798)
├─sshd(711)─┬─sshd(1361)───sshd(1375)───bash(1377)
│ └─sshd(1362)───sshd(1376)───bash(1380)───pstree(2504)
├─sssd(658)─┬─sssd_be(730)
│ └─sssd_nss(758)
├─systemd(1366)───(sd-pam)(1369)
├─systemd-journal(553)
├─systemd-logind(760)
├─systemd-udevd(586)
├─tuned(702)─┬─{tuned}(1073)
│ ├─{tuned}(1076)
│ └─{tuned}(1088)
└─vmtoolsd(660)
#nginx进程杀死后还会自动启动
[root@centos8 ~]#kill 2388
[root@centos8 ~]#ps aux|grep nginx
root 2939 1.1 8.4 908244 69240 ? Ssl 22:45 0:00
/usr/bin/podman start -a nginx
root 3009 0.0 0.3 142832 2652 ? Ssl 22:45 0:00
/usr/libexec/podman/conmon -s -c
9198c59a8a3db50801c52ceaa39521b4381ac46ab7c16907130244d2a328e823 -u
9198c59a8a3db50801c52ceaa39521b4381ac46ab7c16907130244d2a328e823 -n nginx -r
/usr/bin/runc -b /var/lib/containers/storage/overlay-
containers/9198c59a8a3db50801c52ceaa39521b4381ac46ab7c16907130244d2a328e823/user
data -p /var/run/containers/storage/overlay-
containers/9198c59a8a3db50801c52ceaa39521b4381ac46ab7c16907130244d2a328e823/user
data/pidfile --exit-dir /var/run/libpod/exits --exit-command /usr/bin/podman --
exit-command-arg --root --exit-command-arg /var/lib/containers/storage --exit-
command-arg --runroot --exit-command-arg /var/run/containers/storage --exit-
command-arg --log-level --exit-command-arg error --exit-command-arg --cgroup-
manager --exit-command-arg systemd --exit-command-arg --tmpdir --exit-command-
arg /var/run/libpod --exit-command-arg --runtime --exit-command-arg runc --exit-
command-arg --storage-driver --exit-command-arg overlay --exit-command-arg --
events-backend --exit-command-arg journald --exit-command-arg container --exit-
command-arg cleanup --exit-command-arg
9198c59a8a3db50801c52ceaa39521b4381ac46ab7c16907130244d2a328e823 --socket-dir-
path /var/run/libpod/socket -t -l k8s-file:/var/lib/containers/storage/overlay-
containers/9198c59a8a3db50801c52ceaa39521b4381ac46ab7c16907130244d2a328e823/user
data/ctr.log --log-level error
root 3019 2.5 0.6 32656 5364 pts/0 Ss+ 22:45 0:00 nginx: master
process nginx -g daemon off;
101 3031 0.0 0.3 33144 2636 pts/0 S+ 22:45 0:00 nginx: worker
process
root 3034 0.0 0.1 12108 1072 pts/1 S+ 22:45 0:00 grep --
color=auto nginx
[root@centos8 ~]#podman top nginx
USER PID PPID %CPU ELAPSED TTY TIME COMMAND
root 1 0 0.000 4m38.979412738s pts/0 0s nginx: master
process nginx -g daemon off;
nginx 6 1 0.000 4m37.979473913s pts/0 0s nginx: worker
process
[root@centos8 ~]#podman stats nginx
ID NAME CPU % MEM USAGE / LIMIT MEM % NET IO BLOCK
IO PIDS
9198c59a8a3d nginx -- 2.474MB / 835.8MB 0.30% 2.25kB / 1.742kB --
/ -- 2
**5、★★Docker 镜像制作和管理★★ **
5.1Docker 镜像说明
5.1.1Docker 镜像中有没有内核
从镜像大小上面来说,一个比较小的镜像只有1MB多点或几MB,而内核文件需要几十MB, 因此镜像里面是没有内核的,镜像在被启动为容器后将直接使用宿主机的内核,而镜像本身则只提供相应的rootfs,即系统正常运行所必须的用户空间的文件系统,比如: /dev/,/proc,/bin,/etc等目录,容器当中/boot目录是空的,而/boot当中保存的就是与内核相关的文件和目录。
5.1.2为什么没有内核
由于容器启动和运行过程中是直接使用了宿主机的内核,不会直接调用物理硬件,所以也不会涉及到硬件驱动,因此也无需容器内拥有自已的内核和驱动。而如果使用虚拟机技术,对应每个虚拟机都有自已独立的内核
5.1.3 容器中的程序后台运行会导致此容器启动后立即退出
Docker容器如果希望启动后能持续运行,就必须有一个能前台持续运行的进程,如果在容器中启动传统的服务,如:httpd,php-fpm等均为后台进程模式运行,就导致 docker 在前台没有运行的应用,这样的容器启动后会立即退出。所以一般会将服务程序以前台方式运行,对于有一些可能不知道怎么实现前台运行的程序,只需要在你启动的该程序之后添加类似于 tail ,top 这种可以前台运行的程序即可. 比较常用的
方法,如 tail -f /etc/hosts 。
5.1.4 docker 镜像生命周期
5.1.5 制作镜像方式
Docker 镜像制作类似于虚拟机的镜像(模版)制作,即按照公司的实际业务需求将需要安装的软件、相关配置等基础环境配置完成,然后将其做成镜像,最后再批量从镜像批量生成容器实例,这样可以极大的简化相同环境的部署工作.
Docker的镜像制作分为手动制作(基于容器)和自动制作(基于DockerFile),企业通常都是基于Dockerfile制作镜像
docker commit #通过修改现有容器,将之手动构建为镜像
docker build #通过Dockerfile文件,批量构建为镜像
5.2 将现有容器通过 docker commit 手动构建镜像(可复用性较低,所以生产中较少使用了解即可)
5.2.1 基于容器手动制作镜像步骤
docker commit 格式
docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
#选项
-a, --author string Author (e.g., "John Hannibal Smith <hannibal@a-team.com>") #提交的镜像作者
-c, --change list Apply Dockerfile instruction to the created image #使用Dockerfile指令来创建镜像
-m, --message string Commit message #提交时的说明文字
-p, --pause Pause container during commit (default true) #在commit时,将容器暂停
#说明:
制作镜像和CONTAINER状态无关,停止状态也可以制作镜像
如果没有指定[REPOSITORY[:TAG]],REPOSITORY和TAG都为<none>
提交的时候标记TAG号: 生产当中常用,后期可以根据TAG标记创建不同版本的镜像以及创建不同版本的容器
基于容器手动制作镜像步骤具体如下:
- 下载一个系统的官方基础镜像,如: CentOS 或 Ubuntu
- 基于基础镜像启动一个容器,并进入到容器
- 在容器里面做配置操作
- 安装基础命令
- 配置运行环境
- 安装服务和配置服务
- 放业务程序代码
- 提交为一个新镜像 docker commit
- 基于自己的的镜像创建容器并测试访问
5.2.2 实战案例: 基于 busybox 制作 httpd 镜像
root@ubuntu1804:~# docker run -it --name busy1 busybox
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
01c2cdc13739: Pull complete
Digest: sha256:15e927f78df2cc772b70713543d6b651e3cd8370abf86b2ea4644a9fba21107f
Status: Downloaded newer image for busybox:latest
/ # ls
bin dev etc home proc root sys tmp usr var
/ # mkd
/ # mkdir /data/html -p
/ # echo httpd website in busybox > /data/html/index.html
/ # httpd --help
BusyBox v1.34.1 (2021-10-26 18:45:18 UTC) multi-call binary.
Usage: httpd [-ifv[v]] [-c CONFFILE] [-p [IP:]PORT] [-u USER[:GRP]] [-r REALM] [-h HOME]
or httpd -d/-e/-m STRING
Listen for incoming HTTP requests
-i Inetd mode
-f Don't daemonize
-v[v] Verbose
-p [IP:]PORT Bind to IP:PORT (default *:80)
-u USER[:GRP] Set uid/gid after binding to port
-r REALM Authentication Realm for Basic Authentication
-h HOME Home directory (default .)
-c FILE Configuration file (default {/etc,HOME}/httpd.conf)
-m STRING MD5 crypt STRING
-e STRING HTML encode STRING
-d STRING URL decode STRING
/ # exit
#制作镜像格式1
root@ubuntu1804:~# docker commit -a "sunx<root@sunx.com>" -c 'CMD /bin/httpd -fv -h /data/html' -c "EXPOSE 80" busy1 httpd-busybox:v1.0
sha256:6f1910713086683f51d24a9d2611063c5a7b8de4f29e6fd586fa28b9dc2982ab
#制作镜像格式2
root@ubuntu1804:~# docker commit -a "sunx<root@sunx.com>" -c 'CMD ["/bin/httpd", "-f", "-v","-h", "/data/html"]' -c "EXPOSE 80" b1 httpd-busybox:v1.0
#说明 -c中的内容用于指定在容器中前台运行的程序,以及对外暴露的端口号,如果不指定前台运行的程序那么容器一启动就会自动关闭,如果不指定对外暴露的端口号那么就无法使用-P选项进行端口映射只能使用-p选项
root@ubuntu1804:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
httpd-busybox v1.0 6f1910713086 17 seconds ago 1.24MB
busybox latest cabb9f684f8b 8 days ago 1.24MB
root@ubuntu1804:~# docker run -d -P --name httpd01 httpd-busybox:v1.0
b6efccb8a286dd1b7db4311d0d30d66a89420f53a4fbf06aa8ee22a63cfed226
root@ubuntu1804:~# docker port httpd01
80/tcp -> 0.0.0.0:32768
root@ubuntu1804:~# docker inspect -f "{{.NetworkSettings.Networks.bridge.IPAddress}}" httpd01
172.17.0.2
#对应格式1
root@ubuntu1804:~# docker inspect -f "{{.Config.Cmd}}" httpd01
[/bin/sh -c /bin/httpd -fv -h /data/html]
#对应格式2
root@ubuntu1804:~# docker inspect -f "{{.Config.Cmd}}" httpd01
[/bin/httpd -f -h /data/html
root@ubuntu1804:~# docker exec -it httpd01 sh
/ # pstree -p
httpd(1)
/ # ps aux
PID USER TIME COMMAND
1 root 0:00 /bin/httpd -fv -h /data/html
6 root 0:00 sh
12 root 0:00 ps aux
/ # exit
root@ubuntu1804:~# curl 172.17.0.2
httpd website in busybox
[root@Centos7 ~]# curl 10.0.0.110:32768
httpd website in busybox
5.2.3 实战案例: 基于官方镜像生成的容器制作 tomcat 镜像
5.2.3.1 下载官方的tomcat镜像并运行
root@ubuntu1804:~# docker run -d -p 8080:8080 tomcat
Unable to find image 'tomcat:latest' locally
latest: Pulling from library/tomcat
bb7d5a84853b: Pull complete
f02b617c6a8c: Pull complete
d32e17419b7e: Pull complete
c9d2d81226a4: Pull complete
fab4960f9cd2: Pull complete
da1c1e7baf6d: Pull complete
1d2ade66c57e: Pull complete
ea2ad3f7cb7c: Pull complete
d75cb8d0a5ae: Pull complete
76c37a4fffe6: Pull complete
Digest: sha256:509cf786b26a8bd43e58a90beba60bdfd6927d2ce9c7902cfa675d3ea9f4c631
Status: Downloaded newer image for tomcat:latest
17174df5ecac7e70bcb657bafe193d0559448c13d4087efe91767177dbe6725b
root@ubuntu1804:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
17174df5ecac tomcat "catalina.sh run" 50 seconds ago Up 48 seconds 0.0.0.0:8080->8080/tcp awesome_wiles
root@ubuntu1804:~# curl -I 127.0.0.1:8080
HTTP/1.1 404
Content-Type: text/html;charset=utf-8
Content-Language: en
Transfer-Encoding: chunked
Date: Fri, 05 Nov 2021 00:34:15 GMT
5.2.3.2 修改容器
root@ubuntu1804:~# docker exec -it 17174df5ecac bash
root@17174df5ecac:/usr/local/tomcat# ls
BUILDING.txt NOTICE RUNNING.txt lib temp work
CONTRIBUTING.md README.md bin logs webapps
LICENSE RELEASE-NOTES conf native-jni-lib webapps.dist
root@17174df5ecac:/usr/local/tomcat# ls webapps
root@17174df5ecac:/usr/local/tomcat# ls webapps.dist/
ROOT docs examples host-manager manager
root@17174df5ecac:/usr/local/tomcat# cp -a webapps.dist/* webapps/
root@17174df5ecac:/usr/local/tomcat# ls webapps/
ROOT docs examples host-manager manager
root@17174df5ecac:/usr/local/tomcat# exit
exit
root@ubuntu1804:~# curl -I 127.0.0.1:8080
HTTP/1.1 200
Content-Type: text/html;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 05 Nov 2021 00:37:19 GMT
5.2.3.3 提交新镜像
root@ubuntu1804:~# docker commit -m"add webapps app" -a "sunx" 17174df5ecac tomcat:6.6.6-v1
sha256:764b532364404f2e0c9500c207138d4e2c409219081f35a0e659e6f732254674
root@ubuntu1804:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat 6.6.6-v1 764b53236440 5 seconds ago 684MB
tomcat latest b0e0b0a92cf9 2 weeks ago 680MB
root@ubuntu1804:~# docker history tomcat:6.6.6-v1
IMAGE CREATED CREATED BY SIZE COMMENT
764b53236440 21 seconds ago catalina.sh run 4.42MB add webapps app
b0e0b0a92cf9 2 weeks ago /bin/sh -c #(nop) CMD ["catalina.sh" "run"] 0B
<missing> 2 weeks ago /bin/sh -c #(nop) EXPOSE 8080 0B
<missing> 2 weeks ago /bin/sh -c set -eux; nativeLines="$(catalin… 0B
<missing> 2 weeks ago /bin/sh -c set -eux; savedAptMark="$(apt-m… 20.1MB
<missing> 2 weeks ago /bin/sh -c #(nop) ENV TOMCAT_SHA512=e084fc0… 0B
<missing> 2 weeks ago /bin/sh -c #(nop) ENV TOMCAT_VERSION=10.0.12 0B
<missing> 2 weeks ago /bin/sh -c #(nop) ENV TOMCAT_MAJOR=10 0B
<missing> 2 weeks ago /bin/sh -c #(nop) ENV GPG_KEYS=A9C5DF4D22E9… 0B
<missing> 2 weeks ago /bin/sh -c #(nop) ENV LD_LIBRARY_PATH=/usr/… 0B
<missing> 2 weeks ago /bin/sh -c #(nop) ENV TOMCAT_NATIVE_LIBDIR=… 0B
<missing> 2 weeks ago /bin/sh -c #(nop) WORKDIR /usr/local/tomcat 0B
<missing> 2 weeks ago /bin/sh -c mkdir -p "$CATALINA_HOME" 0B
<missing> 2 weeks ago /bin/sh -c #(nop) ENV PATH=/usr/local/tomca… 0B
<missing> 2 weeks ago /bin/sh -c #(nop) ENV CATALINA_HOME=/usr/lo… 0B
<missing> 2 weeks ago /bin/sh -c #(nop) CMD ["jshell"] 0B
<missing> 2 weeks ago /bin/sh -c set -eux; arch="$(dpkg --print-… 343MB
<missing> 2 weeks ago /bin/sh -c #(nop) ENV JAVA_VERSION=11.0.13 0B
<missing> 3 weeks ago /bin/sh -c #(nop) ENV LANG=C.UTF-8 0B
<missing> 3 weeks ago /bin/sh -c #(nop) ENV PATH=/usr/local/openj… 0B
<missing> 3 weeks ago /bin/sh -c { echo '#/bin/sh'; echo 'echo "$J… 27B
<missing> 3 weeks ago /bin/sh -c #(nop) ENV JAVA_HOME=/usr/local/… 0B
<missing> 3 weeks ago /bin/sh -c set -eux; apt-get update; apt-g… 11.3MB
<missing> 3 weeks ago /bin/sh -c apt-get update && apt-get install… 152MB
<missing> 3 weeks ago /bin/sh -c set -ex; if ! command -v gpg > /… 18.9MB
<missing> 3 weeks ago /bin/sh -c set -eux; apt-get update; apt-g… 10.7MB
<missing> 3 weeks ago /bin/sh -c #(nop) CMD ["bash"] 0B
<missing> 3 weeks ago /bin/sh -c #(nop) ADD file:aea313ae50ce6474a… 124MB
root@ubuntu1804:~# docker inspect tomcat:6.6.6-v1 | tail -n15
"sha256:ba6e5ff31f235bbfd34aae202da4e6d4dc759f266f284d79018cae755f36f9e3",
"sha256:36e0782f115904773d06f7d03af94a1ec9ca9ad42736ec55baae8823c457ba69",
"sha256:62a5b8741e8334844625c513016da47cf2b61afb1145f6317edacb4c13ab010e",
"sha256:78700b6b35d0ab6e70befff1d26c5350222a8fea49cc874916bce950eeae35a1",
"sha256:cb80689c9aefc3f455b35b0110fa04a7c13e21a25f342ee2bb27c28f618a0eb5",
"sha256:5122793ce9cb2007fe52ae7bb8ff25001e7c29c04d081a0a4bb1986d1b06a4cb",
"sha256:450346f29d28210054da70889add4cf59f9c9f3964a94cfa213f905620ade8e2",
"sha256:9f618e520727812dbb32cfe6c93c30aa9a66821d29824c6ac55692724b0cf628"
]
},
"Metadata": {
"LastTagTime": "2021-11-05T08:39:55.05052478+08:00"
}
}
]
5.2.3.4 利用新镜像启动容器
#删除当前的容器
root@ubuntu1804:~# docker rm -f 17174df5ecac
17174df5ecac
root@ubuntu1804:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
root@ubuntu1804:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
#运行新镜像启动容器
root@ubuntu1804:~# docker run -d -p 8080:8080 --name tomsun tomcat:6.6.6-v1
255e29e266bed9bb8595151258e2d55a5438dcb05bd090b1d1abed299d8d04ac
root@ubuntu1804:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
255e29e266be tomcat:6.6.6-v1 "catalina.sh run" 3 seconds ago Up 3 seconds 0.0.0.0:8080->8080/tcp tomsun
5.2.3.5 测试新镜像启动的容器
浏览器访问 http://10.0.0.110:8080/ 可以看到下面显示
5.2.4 实战案例: 基于Ubuntu的基础镜像利用 apt 安装手动制作nginx 的镜像
5.2.4.1 启动Ubuntu基础镜像并实现相关的配置
[root@ubuntu1804 ~]#docker run -it -p 80 --name nginx_ubuntu ubuntu bash
root@705148273eac:/# cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal
root@705148273eac:/# ll /etc/apt/sources.list
-rw-r--r-- 1 root root 2743 Jul 3 02:00 /etc/apt/sources.list
root@705148273eac:/# cat > /etc/apt/sources.list
deb http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse
^C
root@705148273eac:/# apt update
Get:1 http://mirrors.aliyun.com/ubuntu focal InRelease [265 kB]
Get:2 http://mirrors.aliyun.com/ubuntu focal-security InRelease [107 kB]
Get:3 http://mirrors.aliyun.com/ubuntu focal-updates InRelease [111 kB]
Get:4 http://mirrors.aliyun.com/ubuntu focal-proposed InRelease [265 kB]
Get:5 http://mirrors.aliyun.com/ubuntu focal-backports InRelease [98.3 kB]
Get:6 http://mirrors.aliyun.com/ubuntu focal/restricted Sources [7198 B]
Get:7 http://mirrors.aliyun.com/ubuntu focal/multiverse Sources [208 kB]
......
Fetched 28.7 MB in 6s (4651 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
8 packages can be upgraded. Run 'apt list --upgradable' to see them.
root@705148273eac:/# apt -y install nginx
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
........
Configuring tzdata
------------------
Please select the geographic area in which you live. Subsequent configuration questions will narrow this down
by presenting a list of cities, representing the time zones in which they are located.
1. Africa 3. Antarctica 5. Arctic 7. Atlantic 9. Indian 11. SystemV
13. Etc
2. America 4. Australia 6. Asia 8. Europe 10. Pacific 12. US
Geographic area: 6
Please select the city or region corresponding to your time zone.
1. Aden 16. Brunei 31. Hong_Kong 46. Kuala_Lumpur 61. Pyongyang
76. Tehran
2. Almaty 17. Chita 32. Hovd 47. Kuching 62. Qatar
77. Tel_Aviv
3. Amman 18. Choibalsan 33. Irkutsk 48. Kuwait 63. Qostanay
78. Thimphu
4. Anadyr 19. Chongqing 34. Istanbul 49. Macau 64. Qyzylorda
79. Tokyo
5. Aqtau 20. Colombo 35. Jakarta 50. Magadan 65. Rangoon
80. Tomsk
6. Aqtobe 21. Damascus 36. Jayapura 51. Makassar 66. Riyadh
81. Ujung_Pandang
7. Ashgabat 22. Dhaka 37. Jerusalem 52. Manila 67. Sakhalin
82. Ulaanbaatar
8. Atyrau 23. Dili 38. Kabul 53. Muscat 68. Samarkand
83. Urumqi
9. Baghdad 24. Dubai 39. Kamchatka 54. Nicosia 69. Seoul
84. Ust-Nera
10. Bahrain 25. Dushanbe 40. Karachi 55. Novokuznetsk 70. Shanghai
85. Vientiane
11. Baku 26. Famagusta 41. Kashgar 56. Novosibirsk 71. Singapore
86. Vladivostok
12. Bangkok 27. Gaza 42. Kathmandu 57. Omsk 72.
Srednekolymsk 87. Yakutsk
13. Barnaul 28. Harbin 43. Khandyga 58. Oral 73. Taipei
88. Yangon
14. Beirut 29. Hebron 44. Kolkata 59. Phnom_Penh 74. Tashkent
89. Yekaterinburg
15. Bishkek 30. Ho_Chi_Minh 45. Krasnoyarsk 60. Pontianak 75. Tbilisi
90. Yerevan
Time zone: 70 #配置时区
......
Setting up nginx-core (1.18.0-0ubuntu1) ...
invoke-rc.d: could not determine current runlevel
invoke-rc.d: policy-rc.d denied execution of start.
Setting up nginx (1.18.0-0ubuntu1) ...
Processing triggers for libc-bin (2.31-0ubuntu9) ...
root@705148273eac:/# nginx -v
nginx version: nginx/1.18.0 (Ubuntu)
root@705148273eac:~# grep include /etc/nginx/nginx.conf
include /etc/nginx/modules-enabled/*.conf;
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
root@705148273eac:~# grep root /etc/nginx/sites-enabled/default
root /var/www/html;
# deny access to .htaccess files, if Apache's document root
# root /var/www/example.com;
root@705148273eac:/# echo Nginx Website in Docker > /var/www/html/index.html
root@705148273eac:/# exit
exit
5.2.4.2 提交为镜像
[root@ubuntu1804 ~]#docker commit -a 'wangxiaochun' -m 'nginx-ubuntu:20.04' nginx_ubuntu nginx_ubuntu20.04:v1.18.0
sha256:2c789ec21d2545c9bfc4af6d4380878153d52fcc03890aac755d09112631742a
[root@ubuntu1804 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx_ubuntu20.04 v1.18.0 2c789ec21d25 22 seconds ago 179MB
5.2.4.3 从制作的新镜像启动容器并测试访问
[root@ubuntu1804 ~]#docker run -d -p 80 --name nginx-web
nginx_ubuntu20.04:v1.18.0 nginx -g 'daemon off;'
b0c8496a497ba60f7b5bc430b075b00d40c7ace24068e71decac625e84df40de
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b0c8496a497b nginx_ubuntu20.04:v1.18.0 "nginx -g 'daemon of…" 7seconds ago Up 5 seconds 0.0.0.0:32771->80/tcp nginx-web
[root@ubuntu1804 ~]#docker port nginx-web
80/tcp -> 0.0.0.0:32771
[root@ubuntu1804 ~]#curl http://127.0.0.1:32771
Nginx Website in Docker
5.2.5 实战案例: 基于CentOS的基础镜像利用 yum 安装手动制作nginx 的镜像
5.2.5.1下载基础镜像并初始化系统
基于某个基础镜像之上重新制作,因此需要先有一个基础镜像,本次使用官方提供的centos镜像为基础
[root@ubuntu1804 ~]#docker pull centos
[root@ubuntu1804 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos centos 08d05d1d5859 2 months ago 204MB
[root@ubuntu1804 ~]#docker run -it centos bash
#修改时区
[root@9caa8742e6ce /]#rm -f /etc/localtime
[root@9caa8742e6ce /]#ln -s ../usr/share/zoneinfo/Asia/Shanghai /etc/localtime
[root@9caa8742e6ce /]# yum -y install wget
[root@9caa8742e6ce /]# rm -rf /etc/yum.repos.d/*
#更改yum 源
[root@9caa8742e6ce /]# wget -P /etc/yum.repos.d/
http://mirrors.aliyun.com/repo/Centos-7.repo
[root@9caa8742e6ce /]# wget -P /etc/yum.repos.d/
http://mirrors.aliyun.com/repo/epel-7.repo
5.2.5.2 安装相关软件和工具
#yum安装nginx
[root@9caa8742e6ce /]# yum install nginx –y
#安装常用命令
[root@9caa8742e6ce /]# yum install -y vim curl iproute net-tools
#清理yum缓存
[root@9caa8742e6ce /]# rm -rf /var/cache/yum/*
5.2.5.3 修改服务的配置信息关闭服务后台运行
#关闭nginx后台运行
[root@9caa8742e6ce /]# vim /etc/nginx/nginx.conf
user nginx;
daemon off; #关闭后台运行
5.2.5.4 准备程序和数据
#自定义web界面
[root@9caa8742e6ce ~]# rm -f /usr/share/nginx/html/index.html
[root@9caa8742e6ce ~]# echo "Nginx Page in Docker" > /usr/share/nginx/html/index.html
5.2.5.5 提交为镜像
docker commit 命令在宿主机基于容器ID 提交为镜像
#不关闭容器的情况,将容器提交为镜像
[root@ubuntu1804 ~]#docker commit -a "root@sunx.com" -m "nginx yum v1" -c "EXPOSE 80 443" 9caa8742e6ce centos7-nginx:6.6.v1
sha256:e9d09cc585ed8ee1544b1e68de326ea6dcbe99577fc9b2edad9ab481b7a7e7ec
[root@ubuntu1804 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos7-nginx centos7-nginx:6.6.v1 e9d09cc585ed 4 seconds ago 442MB
centos centos7.7.1908 08d05d1d5859 2 months ago 204MB
5.2.5.6 从制作的镜像启动容器
[root@ubuntu1804 ~]#docker run -d -p 8080:80 --name ng1
centos7-nginx:6.6.v1 /usr/sbin/nginx
c60f8373a14210bb3aa06ce03c2258a4b912033b0650ef690f9245fc3afc5bf1
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c60f8373a142 centos7-nginx:6.6.v1 "/usr/sbin/nginx" 6 seconds ago Up 5 seconds 443/tcp, 0.0.0.0:8080->80/tcp ng1
9caa8742e6ce centos:centos7.7.1908 "bash" 35 minutes ago Up 35 minutes thirsty_hypatia
5.2.5.7 访问测试镜像
[root@ubuntu1804 ~]#curl 127.0.0.1:8080
Nginx Page in Docker
[root@ubuntu1804 ~]#
5.2.6 实战案例: 基于CentOS 基础镜像手动制作编译版本 nginx 镜像
在CentOS 基础镜像的容器之上手动编译安装nginx,然后再将此容器提交为镜像
5.2.6.1 下载镜像并初始化系统
[root@ubuntu1804 ~]#docker pull centos:centos7.7.1908
[root@ubuntu1804 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED
SIZE
centos centos7.7.1908 08d05d1d5859 2 months ago
204MB
[root@ubuntu1804 ~]#docker run -it centos:centos7.7.1908 /bin/bash
#生成yum源配置
[root@86a48908bb97 /]# yum -y install wget
[root@64944257fa88 /]# rm -rf /etc/yum.repos.d/*
[root@64944257fa88 /]# wget -P /etc/yum.repos.d/
http://mirrors.aliyun.com/repo/Centos-7.repo
http://mirrors.aliyun.com/repo/epel-7.repo
5.2.6.2 编译安装 nginx
[root@64944257fa88 /]# useradd -r -s /sbin/nologin nginx
#安装基础包
[root@64944257fa88 /]# yum -y install gcc gcc-c++ automake pcre pcre-devel zlib
zlib-devel openssl openssl-devel
[root@64944257fa88 /]# cd /usr/local/src
[root@64944257fa88 src]# wget http://nginx.org/download/nginx-1.16.1.tar.gz
[root@64944257fa88 src]# tar xf nginx-1.16.1.tar.gz
[root@64944257fa88 src]# cd nginx-1.16.1
[root@64944257fa88 nginx-1.16.1]# ./configure --prefix=/apps/nginx
[root@64944257fa88 nginx-1.16.1]# make && make install
[root@64944257fa88 nginx-1.16.1]# rm -rf nginx*
[root@64944257fa88 nginx-1.16.1]# rm -rf /var/cache/yum/*
5.2.6.3 关闭 nginx 后台运行
[root@64944257fa88 nginx-1.16.1]# cd /apps/nginx/
[root@64944257fa88 nginx]# ls
conf html logs sbin
[root@64944257fa88 nginx]# vi conf/nginx.conf
user nginx;
daemon off;
[root@64944257fa88 nginx]# ln -s /apps/nginx/sbin/nginx /usr/sbin/
[root@64944257fa88 nginx]# ll /usr/sbin/nginx
lrwxrwxrwx 1 root root 22 Jan 28 05:29 /usr/sbin/nginx -> /apps/nginx/sbin/nginx
5.2.6.4 准备相关数据自定义web界面
[root@64944257fa88 nginx]# echo "Nginx Test Page in Docker" > /apps/nginx/html/index.html
5.2.6.5 提交为镜像
#不要退出容器,在另一个终端窗口执行以下命令
[root@ubuntu1804 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos centos7.7.1908 08d05d1d5859 2 months ago 204MB
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
64944257fa88 centos:centos7.7.1908 "/bin/bash" 18 seconds ago Up 17 seconds stupefied_albattani
[root@ubuntu1804 ~]#docker commit -m "nginx1.6.1" 64944257fa88 -c "CMD nginx" centos7-nginx:1.6.1
sha256:d86d957bb00f35fe09ae38230e1e2d12916f4406e997146c68e34dae7526c079
[root@ubuntu1804 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos7-nginx 1.6.1 d86d957bb00f 2 minutes ago 486MB
centos centos7.7.1908 08d05d1d5859 2 months ago 204MB
5.2.6.6 从自己的镜像启动容器
[root@ubuntu1804 ~]#docker run -d -p 80:80 centos7-nginx:1.6.1 nginx
ae90b1abf374138a21f7ed104d14c88f1af23c0b2027c3fe099722fd7fbad3a4
[root@ubuntu1804 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ae90b1abf374 centos7-nginx:1.6.1 "nginx" About a minute ago Up About a minute 0.0.0.0:80->80/tcp naughty_thompson
备注: 最后面的nginx是运行的命令,即镜像里面要运行一个nginx命令,所以前面软链接到/usr/sbin/nginx,目的为了让系统不需要指定路径就可以执行此命令
5.2.6.7 访问测试
[root@ubuntu1804 ~]#curl 127.0.0.1
Nginx Test Page in Docker
5.2.6.8 查看Nginx访问日志和进程
[root@ubuntu1804 ~]#docker exec -it ae90b1abf374 bash
[root@ae90b1abf374 /]# cat /apps/nginx/logs/access.log
172.17.0.1 - - [28/Jan/2020:05:40:51 +0000] "GET / HTTP/1.1" 200 26 "-"
"curl/7.58.0"
[root@ae90b1abf374 /]# ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.2 20572 2468 ? Ss 05:40 0:00 nginx: master process nginx
nginx 6 0.0 0.3 21024 3104 ? S 05:40 0:00 nginx: worker process
root 7 0.3 0.2 11840 2928 pts/0 Ss 05:45 0:00 bash
root 21 0.0 0.3 51764 3344 pts/0 R+ 05:46 0:00 ps aux
5.3 ★★利用 DockerFile 文件执行 docker build 自动构建镜像 ★★
5.3.1 Dockfile 使用详解
5.3.1.1 Dockerfile 介绍
DockerFile 是一种被Docker程序解释执行的脚本,由一条条的命令组成的,每条命令对应linux下面的一条命令,Docker程序将这些DockerFile指令再翻译成真正的linux命令,其有自己的书写方式和支持的命令,Docker程序读取DockerFile并根据指令生成Docker镜像,相比手动制作镜像的方式,DockerFile更能直观的展示镜像是怎么产生的,有了DockerFile,当后期有额外的需求时,只要在之前的DockerFile添加或者修改相应的命令即可重新生成新的Docker镜像,避免了重复手动制作镜像的麻烦,类似与shell脚本一样,可以方便高效的制作镜像
Docker守护程序 Dockerfile 逐一运行指令,如有必要,将每个指令的结果提交到新镜像,然后最终输出新镜像的ID。Docker守护程序将自动清理之前发送的上下文请注意,每条指令都是独立运行的,并会导致创建新镜像,比如 RUN cd /tmp 对下一条指令不会有任何影响。
Docker将尽可能重用中间镜像层(缓存),以显著加速 docker build 命令的执行过程,这由 Using cache 控制台输出中的消息指示
5.3.1.2 Dockerfile 镜像制作和使用流程
5.3.1.3 Dockerfile文件的制作镜像的分层结构
#推荐一种规范化的分层结构(不是必须但是可以参考)
root@ubuntu1804:~# mkdir /data/dockerfile/{web/{nginx,apache,tomcat,jdk},system/{centos,ubuntu,alpine,debian}} -p
root@ubuntu1804:~# tree /data/dockerfile/
/data/dockerfile/
├── system
│ ├── alpine
│ ├── centos
│ ├── debian
│ └── ubuntu
└── web
├── apache
├── jdk
├── nginx
└── tomcat
10 directories, 0 files
5.3.1.4 Dockerfile 文件格式
Dockerfile 是一个有特定语法格式的文本文件
dockerfile 官方说明: https://docs.docker.com/engine/reference/builder/
帮助: man 5 dockerfile
Dockerfile 文件说明
- 每一行以Dockerfile的指令开头,指令不区分大小写,但是惯例使用大写
- 使用 # 开始作为注释
- 每一行只支持一条指令,每条指令可以携带多个参数
- 指令按文件的顺序从上至下进行执行
- 每个指令的执行会生成一个新的镜像层,为了减少分层和镜像大小,尽可能将多条指令合并成一条指令
- 制作镜像一般可能需要反复多次,每次执行dockfile都按顺序执行,从头开始,已经执行过的指令已经缓存,不需要再执行,如果后续有一行新的指令没执行过,其往后的指令将会重新执行,所以为加速镜像制作,将最常变化的内容放下dockerfile的文件的后面
5.3.1.5 ★★Dockerfile 相关指令★★
dockerfile 文件中的常见指令:
ADD
COPY
ENV
EXPOSE
FROM
LABEL
STOPSIGNAL
USER
VOLUME
WORKDIR
5.3.1.5.1 ★★FROM: 指定基础镜像
定制镜像,需要先有一个基础镜像,在这个基础镜像上进行定制。
FROM 就是指定基础镜像,此指令通常必需放在Dockerfile文件第一个非注释行。后续的指令都是运行于此基准镜像所提供的运行环境
基础镜像可以是任何可用镜像文件,默认情况下,docker build会在docker主机上查找指定的镜像文件,在其不存在时,则会从Docker Hub Registry上拉取所需的镜像文件.如果找不到指定的镜像文件,docker build会返回一个错误信息
如何选择合适的镜像呢?
对于不同的软件官方都提供了相关的docker镜像,比如: nginx、redis、mysql、httpd、tomcat等服务类的镜像,也有操作系统类,如: centos、ubuntu、debian等。建议使用官方镜像,比较安全。
格式:
FROM [--platform=<platform>] <image> [AS <name>]
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]
#说明:
--platform 指定镜像的平台,比如: linux/amd64, linux/arm64, or windows/amd64 tag 和 digest是可选项,如果不指定,默认为latest
#举例
FROM scratch #所有镜像的起源镜像,相当于Object类
FROM ubuntu
FROM ubuntu:bionic
FROM debian:buster-slim
说明: 关于scratch 镜像
FROM scratch
参考链接:
https://hub.docker.com/_/scratch?tab=description
https://docs.docker.com/develop/develop-images/baseimages/
该镜像是一个空的镜像,可以用于构建busybox等超小镜像,可以说是真正的从零开始构建属于自己的镜像该镜像在构建基础镜像(例如debian和busybox)或超最小镜像(仅包含一个二进制文件及其所需内容,例如:hello-world)的上下文中最有用。
5.3.1.5.2 LABEL: 指定镜像元数据
可以指定镜像元数据,如: 镜像作者等
#格式
LABEL <key>=<value> <key>=<value> <key>=<value> ...
#举例
LABEL "com.example.vendor"="ACME Incorporated"
LABEL com.example.label-with-value="foo"
LABEL version="1.0"
LABEL description="This text illustrates \
that label-values can span multiple lines."
#一个镜像可以有多个label ,还可以写在一行中,即多标签写法,可以减少镜像的的大小
#一行格式
LABEL multi.label1="value1" multi.label2="value2" other="value3"
#多行格式
LABEL multi.label1="value1" \
multi.label2="value2" \
other="value3"
docker inspect 命令可以查看LABEL
root@ubuntu1804:~# docker inspect tomsun -f "{{.Labels}}"
"Labels": {
"com.example.vendor": "ACME Incorporated"
"com.example.label-with-value": "foo",
"version": "1.0",
"description": "This text illustrates that label-values can span multiple
lines.",
"multi.label1": "value1",
"multi.label2": "value2",
"other": "value3"
},
MAINTAINER: 指定维护者信息
此指令已过时,用LABEL代替
MAINTAINER <name>
MAINTAINER sunx <root@sunx.com>
#用LABEL代替
LABEL maintainer=" sunx <root@sunx.com>"
5.3.1.5.3 ★★RUN: 执行 shell命令
RUN 指令用来在构建镜像阶段需要执行 FROM 指定镜像所支持的Shell命令。
通常各种基础镜像一般都支持丰富的shell命令
注意:
- RUN 可以写多个,每一个RUN指令都会建立一个镜像层,所以尽可能合并成一条指令,比如将多个shell命令通过 && 连接一起成为在一条指令
- 每个RUN都是独立运行的,和前一个RUN无关
#shell 格式: 相当于 /bin/sh -c <命令> 此种形式支持环境变量
RUN <命令>
#exec 格式: 此种形式不支持环境变量,注意:是双引号,不能是单引号
RUN ["可执行文件", "参数1", "参数2"]
#exec格式可以指定其它shell
RUN ["/bin/bash","-c","echo hello wang"]
说明:
shell格式中,<command>通常是一个shell命令,且以"/bin/sh -c”来运行它,这意味着此进程在容器中的PID不为1,不能接收Unix信号,因此,当使用docker stop <container>命令停止容器时,此进程接收不到SIGTERM信号
exec格式中的参数是一个JSON格式的数组,其中<executable>为要运行的命令,后面的<paramN>为传递给命令的选项或参数;然而,此种格式指定的命令不会以"/bin/sh -c"来发起,因此常见的shell操作如变量替换以及通配符(?,*等)替换将不会进行;不过,如果要运行的命令依赖于此shell特性的话,可以将其替换为类似下面的格式。
RUN ["/bin/bash", "-c", "<executable>", "<param1>"]
#举例
RUN echo '<h1>Hello, Docker!</h1>' > /usr/share/nginx/html/index.html
RUN ["/bin/bash", "-c", "echo hello world"]
RUN yum -y install epel-release \
&& yum -y install nginx \
&& rm -rf /usr/share/nginx/html/*
&& echo "<h1> docker test nginx </h1>" > /usr/share/nginx/html/index.html
#多个 前后RUN 命令独立无关和shell命令不同
#world.txt并不存放在/app内
RUN cd /app
RUN echo "hello" > world.txt
5.3.1.5.4 ENV: 设置环境变量
ENV 可以定义环境变量和值,会被后续指令(如:ENV,ADD,COPY,RUN等)通过$KEY或${KEY}进行引用,并在容器运行时保持
#变量赋值格式1
ENV <key> <value> #此格式只能对一个key赋值,<key>之后的所有内容均会被视作其<value>的组成部分
#变量赋值格式2
ENV <key1>=<value1> <key2>=<value2> \ #此格式可以支持多个key赋值,定义多个变量建议使用,减少镜像层
<key3>=<value3> ...
#如果<value>中包含空格,可以以反斜线\进行转义,也可通过对<value>加引号进行标识;另外,反斜线也可用于续行
#只使用一次变量
RUN <key>=<value> <command>
#引用变量
RUN $key .....
#变量支持高级赋值格式
${key:-word}
${kye:+word}
#格式1
ENV myName="John Doe" myDog=Rex\ The\ Dog \
myCat=fluffy
#格式2
ENV myName John Doe
ENV myDog Rex The Dog
ENV myCat fluffy
如果运行容器时如果需要修改变量,可以执行下面通过基于 exec 机制实现
注意: 下面方式只影响容器运行时环境,而不影响构建镜像的过程,即只能覆盖docker run时的环境变量,而不会影响docker build时环境变量的值
docker run -e|--env <key>=<value>
#说明
-e, --env list #Set environment variables
--env-file filename #Read in a file of environment variables
5.3.1.5.5 ★★COPY: 复制文本
复制本地宿主机的文件到容器中的
COPY [--chown=<user>:<group>] <src>... <dest>
COPY [--chown=<user>:<group>] ["<src>",... "<dest>"] #路径中有空白字符时,建议使用此格式
说明:
- 可以是多个,可以使用通配符,通配符规则满足Go的filepath.Match 规则
filepath.Match 参考链接: https://golang.org/pkg/path/filepath/#Match - 必须是build上下文中的路径(为 Dockerfile 所在目录的相对路径),不能是其父目录中的文件
- 如果是目录,则其内部文件或子目录会被递归复制,但目录自身不会被复制
- 如果指定了多个, 或在中使用了通配符,则必须是一个目 录,且必须以 / 结尾
- 可以是绝对路径或者是 WORKDIR 指定的相对路径
- 使用 COPY 指令,源文件的各种元数据都会保留。比如读、写、执行权限、文件变更时间等
- 如果事先不存在,它将会被自动创建,这包括其父目录路径,即递归创建目录
COPY hom* /mydir/
COPY hom?.txt /mydir/
5.3.1.5.6 ★★ADD: 复制和解包文件
该命令可认为是增强版的COPY,不仅支持COPY,还支持自动解缩。可以将复制指定的到容器中的
ADD [--chown=<user>:<group>] <src>... <dest>
ADD [--chown=<user>:<group>] ["<src>",... "<dest>"]
说明:
- 可以是Dockerfile所在目录的一个相对路径;也可是一个 URL;还可是一个 tar 文件(自动解压)
- 可以是绝对路径或者是 WORKDIR 指定的相对路径
- 如果是目录,只复制目录中的内容,而非目录本身
- 如果是一个 URL ,下载后的文件权限自动设置为 600
- 如果为URL且不以/结尾,则指定的文件将被下载并直接被创建为,如果以 / 结尾,则文件名URL指定的文件将被直接下载并保存为/< filename>
- 如果是一个本地文件系统上的打包文件,如: gz, bz2 ,xz ,它将被解包 ,其行为类似于”tar -x”命令,但是通过URL获取到的tar文件将不会自动展开
- 如果有多个,或其间接或直接使用了通配符,则必须是一个以/结尾的目录路径;如果不以/结尾,则其被视作一个普通文件,的内容将被直接写入到
ADD test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/
ADD test /absoluteDir/ # adds "test" to /absoluteDir/
ADD --chown=55:mygroup files* /somedir/
ADD --chown=bin files* /somedir/
ADD --chown=1 files* /somedir/
ADD --chown=10:11 files* /somedir/
ADD ubuntu-xenial-core-cloudimg-amd64-root.tar.gz /
5.3.1.5.7 ★★CMD: 容器启动命令
一个容器中需要持续运行的进程一般只有一个,CMD 用来指定启动容器时默认执行的一个命令,且其运行结束后,容器也会停止,所以一般CMD 指定的命令为持续运行且为前台命令.
- 如果docker run没有指定任何的执行命令或者dockerfile里面也没有ENTRYPOINT,那么开启容器时就会使用执行CMD指定的默认的命令
- 前面介绍过的 RUN 命令是在构建镜像进执行的命令,注意二者的不同之处
- 每个 Dockerfile 只能有一条 CMD 命令。如指定了多条,只有最后一条被执行
- 如果用户启动容器时用 docker run xxx 指定运行的命令,则会覆盖 CMD 指定的命令
# 使用 exec 执行,推荐方式,第一个参数必须是命令的全路径,此种形式不支持环境变量
CMD ["executable","param1","param2"]
# 在 /bin/sh 中执行,提供给需要交互的应用;此种形式支持环境变量
CMD command param1 param2
# 提供给 ENTRYPOINT 命令的默认参数
CMD ["param1","param2"]
CMD ["nginx", "-g", "daemon off;"]
5.3.1.5.8 ★★ENTRYPOINT: 入口点
功能类似于CMD,配置容器启动后执行的命令及参数
# 使用 exec 执行
ENTRYPOINT ["executable", "param1", "param2"]
# shell中执行
ENTRYPOINT command param1 param2
- ENTRYPOINT 不能被 docker run 提供的参数覆盖,而是追加,即如果docker run 命令有参数,那么参数全部都会作为ENTRYPOINT的参数
- 如果docker run 后面没有额外参数,但是dockerfile中的CMD里有(即上面CMD的第三种用法),即Dockerfile中即有CMD也有ENTRYPOINT,那么CMD的全部内容会作为ENTRYPOINT的参数
- 如果docker run 后面有额外参数,同时Dockerfile中即有CMD也有ENTRYPOINT,那么docker run后面的参数覆盖掉CMD参数内容,最终作为ENTRYPOINT的参数
- 可以通过docker run –entrypoint string 参数在运行时替换,注意string不要加空格
- 使用CMD要在运行时重新写命令本身,然后在后面才能追加运行参数,ENTRYPOINT则可以运行时无需重写命令就可以直接接受新参数
- 每个 Dockerfile 中只能有一个 ENTRYPOINT,当指定多个时,只有最后一个生效
5.3.1.5.9 ARG: 构建参数
ARG指令在build 阶段指定变量,和ENV不同的是,容器运行时不会存在这些环境变量
ARG <name>[=<default value>]
如果和ENV同名,ENV覆盖ARG变量
可以用 docker build –build-arg <参数名>=<值> 来覆盖
说明: ARG 和 FROM
#FROM指令支持由第一个FROM之前的任何ARG指令声明的变量
#示例:
ARG CODE_VERSION=latest
FROM base:${CODE_VERSION}
CMD /code/run-app
FROM extras:${CODE_VERSION}
CMD /code/run-extras
#在FROM之前声明的ARG在构建阶段之外,所以它不能在FROM之后的任何指令中使用。 要使用在第一个FROM之前声明的ARG的默认值,请在构建阶段内使用没有值的ARG指令
#示例:
ARG VERSION=latest
FROM busybox:$VERSION
ARG VERSION
RUN echo $VERSION > image_version
5.3.1.5.11 VOLUME: 匿名卷
在容器中创建一个可以从本地主机或其他容器挂载的挂载点,一般用来存放数据库和需要保持的数据等,一般会将宿主机上的目录挂载至VOLUME 指令指定的容器目录。即使容器后期被删除,此宿主机的目录仍会保留,从而实现容器数据的持久保存。
宿主机目录为
/var/lib/docker/volumes/<volume_id>/_data
语法:
VOLUME <容器内路径>
VOLUME ["<容器内路径1>", "<容器内路径2>"...]
注意:
- Dockerfile中的VOLUME实现的是匿名数据卷,无法指定宿主机路径和容器目录的挂载关系
- 通过docker rm -fv <容器ID> 可以删除容器的同时删除VOLUME指定的卷
5.3.1.5.12 ★★EXPOSE: 暴露端口
指定服务端的容器需要对外暴露(监听)的端口号,以实现容器与外部通信。
EXPOSE 仅仅是声明容器打算使用什么端口而已,并不会真正暴露端口,即不会自动在宿主进行端口映射
因此,在启动容器时需要通过 -P 或-p ,Docker 主机才会真正分配一个端口转发到指定暴露的端口才可使用
注意: 即使 Dockerfile没有EXPOSE 端口指令,也可以通过docker run -p 临时暴露容器内程序真正监听的端口,所以EXPOSE 相当于指定默认的暴露端口,可以通过docker run -P 进行真正暴露
EXPOSE <port>[/ <protocol>] [<port>[/ <protocol>] ..]
#说明
<protocol>用于指定传输层协议,可为tcp或udp二者之一,默认为TCP协议
5.3.1.5.13 WORKDIR: 指定工作目录
为后续的 RUN、CMD、ENTRYPOINT 指令配置工作目录,当容器运行后,进入容器内WORKDIR指定的默认目录
WORKDIR 指定工作目录(或称当前目录),以后各层的当前目录就被改为指定的目录,如该目录不存在,WORKDIR 会自行创建
WORKDIR /path/to/workdir
#两次RUN独立运行,不在同一个目录,
RUN cd /app
RUN echo "hello" > world.txt
#如果想实现相同目录可以使用WORKDIR
WORKDIR /app
RUN echo "hello" > world.txt
#可以使用多个 WORKDIR 指令,后续命令如果参数是相对路径,则会基于之前命令指定的路径
WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd
#则最终路径为 /a/b/c
5.3.1.5.14 ONBUILD: 子镜像引用父镜像的指令
可以用来配置当构建当前镜像的子镜像时,会自动触发执行的指令,但在当前镜像构建时,并不会执行,即延迟到子镜像构建时才执行
ONBUILD [INSTRUCTION]
#Dockerfile 使用如下的内容创建了镜像 image-A
...
ONBUILD ADD http://www.magedu.com/wp-content/uploads/2017/09/logo.png /data/
ONBUILD RUN rm -rf /*
ONBUILD RUN /usr/local/bin/python-build --dir /app/src...
#如果基于 image-A 创建新的镜像image-B时,新的Dockerfile中使用 FROM image-A指定基础镜像时,会自动执行ONBUILD 指令内容,等价于在后面添加了三条指令。
FROM image-A
#Automatically run the following
ADD http://www.magedu.com/wp-content/uploads/2017/09/logo.png /data
RUN rm -rf /*
RUN /usr/local/bin/python-build --dir /app/src
说明:
- 尽管任何指令都可注册成为触发器指令,但ONBUILD不能自我能套,且不会触发FROM和MAINTAINER指令
- 使用 ONBUILD 指令的镜像,推荐在标签中注明,例如 ruby:1.9-onbuild
5.3.1.5.15 USER: 指定当前用户
指定运行容器时的用户名或 UID,后续的 RUN 也会使用指定用户
当服务不需要管理员权限时,可以通过该命令指定运行用户
这个用户必须是事先建立好的,否则无法切换
如果没有指定 USER,默认是 root 身份执行
USER <user>[:<group>]
USER <UID>[:<GID>]
RUN groupadd -r mysql && useradd -r -g mysql mysql
USER mysql
5.3.1.5.16 HEALTHCHECK: 健康检查
检查容器的健康性
HEALTHCHECK [选项] CMD <命令> #设置检查容器健康状况的命令
HEALTHCHECK NONE #如果基础镜像有健康检查指令,使用这行可以屏蔽掉其健康检查指令
HEALTHCHECK 支持下列选项:
--interval=<间隔> #两次健康检查的间隔,默认为 30 秒
--timeout=<时长> #健康检查命令运行超时时间,如果超过这个时间,本次健康检查就被视为失败,默认 30 秒
--retries=<次数> #当连续失败指定次数后,则将容器状态视为 unhealthy,默认3次
--start-period=<FDURATION> #default: 0s
#检查结果返回值:
0 #success the container is healthy and ready for use
1 #unhealth the container is not working correctly
2 #reserved do not use this exit code
5.3.1.5.17 STOPSIGNAL: 退出容器的信号
该 STOPSIGNAL 指令设置将被发送到容器退出的系统调用信号。该信号可以是与内核syscall表中的位置匹配的有效无符号数字(例如9),也可以是SIGNAME格式的信号名称(例如SIGKILL)
STOPSIGNAL signal
5.3.1.5.18 SHELL : 指定shell
SHELL指令允许覆盖用于命令的shell形式的默认SHELL, 必须在Dockerfile中以JSON形式编写SHELL指令。
SHELL ["executable", "parameters"]
在Linux上默认SHELL程序为[“/bin/sh”,“-c”],在Windows上,默认SHELL程序为[“cmd”,“/S”,“/C”]。
SHELL指令在Windows上特别有用,在Windows上有两个常用且完全不同的本机SHELL:cmd和powershell,以及包括sh在内的备用shell。
SHELL指令可以出现多次。 每个SHELL指令将覆盖所有先前的SHELL指令,并影响所有后续的指令
5.3.1.5.18 .dockerignore文件
官方文档: https://docs.docker.com/engine/reference/builder/#dockerignore-file与.gitignore文件类似,生成构建上下文时Docker客户端应忽略的文件和文件夹指定模式.dockerignore 使用 Go 的文件路径规则 filepath.Match
参考链接: https://golang.org/pkg/path/filepath/#Match
完整的语法
# #以#开头的行为注释
* #匹配任何非分隔符字符序列
? #匹配任何单个非分隔符
\\ #表示 \
** #匹配任意数量的目录(包括零)例如,**/*.go将排除在所有目录中以.go结尾的所有文件,包括构
建上下文的根。
! #表示取反,可用于排除例外情况
Rule |
Behavior |
---|---|
# comment |
Ignored. |
*/temp* |
Exclude files and directories whose names start with temp in any immediate subdirectory of the root. For example, the plain file /somedir/temporary.txt is excluded, as is the directory /somedir/temp . |
*/*/temp* |
Exclude files and directories starting with temp from any subdirectory that is two levels below the root. For example, /somedir/subdir/temporary.txt is excluded. |
temp? |
Exclude files and directories in the root directory whose names are a one- character extension of temp . For example, /tempa and /tempb are excluded. |
#排除 test 目录下的所有文件
test/*
#排除 md 目录下的 xttblog.md 文件
md/xttblog.md
#排除 xttblog 目录下的所有 .md 的文件
xttblog/*.md
#排除以 xttblog 为前缀的文件和文件夹
xttblog?
#排除所有目录下的 .sql 文件夹
**/*.sql
#除了README的md不排外,排除所有md文件,但不排除README-secret.md
*.md
!README*.md
README-secret.md
#除了所有README的md文件以外的md都排除
*.md
README-secret.md
!README*.md
5.3.1.5.19 Dockerfile 构建过程和指令总结
Dockerfile 构建过程
- 从基础镜像运行一个容器
- 执行一条指令,对容器做出修改
- 执行类似docker commit的操作,提交一个新的中间镜像层(可以利用中间层镜像创建容器进行调试和排错)
- 再基于刚提交的镜像运行一个新容器
- 执行Dockerfile中的下一条指令,直至所有指令执行完毕
Dockerfile 指令总结
5.3.1.6 构建镜像docker build 命令
docker build命令使用Dockerfile文件创建镜像
docker build [OPTIONS] PATH | URL | -
说明:
PATH | URL | - #可以使是本地路径,也可以是URL路径。若设置为 - ,则从标准输入获取
Dockerfile的内容
-f, --file string #Dockerfile文件名,默认为 PATH/Dockerfile
--force-rm #总是删除中间层容器,创建镜像失败时,删除临时容器
--no-cache #不使用之前构建中创建的缓存
-q --quiet=false #不显示Dockerfile的RUN运行的输出结果
--rm=true #创建镜像成功时,删除临时容器
-t --tag list #设置注册名称、镜像名称、标签。格式为 <注册名称>/<镜像名称>:<标签>(标签默认为latest)
查看镜像的构建历史: docker history 镜像ID
5.3.2 实战案例: Dockerfile 制作基于基础镜像的Base镜像
5.3.2.1 准备目录结构,下载镜像并初始化系统
#按照业务类型或系统类型等方式划分创建目录环境,方便后期镜像比较多的时候进行分类
[root@ubuntu1804 ~]#mkdir /data/dockerfile/{web/{nginx,apache,tomcat,jdk},system/{centos,ubuntu,alpine,debian}} -p
root@ubuntu1804:/data/dockerfile# tree /data/dockerfile/
/data/dockerfile/
├── system
│ ├── alpine
│ ├── centos
│ ├── debian
│ └── ubuntu
└── web
├── apache
├── jdk
├── nginx
└── tomcat
10 directories, 0 files
#下载基础镜像
root@ubuntu1804:/data/dockerfile# docker pull centos:centos7
centos7: Pulling from library/centos
2d473b07cdd5: Pull complete
Digest: sha256:9d4bcbbb213dfd745b58be38b13b996ebb5ac315fe75711bd618426a630e0987
Status: Downloaded newer image for centos:centos7
docker.io/library/centos:centos7
root@ubuntu1804:/data/dockerfile# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos centos7 eeb6ee3f44bd 7 weeks ago 204MB
5.3.2.2 先制作基于基础镜像的系统Base镜像
#切换到对应目录下
root@ubuntu1804:/data/dockerfile# cd /data/dockerfile/system/centos/
root@ubuntu1804:/data/dockerfile/system/centos# mkdir {7,8}
root@ubuntu1804:/data/dockerfile/system/centos# cd 7
#创建Dockerfile,注意可以是dockerfile,但无语法着色功能
root@ubuntu1804:/data/dockerfile/system/centos/7# vim Dockerfile
FROM centos:centos7
LABEL maintainer="sunx <root@sunx.com>"
RUN yum install -y wget && rm -f /etc/yum.repos.d/* && wget -P /etc/yum.repos.d/ http://mirrors.aliyun.com/repo/Centos-7.repo \
&& wget -P /etc/yum.repos.d/ http://mirrors.aliyun.com/repo/epel-7.repo \
&& yum install -y vim-enhanced tcpdump lrzsz tree telnet bash-completion net-tools wget curl bzip2 lsof zip unzip nfs-utils gcc make gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel systemd-devel zlib-devel \
&& yum clean all \
&& rm -f /etc/localtime \
&& ln -s ../usr/share/zoneinfo/Asia/Shanghai /etc/localtime
#通过Dockerfile构建镜像
root@ubuntu1804:/data/dockerfile/system/centos/7# docker builed -t centos-base:2.0
root@ubuntu1804:/data/dockerfile/system/centos/7# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos-base 2.0 5e579ff2494d 39 seconds ago 431MB
#查看历史操作
root@ubuntu1804:/data/dockerfile/system/centos/7# docker history centos-base:2.0
IMAGE CREATED CREATED BY SIZE COMMENT
5e579ff2494d About a minute ago /bin/sh -c yum install -y wget && rm -f /etc… 227MB
b9b535e149b3 3 minutes ago /bin/sh -c #(nop) LABEL maintainer=sunx <ro… 0B
#运行镜像,进入容器查看一下配置文件是否生效
root@ubuntu1804:/data/dockerfile/system/centos/7# docker run -it --name centos-base centos-base:2.0
[root@c63e2e3933d8 /]# cat /etc/yum.repos.d/Centos-7.repo
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client. You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[base]
name=CentOS-$releasever - Base - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/os/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/os/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#released updates
[updates]
name=CentOS-$releasever - Updates - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/updates/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/extras/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/centosplus/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/centosplus/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#contrib - packages by Centos Users
[contrib]
name=CentOS-$releasever - Contrib - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/contrib/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/contrib/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/contrib/$basearch/
gpgcheck=1
enabled=0
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
[root@c63e2e3933d8 /]# cat /etc/yum.repos.d/epel-7.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
baseurl=http://mirrors.aliyun.com/epel/7/$basearch/debug
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=0
[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
baseurl=http://mirrors.aliyun.com/epel/7/SRPMS
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=0
[root@c63e2e3933d8 /]#
5.3.3 实战案例: Dockerfile 制作基于Base镜像的 nginx 镜像
5.3.3.1 在Dockerfile目录下准备编译安装的相关文件
root@ubuntu1804:/data/dockerfile# tree /data/dockerfile/
/data/dockerfile/
├── system
│ ├── alpine
│ ├── centos
│ │ ├── 7
│ │ │ └── Dockerfile
│ │ └── 8
│ ├── debian
│ └── ubuntu
└── web
├── apache
├── jdk
├── nginx
└── tomcat
12 directories, 1 file
#下载二进制源码包
root@ubuntu1804:/data/dockerfile# cd /data/dockerfile/web/nginx/
root@ubuntu1804:/data/dockerfile/web/nginx# wget http://nginx.org/download/nginx-1.16.1.tar.gz
--2021-11-06 07:45:28-- http://nginx.org/download/nginx-1.16.1.tar.gz
Resolving nginx.org (nginx.org)... 3.125.197.172, 52.58.199.22, 2a05:d014:edb:5704::6, ...
Connecting to nginx.org (nginx.org)|3.125.197.172|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1032630 (1008K) [application/octet-stream]
Saving to: ‘nginx-1.16.1.tar.gz’
nginx-1.16.1.tar.gz 100%[===============================>] 1008K 115KB/s in 9.0s
2021-11-06 07:45:38 (111 KB/s) - ‘nginx-1.16.1.tar.gz’ saved [1032630/1032630]
root@ubuntu1804:/data/dockerfile/web/nginx# ls
nginx-1.16.1.tar.gz
#创建网页文件
root@ubuntu1804:/data/dockerfile/web/nginx# mkdir app/
root@ubuntu1804:/data/dockerfile/web/nginx# echo "hello nginx" > app/index.html
root@ubuntu1804:/data/dockerfile/web/nginx# tar zcf app.tar.gz app
root@ubuntu1804:/data/dockerfile/web/nginx# ll
total 1028
drwxr-xr-x 3 root root 4096 Nov 6 07:47 ./
drwxr-xr-x 6 root root 4096 Nov 5 11:39 ../
drwxr-xr-x 2 root root 4096 Nov 6 07:46 app/
-rw-r--r-- 1 root root 162 Nov 6 07:47 app.tar.gz
-rw-r--r-- 1 root root 1032630 Aug 14 2019 nginx-1.16.1.tar.gz
5.3.3.2 在一台测试机进行编译安装同一版本的nginx 生成模版配置文件
[root@centos7 ~]#yum -y install vim-enhanced tcpdump lrzsz tree telnet bash-completion net-tools wget bzip2 lsof tmux man-pages zip unzip nfs-utils gcc make gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel systemd-devel zlib-devel
[root@centos7 ~]#wget -P /usr/local/src http://nginx.org/download/nginx-1.16.1.tar.gz
[root@centos7 ~]#cd /usr/local/src/
[root@centos7 src]#tar xvf nginx-1.16.1.tar.gz
[root@centos7 src]#cd nginx-1.16.1/
[root@centos7 nginx-1.16.1]#./configure --prefix=/apps/nginx && make && make install
#将配置文件复制到nginx镜像的服务器相应目录下
[root@centos7 ~]#scp /apps/nginx/conf/nginx.conf 10.0.0.100:/data/dockerfile/web/nginx/1.16
#准备配置文件
root@ubuntu1804:/data/dockerfile/web/nginx# vim nginx.conf
#user nobody;
worker_processes 1;
daemon off;
5.3.3.3 编写Dockerfile文件
root@ubuntu1804:/data/dockerfile/web/nginx# vim Dockerfile
FROM centos-base:2.0
LABEL maintainer="sunx <root@sunx.com>"
ADD nginx-1.16.1.tar.gz /usr/local/src
RUN cd /usr/local/src/nginx-1.16.1 \
&& ./configure --prefix=/app/nginx \
&& make && make install \
&& useradd -r nginx
COPY nginx.conf /app/nginx/conf/
ADD app.tar.gz /app/nginx/html
EXPOSE 80 443
CMD [ "/app/nginx/sbin/nginx" ]
5.3.3.4 生成nginx镜像
root@ubuntu1804:/data/dockerfile/web/nginx# ls
app app.tar.gz Dockerfile nginx-1.16.1.tar.gz nginx.conf
root@ubuntu1804:/data/dockerfile/web/nginx# docker build -t nginx-1-16:2.0 .
Successfully built 453efdb8511c
Successfully tagged nginx-1-16:2.0
root@ubuntu1804:/data/dockerfile/web/nginx# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx-1-16 2.0 453efdb8511c 10 seconds ago 454MB
centos-base 2.0 5e579ff2494d 12 hours ago 431MB
5.3.3.5 生成的容器测试镜像
root@ubuntu1804:/data/dockerfile/web/nginx# docker run -d -p 80:80 nginx-1-16:2.0
551db0318007b8ca765ce7f9a3f228a187fd7df1d0c377b6f5cbbfe206522354
root@ubuntu1804:/data/dockerfile/web/nginx# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
551db0318007 nginx-1-16:2.0 "/app/nginx/sbin/ngi…" 5 seconds ago Up 4 seconds 0.0.0.0:80->80/tcp, 443/tcp admiring_kirch
root@ubuntu1804:/data/dockerfile/web/nginx# curl 127.0.0.1:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
root@ubuntu1804:/data/dockerfile/web/nginx# docker exec -it 551db0318007b8ca765ce7f9a3f228a187fd7df1d0c377b6f5cbbfe206522354 bash
[root@551db0318007 /]# ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.2 20568 2676 ? Ss 08:33 0:00 nginx: master process /app/ngi
nobody 9 0.0 0.2 21020 2240 ? S 08:33 0:00 nginx: worker process
root 10 0.4 0.3 12336 3560 pts/0 Ss 08:34 0:00 bash
root 29 0.0 0.3 51744 3300 pts/0 R+ 08:34 0:00 ps aux
[root@551db0318007 /]# exit
exit
root@ubuntu1804:/data/dockerfile/web/nginx# curl 127.0.0.1/app/
hello nginx
5.3.4 实战案例: Dockerfile 直接制作 nginx 镜像
5.3.4.1 在Dockerfile目录下准备编译安装的相关文件
root@ubuntu1804:/data/dockerfile/web# mkdir nginx1/
root@ubuntu1804:/data/dockerfile/web# cd nginx1
root@ubuntu1804:/data/dockerfile/web/nginx1# pwd
/data/dockerfile/web/nginx1
root@ubuntu1804:/data/dockerfile/web/nginx1# wget http://nginx.org/download/nginx-1.16.1.tar.gz
--2021-11-06 08:41:10-- http://nginx.org/download/nginx-1.16.1.tar.gz
#将之前创建的一些文件复制到新文件夹中
root@ubuntu1804:/data/dockerfile/web/nginx1# cd ../nginx
root@ubuntu1804:/data/dockerfile/web/nginx# cp app nginx-1.16.1.tar.gz nginx.conf /data/dockerfile/web/nginx1
root@ubuntu1804:/data/dockerfile/web/nginx# ls ../nginx1
app Dockerfile nginx-1.16.1.tar.gz nginx.conf
root@ubuntu1804:/data/dockerfile/web/nginx# cd ../nginx1
root@ubuntu1804:/data/dockerfile/web/nginx1# vim nginx.conf
#user nobody;
worker_processes 1;
#daemon off;
5.3.4.2 编写Dockerfile文件
root@ubuntu1804:/data/dockerfile/web/nginx1# vim Dockerfile
FROM centos:centos7
LABEL maintainer="sunx <root@sunx.com>"
RUN yum install -y make gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel \
&& useradd -r -s /sbin/nologin nginx \
&& yum clean all
ADD nginx-1.16.1.tar.gz /usr/local/src/
RUN cd /usr/local/src/nginx-1.16.1 \
&& ./configure --prefix=/app/nginx \
&& make && make install
ADD nginx.conf /app/nginx/conf/nginx.conf
COPY app/index.html /app/nginx/html/
RUN ln -s /app/nginx/sbin/nginx /usr/sbin/nginx
EXPOSE 80 443
CMD [ "nginx","-g","daemon off;" ]
5.3.4.3 生成nginx镜像
root@ubuntu1804:/data/dockerfile/web/nginx1# vim build.sh
#!/bin/bash
#
TAG=$1
docker build -t centos7-nginx:$TAG .
root@ubuntu1804:/data/dockerfile/web/nginx1#chmod +x build.sh
root@ubuntu1804:/data/dockerfile/web/nginx1#ls
build.sh Dockerfile index.html nginx-1.16.1.tar.gz nginx.conf
root@ubuntu1804:/data/dockerfile/web/nginx1# ./build.sh 3.0
Sending build context to Docker daemon 1.043MB
Step 1/10 : FROM centos:centos7
---> eeb6ee3f44bd
Step 2/10 : LABEL maintainer="sunx <root@sunx.com>"
---> Using cache
---> b9b535e149b3
Step 3/10 : RUN yum install -y make gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel && useradd -r -s /sbin/nologin nginx && yum clean all
---> Using cache
---> c446ea06ca46
Step 4/10 : ADD nginx-1.16.1.tar.gz /usr/local/src/
---> Using cache
---> d66a6b0b2fa7
Step 5/10 : RUN cd /usr/local/src/nginx-1.16.1 && ./configure --prefix=/app/nginx && make && make install
---> Using cache
---> fe1d39247473
Step 6/10 : ADD nginx.conf /app/nginx/conf/nginx.conf
---> Using cache
---> facce4817ad4
Step 7/10 : COPY app/index.html /app/nginx/html/
---> f2630c1630c7
Step 8/10 : RUN ln -s /app/nginx/sbin/nginx /usr/sbin/nginx
---> Running in 2dc33c9bd68e
Removing intermediate container 2dc33c9bd68e
---> 3524815e50bb
Step 9/10 : EXPOSE 80 443
---> Running in f7281e3d135f
Removing intermediate container f7281e3d135f
---> 94fcf2adcc32
Step 10/10 : CMD [ "nginx","-g","daemon off;" ]
---> Running in 913c8df213fb
Removing intermediate container 913c8df213fb
---> 22bb20393481
Successfully built 22bb20393481
Successfully tagged centos7-nginx:3.0
root@ubuntu1804:/data/dockerfile/web/nginx1# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos7-nginx 3.0 22bb20393481 About a minute ago 356MB
5.3.4.4 生成容器测试镜像
root@ubuntu1804:/data/dockerfile/web/nginx1# docker run -d -p 80:80 centos7-nginx:3.0
24fdc20e5680d2a6febbadf516aad622c613937c5c57b2f9c6184029c34fcd4f
root@ubuntu1804:/data/dockerfile/web/nginx1# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
24fdc20e5680 centos7-nginx:3.0 "nginx -g 'daemon of…" 4 seconds ago Up 3 seconds 0.0.0.0:80->80/tcp, 443/tcp nostalgic_leavitt
root@ubuntu1804:/data/dockerfile/web/nginx1# curl 127.0.0.1
hello nginx
root@ubuntu1804:/data/dockerfile/web/nginx1# docker exec -it 24fdc20e5680 bash
[root@24fdc20e5680 /]# ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.2 20568 2748 ? Ss 01:15 0:00 nginx: master process nginx -g
nobody 6 0.0 0.2 21016 2344 ? S 01:15 0:00 nginx: worker process
root 7 0.2 0.3 11840 3004 pts/0 Ss 01:16 0:00 bash
root 21 0.0 0.3 51744 3516 pts/0 R+ 01:16 0:00 ps aux
[root@24fdc20e5680 /]#