1 Docker 核心概念

1.1 为什么要用容器?

  1. 上线流程繁琐

开发 → 测试 → 申请资源 → 审批 → 部署 → 测试等环节

  1. 资源利用率低

普遍服务器利用率低,造成过多浪费[ 传统的虚拟化,利用率也是较低的,也不能一直将服务器的利用率一直占满 ]

  1. 扩容/缩容不及时

业务高峰期扩容流程繁琐,上线不及时

  1. 服务器环境臃肿

服务器越来越臃肿,对维护、迁移带来困难[ 需要对服务器集群环境进行治理 ]

  1. 环境不一致性

测试环境,开发环境,线上环境

:::color1 (1)已知的业务承载量

(2)未知的业务承载量

  • 业务机器增加承载量,可以应对一些突发,30%
  • 弹性伸缩,HPA

:::

1.2 Docker 是什么

  • 使用最广泛的开源容器引擎
  • 一种操作系统级的虚拟化技术[ 沙盒技术 ]
  • 依赖于Linux内核特性:Namespace( 资源隔离 )和Cgroups( 资源限制 )
NameSpace 系统调用参数 隔离内容
UTS CLONE_NEWUTS 主机和域名
IPC CLONE_NEWIPC 进程信号量、消息队列和共享内存
PID CLONE_NEWPID 进程编号
Network CLONE_NEWNET 网络设备、网络栈、端口等
Mount CLONE_NEWNS 挂载点(文件系统)
User CLONE_NEWUSER 用户和用户组

CGroups 资源控制系统,每种子系统独立地控制一种资源。功能如下

子系统 功能
cpu 使用调度程序控制任务对CPU的使用。
cpuacct(CPU Accounting) 自动生成cgroup中任务对CPU资源使用情况的报告。
cpuset 为cgroup中的任务分配独立的CPU(多处理器系统时)和内存。
devices 开启或关闭cgroup中任务对设备的访问
freezer 挂起或恢复cgroup中的任务
memory 设定cgroup中任务对内存使用量的限定,并生成这些任务对内存资源使用 情况的报告
perf_event(Linux CPU性能探测器) 使cgroup中的任务可以进行统一的性能测试
net_cls(Docker未使用) 通过等级识别符标记网络数据包,从而允许Linux流量监控程序(Trawic Controller)识别从具体cgroup中生成的数据包
  • 一个简单的应用程序打包工具

1.3 Docker 设计目标

  • 提供简单的应用程序打包工具
  • 开发人员和运维人员职责逻辑分离
    • 开发人员:
      • 1、开发项目
      • 2、打包项目环境 + 代码成镜像
      • 3、部署到容器平台
    • 运维人员:怎么高效去管理容器
      • 1、运维人员节省人工成本
      • 2、持续发布有问题更快解决
  • 多环境保持一致性,标准化

01 Docker 基础部分 - 图1

1.4 Docker 基本组成

01 Docker 基础部分 - 图2

01 Docker 基础部分 - 图3

:::color1

Client 客户端,Docker Host 宿主机,Docker Registry 仓库。Docker 可以一种客户端连接到 Docker Host主机后台程序进行操作。
  1. Docker 引擎会查看本地是否拥有Images镜像,若本地有镜像,则可以直接运行成Containers容器实例,根据镜像的不同,运行出的容器实例也各不相同
  2. 若本地没有镜像,则会通过网络向公有Registry仓库或者私有仓库拉取镜像后,再来运行成容器。
Docker 是一个 C/S(Client/Server) 结构的系统,Docker 守护进程运行在主机上,然后通过Socket连接在客户端访问,守护进程从客户端接受命令并管理运行在主机上的容器。容器,是一个运行时环境,就是我们说的集装箱。可以对比 MySQL 演示对比讲解01 Docker 基础部分 - 图4 ::: :::color1 整体架构及底层通信原理简述: 01 Docker 基础部分 - 图5 Docker 是一个 C/S(Client/Server) 结构的系统,后端是一个松耦合架构,众多模块各司其职。 Docker 运行的基本流程为: 1. 用户是使用 Docker Client(Docker CLI 命令行窗口) 与 Docker Daemon 建立通信,并发送请求给后者。 2. Docker Daemon 作为 Docker 架构中的主体部分,首先提供 Docker Server 的功能使其可以接受 Docker Client 的请求。 3. Docker Engine 执行 Docker 内部的一系列工作,每一项工作都是以一个Job的形式的存在。 4. Job 的运行过程中,当需要容器镜像时,则从 Docker Registry 中下载镜像,并通过镜像管理驱动 Graph Driver 将下载镜像以 Graph 的形式存储。 5. 当需要为 Docker 创建网络环境时,通过网络管理驱动 Network Driver 创建并配置 Docker 容器网络环境。 6. 当需要限制 Docker 容器运行资源或者执行用户指令等操作时,则通过 Exec Driver 来完成。 7. Libcontainer 是一项独立的容器管理包,Network Driver 以及 Exec Driver 都是通过 Libcontainer 来实现具体对容器进行操作。 8. rootfs = Linux 根文件系统,各发行版建立在 Linux内核文件系统 之上的底层系统 ::: ## 1.5 容器 VS 虚拟机 01 Docker 基础部分 - 图6 01 Docker 基础部分 - 图7 ### 1.5.1 虚拟机 虚拟机(Virtual Machine)就是带环境安装的一种解决方案。 虚拟机可以在一种操作系统里面运行另一种操作系统,比如在 Windows 10系统里面运行Linux镜像CentOS 7。应用程序对此毫无感知,因为虚拟机看上去跟真实系统一模一样,而对于底层操作系统来说,虚拟机就是一个普通文件,不需要了就删除,对其他部分毫无影响。这些虚拟机完美的运行了另一套操作系统,能够使应用程序,操作系统和硬件三者之间的逻辑不变。 > Windows10 —> VMware —> CentOS 7 —> 各种CPU,内存网络配置+各种软件 —> 虚拟机实例 > 传统虚拟机技术基于安装在主操作系统上的虚拟机管理系统(如:VirtualBox 和 VMware等),创建虚拟机(虚拟出各种硬件),在虚拟机上安装从操作系统,在从操作系统中安装各种应用。 01 Docker 基础部分 - 图8 传统虚拟机技术缺点: 1. 资源占用多 2. 冗余步骤多 3. 启动速度慢 ### 1.5.2 容器 由于前面虚拟机存在某些缺点,Linux发展出了另一种虚拟化容器:

<font style="color:#E8323C;">Linux容器(Linux Containers),缩写为 LXC</font>

Linux 容器是与系统其他部分隔离开的一系列进程,从另一个镜像运行,并由该镜像提供支持进程所需的全部文件。容器提供的镜像包含了应用的所有依赖项,因而在从开发到测试再到生产的整个过程中,它都具有可移植性和一致性。

<font style="color:#E8323C;">Linux容器不是模拟一个完整的操作系统而是对进程进行隔离</font>。有了容器,就可以将软件运行所需的所有资源打包到一个隔离的容器中。<font style="color:#E8323C;">容器与虚拟机不同,不需要捆绑一整套操作系统</font>,只需要软件工作所需的库资源和设置。系统因此而变得高效轻量并且保证部署在任何环境中的软件都能始终如一的运行。

01 Docker 基础部分 - 图9

01 Docker 基础部分 - 图10

Docker 容器是在操作系统层面上实现虚拟化,直接复用本地主机的操作系统,而传统虚拟机则是在硬件层面实现虚拟化。与传统的虚拟机相比,<font style="color:#E8323C;">Docker 优势体现为启动速度快,占用体积小</font>

1.5.3 容器 VS 虚拟机对比

01 Docker 基础部分 - 图11

比较了 Docker 和传统虚拟化方式的不同之处:

  • 传统虚拟机技术是虚拟出一套硬件后,在其之上运行一个完整的操作系统,在该系统上再运行所需的应用进程。
  • 容器内的应用进程直接运行于宿主机的内核,容器内没有自己的内核并<font style="color:#E8323C;">且也没有进行硬件虚拟</font>。因此容器比传统虚拟机更为轻便。
  • 每个容器之间互相隔离,每个容器有自己的文件系统,容器之间进程不会互相影响,能区分计算资源。
Container VM
启动速度 秒级 分钟级
运行性能 接近原生 5% 左右损失
磁盘占用 MB GB
数量 成百上千 一般几十台
隔离性 进程级 系统级( 更彻底 )
操作系统 主要支持Linux 几乎所有
封装程度 只打包项目代码和依赖关系,共享宿主机内核 完整的操作系统

:::color1 容器:

  1. 提供一个基本的独立环境,实现容器隔离,资源限制
  2. 主要解决应用层面的问题,应用快速部署,高效管理

虚拟机:

  1. 提升服务器资源利用率
  2. 提供一个完全隔离的环境

:::

1.6 Docker 应用场景

  • 应用程序打包和发布
  • 应用程序隔离
  • 持续集成
  • 部署微服务
  • 快速搭建测试环境
  • 提供PaaS产品( 平台即服务 )

1.7 Linux 安装 Docker

:::color1 Docker版本:

社区版 ( Community Edition , CE )

企业版 ( Enterprise Edition , EE )

支持平台:

  • Linux (CentOS, Debian, Fedora, Oracle Linux, RHEL, SUSE 和 Ubuntu)
  • Mac
  • Windows

:::

1.7.1 CentOS 部署 Docker

安装依赖包

  1. yum install -y yum-utils

添加Docker软件包源

  1. yum-config-manager \
  2. --add-repo \
  3. https://download.docker.com/linux/centos/docker-ce.repo

安装Docker CE

  1. yum install -y docker-ce

启动Docker服务并设置开机启动

  1. systemctl enable --now docker

官方文档:https://docs.docker.com

Docker官方二进制文档:https://docs.docker.com/engine/install/binaries/

阿里云源:http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

范例:CentOS 部署 Docker 脚本

  1. #!/bin/bash
  2. # Shell ENV
  3. DOCKER_VERSION="20.10.7"
  4. CONTAINERD_VERSION="1.4.6"
  5. # step 1: 安装必要的一些系统工具
  6. echo -e "==> 安装必要的系统工具"
  7. sudo yum install -y yum-utils device-mapper-persistent-data lvm2
  8. # Step 2: 添加软件源信息
  9. echo -e "==> 添加软件源信息"
  10. sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
  11. # Step 3
  12. echo -e "==> 修改配置文件"
  13. sudo sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo
  14. # Step 4: 更新并安装Docker-CE
  15. echo -e "==> 安装更新Docker"
  16. sudo yum makecache fast
  17. # containerd.io Docker运行时环境
  18. sudo yum -y install docker-ce-${DOCKER_VERSION} docker-ce-cli-${DOCKER_VERSION} containerd.io-${CONTAINERD_VERSION}
  19. # Step 5: 配置加速器以及docker参数
  20. echo -e "==> 配置加速器以及docker参数"
  21. sudo mkdir -p /etc/docker
  22. sudo tee /etc/docker/daemon.json <<-'EOF'
  23. {
  24. "registry-mirrors": ["https://po13h3y1.mirror.aliyuncs.com","http://hub-mirror.c.163.com","https://mirror.ccs.tencentyun.com","http://f1361db2.m.daocloud.io"],
  25. "exec-opts": ["native.cgroupdriver=systemd"],
  26. "log-driver": "json-file",
  27. "log-opts": {
  28. "max-size": "100m"
  29. },
  30. "storage-driver": "overlay2"
  31. }
  32. EOF
  33. # Step 6: 加载服务
  34. echo -e "==> 加载服务"
  35. sudo systemctl daemon-reload
  36. sudo systemctl restart docker
  37. sudo systemctl enable docker
  38. # Step 7: 查看Docker服务信息
  39. echo -e "==> 查看Docker服务信息"
  40. docker info

1.7.2 Ubuntu 部署 Docker

  1. #!/bin/bash
  2. #Description: ubuntu1804系统安装docker-compose编排工具
  3. COLOR="echo -e \\033[1;31m"
  4. END="\033[m"
  5. DOCKER_VERSION="5:19.03.5~3-0~ubuntu-bionic"
  6. install_docker(){
  7. ${COLOR}"开始安装 Docker....."${END}
  8. sleep 1
  9. apt update
  10. apt -y install apt-transport-https ca-certificates curl software-properties-common
  11. curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add -
  12. add-apt-repository "deb [arch=amd64] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
  13. apt update
  14. ${COLOR}"Docker有以下版本:"${END}
  15. sleep 2
  16. apt-cache madison docker-ce
  17. ${COLOR}"5秒后即将安装: docker-"${DOCKER_VERSION}" 版本....."${END}
  18. ${COLOR}"如果想安装其它Docker版本,请按ctrl+c键退出,修改版本再执行"${END}
  19. sleep 5
  20. apt -y install docker-ce=${DOCKER_VERSION} docker-ce-cli=${DOCKER_VERSION}
  21. mkdir -p /etc/docker
  22. tee /etc/docker/daemon.json <<-'EOF'
  23. {
  24. "registry-mirrors": ["https://po13h3y1.mirror.aliyuncs.com","http://hub-mirror.c.163.com","https://mirror.ccs.tencentyun.com","http://f1361db2.m.daocloud.io"],
  25. "exec-opts": ["native.cgroupdriver=systemd"],
  26. "log-driver": "json-file",
  27. "log-opts": {
  28. "max-size": "100m"
  29. },
  30. "storage-driver": "overlay2"
  31. }
  32. EOF
  33. systemctl daemon-reload
  34. systemctl restart docker
  35. docker version && ${COLOR}"Docker 安装完成"${END} || ${COLOR}"Docker 安装失败"${END}
  36. }
  37. install_docker_compose(){
  38. ${COLOR}"开始安装 Docker compose....."${END}
  39. sleep 1
  40. curl -L https://github.com/docker/compose/releases/download/1.25.3/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
  41. chmod +x /usr/local/bin/docker-compose
  42. docker-compose --version && ${COLOR}"Docker Compose 安装完成"${END} || ${COLOR}"Docker compose 安装失败"${END}
  43. }
  44. dpkg -s docker-ce &> /dev/null && ${COLOR}"Docker已安装"${END} || install_docker
  45. docker-compose --version &> /dev/null && ${COLOR}"Docker Compose已安装"${END} || install_docker_compose

1.7.3 运行 hello-world 容器

  1. $ docker run hello-world
  2. Unable to find image 'hello-world:latest' locally
  3. latest: Pulling from library/hello-world
  4. 2db29710123e: Pull complete
  5. Digest: sha256:2498fce14358aa50ead0cc6c19990fc6ff866ce72aeb5546e1d59caac3d0d60f
  6. Status: Downloaded newer image for hello-world:latest
  7. Hello from Docker!
  8. This message shows that your installation appears to be working correctly.
  9. To generate this message, Docker took the following steps:
  10. 1. The Docker client contacted the Docker daemon.
  11. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
  12. (amd64)
  13. 3. The Docker daemon created a new container from that image which runs the
  14. executable that produces the output you are currently reading.
  15. 4. The Docker daemon streamed that output to the Docker client, which sent it
  16. to your terminal.
  17. To try something more ambitious, you can run an Ubuntu container with:
  18. $ docker run -it ubuntu bash
  19. Share images, automate workflows, and more with a free Docker ID:
  20. https://hub.docker.com/
  21. For more examples and ideas, visit:
  22. https://docs.docker.com/get-started/
  23. # Docker 环境搭建成功

2 Docker 镜像管理

2.1 什么是镜像

  • 一个分层存储的文件
  • 一个软件的环境
  • 一个镜像可以创建N个容器
  • 一种标准化的交付
  • 一个不包含Linux内核而又精简的Linux操作系统
  • 镜像不是一个单一的文件,而是有多层构成

2.2 镜像从哪里来?

Docker Hub是由Docker公司负责维护的公共注册中心,包含大量的容器镜像,Docker工具默认从这个公共镜像库下载镜像。

Docker Hub地址: https://hub.docker.com

1、Docker命令最后一个是指定镜像

2、默认镜像版本latest

3、分层下载

配置镜像加速器:

  1. mkdir -p /etc/docker
  2. tee /etc/docker/daemon.json <<-'EOF'
  3. {
  4. "registry-mirrors": ["https://po13h3y1.mirror.aliyuncs.com","http://hub-mirror.c.163.com","https://mirror.ccs.tencentyun.com","http://f1361db2.m.daocloud.io"],
  5. "exec-opts": ["native.cgroupdriver=systemd"],
  6. "log-driver": "json-file",
  7. "log-opts": {
  8. "max-size": "100m"
  9. },
  10. "storage-driver": "overlay2"
  11. }
  12. EOF

2.3 镜像与容器联系

01 Docker 基础部分 - 图12

当启动一个新的容器时,Docker会加载只读镜像,并在其之上添加一个读写层,即容器层。

  1. /var/lib/docker/containers/:容器元数据信息目录
  2. /var/lib/docker/overlay2/ :镜像目录

01 Docker 基础部分 - 图13

  1. rootfs:根文件系统
  2. bootfs:引导文件系统,引导程序和内核,容器是共享宿主机的内核

2.4 镜像常用管理命令

指令 描述
ls 列出镜像
build 构建镜像来自Dockerfile
history 查看镜像历史
inspect 显示一个或多个镜像详细信息
pull 从镜像仓库拉取镜像
push 推送一个镜像到镜像仓库
rm 移除一个或多个镜像
prune 移除没有被标记[ 虚悬镜像(dangling Image) ]或者没有被任何容器引用的镜像
tag 创建一个引用源镜像标记目标镜像
export 导出容器文件系统到tar归档文件
import 导入容器文件系统tar归档文件创建镜像
save 保存一个或多个镜像到一个tar归档文件
load 加载镜像来自tar归档或标准输入

:::color1 commit:将运行的容器直接提交为镜像。

export:将容器(运行或不运行)打包成tar包,再由import将tar包提交为镜像。

save:将镜像打包成tar包,再有load将tar包提交为镜像。

:::

  1. # 导出容器文件系统到tar归档文件
  2. $ docker run -it -d --name nginx-node1 nginx:latest
  3. $ docker export nginx-node1 -o nginx.tar
  4. $ tar -tf nginx.tar
  5. # 导入容器文件系统tar归档文件创建镜像
  6. $ docker import nginx.tar
  7. # 保存一个或多个镜像到一个tar归档文件
  8. $ docker save -o nginx.tar nginx:latest
  9. # 加载镜像来自tar归档或标准输入
  10. $ docker load -i nginx.tar
  11. # 将运行的容器直接提交为镜像
  12. ~ docker run -itd --name c1 centos /bin/bash
  13. ~ docker exec -it c1 /bin/bash
  14. $ rm -rf /etc/yum.repos.d/CentOS-Linux-*
  15. $ curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
  16. $ yum update ; yum install -y vim ; yum clean all
  17. $ vim --version
  18. VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Sep 22 2021 11:10:49)
  19. $ exit
  20. ~ docker commit -a "zhongzhiwei <935523993@qq.com>" -m "添加VIM软件" c1 kubesphere-centos:1.0
  21. ~ docker images kubesphere-centos:1.0
  22. REPOSITORY TAG IMAGE ID CREATED SIZE
  23. kubesphere-centos 1.0 7f36413d0ef3 4 seconds ago 271MB
  24. # 运行添加VIM的新镜像
  25. ~ docker run -it --name kc1 kubesphere-centos:1.0 /bin/bash
  26. $ vim --version
  27. VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Sep 22 2021 11:10:49)
  28. #########################################################################################################
  29. ~ docker run -itd --name u1 ubuntu /bin/bash
  30. ~ docker exec -it u1 /bin/bash
  31. $ apt update ; apt install -y vim
  32. $ vim --version
  33. VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Sep 22 2021 11:10:49)
  34. $ exit
  35. ~ docker commit -a "zhongzhiwei <935523993@qq.com>" -m "添加VIM软件" c1 kubesphere-ubuntu:1.0
  36. ~ docker images kubesphere-ubuntu:1.0
  37. REPOSITORY TAG IMAGE ID CREATED SIZE
  38. kubesphere-ubuntu 1.0 7f36413d0ef3 4 seconds ago 178MB
  39. # 运行添加VIM的新镜像
  40. ~ docker run -it --name ku1 kubesphere-ubuntu:1.0 /bin/bash
  41. $ vim --version
  42. VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Sep 22 2021 11:10:49)

2.5 镜像存储核心技术:联合文件系统 (UnionFS)

01 Docker 基础部分 - 图14

镜像怎么高效存储?

难道像虚拟机那样一个容器对应一个独立的镜像文件?这样对于密集型容器,磁盘占用率太大!

答:引入联合文件系统,将镜像多层文件联合挂载到容器文件系统

01 Docker 基础部分 - 图15

:::color1 容器层(读写):提供一个独立的运行环境

:::

2.6 镜像存储核心技术:写时复制 (COW)

01 Docker 基础部分 - 图16

了解联合文件系统后,我们知道,镜像是只读的,类似共享形式让多个容器使用,如果要在容器里修改文件,即镜像里的文件,那该怎么办呢?

答:引入写时复制(copy-on-write),需要修改文件操作时,会先从镜像里把要写的文件复制到自己的文件系统中进行修改[ 该逻辑在用户视觉层面是屏蔽的 ]

  1. # 默认挂载宿主机的三个文件
  2. hostname --hostname
  3. hosts --dns
  4. resolv.conf --add-host

:::color1 读文件:容器层 → 镜像层

修改文件:容器层 → 镜像层

Storage Driver: overlay2 ( aufs 、overlay、devicemapper )

01 Docker 基础部分 - 图17

:::

优化建议

使用SSD固态硬盘

使用卷作为频繁读写文件的工作目录,绕过存储驱动,减少抽象的开销

2.7 Docker 打包成镜像

docker commit 将容器提交成镜像

  • docker export 将容器打包成 tar 包

docker export -o .tar

根据容器的大小,打包的效率也会随之变化

  • docker import 将 tar 包提交为镜像

docker import .tar :

根据Tar包的大小,提交镜像的效率也会随之变化

  • docker save 将镜像打包成 tar 包

docker save : -o .tar

根据镜像的大小,打包的效率也会随之变化

  • docker load 将 tar 包提交为镜像

docker load -i .tar

根据Tar包的大小,提交镜像的效率也会随之变化

以及使用 Dockerfile 编写镜像脚本

docker build -t ImageName:[Tag] -f Dockerfile .

2.8 容器文件存储解析

2.8.1 容器运行时的 UpperDir 目录结构

  1. #~ touch /data/docker/overlay2/<UpperDir>/container_upperdir.txt
  2. ~ echo "Welcome to container_upperdir" >> /data/docker/overlay2/<UpperDir>/container_upperdir.txt
  3. #在进入到容器操作查看
  4. ~ docker exec -it jdk8-node01 /bin/bash
  5. ~ cat /container_upperdir.txt

2.8.2 Work目录

work目录用于联合挂载指定的工作目录,在overlay 把文件挂载到 upperdir后, work内容会被清空,且在使用过程中(为空)其内容用户不可见。

2.8.3 用户视角层 Merged

最后给用户展示的层,一般看到为一个完整的操作系统文件系统结构

  1. ~ ls -l /data/docker/overlay2/<Merged>/

2.8.4 Lower 层

#Lower 包括两个层:
  • a:系统的 init (docker 容器启动后自动挂载)
  • b:容器的镜像层
  1. ~ cat /data/docker/overlay2/<LowerDir>-init/lower
  2. l/BYHA4RECHA4CPGWNIZLPAN7HCD:l/JGA2WPDQWQI3IKC3JSFPHFBMDA:
  3. #init层 :/ 容器镜像层

:::color1 docker 容器管理工具即做了资源隔离,挂载,分配一个网段。

:::

2.8.4.1 查看init层地址指向

容器在启动的过程中, Lower 会自动挂载init的一些文件

  1. ~ ls -l /data/docker/overlay2/<LowerDir>-init/diff/etc/
  2. total 0
  3. -rwxr-xr-x 1 root root 0 Jun 28 21:15 hostname
  4. -rwxr-xr-x 1 root root 0 Jun 28 21:15 hosts
  5. lrwxrwxrwx 1 root root 12 Jun 28 21:15 mtab -> /proc/mounts
  6. -rwxr-xr-x 1 root root 0 Jun 28 21:15 resolv.conf

:::color1 需求:同一个域名,在公网解析成另一个公网IP地址,在内网解析成另一个内网IP地址。

在修改 容器的hosts文件的时候,需要将整个镜像全部构建完毕后,在启动脚本中修改 hosts 文件,需要在最后一个步骤才能进行修改,因为会在容器挂载的时候覆盖掉该文件。

在将来绑定 hosts 的时候需要知道在 init 层进行绑定

:::

2.8.4.2 init层主要内容是什么?

init 层是以一个uuid+-init结尾表示,放在只读层(Lower)和读写层(upperdir)之间,作用只是存放 /etc/hosts、/etc/resolv.conf 等文件

2.8.4.3 为什么需要init层?

1)容器在启动以后, 默认情况下lower层是不能够修改内容的, 但是用户有需求需要修改主机名与域名地址, 那么就需要添加init层中的文件(hostname, resolv.conf), 用于解决此类问题。

2) 修改的内容只对当前的容器生效,而在docker commit提交为镜像时候,并不会将init层提交。

3) init 文件存放的目录为/var/lib/docker/overlay2//diff

2.8.4.4 查看init层文件

hostname与resolv.conf 全部为空文件, 在系统启动以后由系统写入。

  1. ~ ls -l /data/docker/overlay2/<LowerDir>-init/diff/etc/
  2. total 0
  3. -rwxr-xr-x 1 root root 0 Jun 28 21:15 hostname
  4. -rwxr-xr-x 1 root root 0 Jun 28 21:15 hosts
  5. lrwxrwxrwx 1 root root 12 Jun 28 21:15 mtab -> /proc/mounts
  6. -rwxr-xr-x 1 root root 0 Jun 28 21:15 resolv.conf

2.8.5 总结

1) 镜像所挂载的目录层为 Lower 层,然后通过 Merged 展示所有的文件目录与文件。用户写入的所有文件都是在 UpperDir 目录,并且会在 UpperDir 建立于 Merged 层展示的文件目录结构, 所以用户就可以看到写入的文件。并且底层的镜像是不能被修改(如果挂载目录为 UpperDir,则可以修改源镜像)。

2) 在下次重新启动已经停止的容器的时候, 如果容器的 ID 没有发生改变, 那么所写入的文件是存在物理系统中的; 反之就会是一个新的容器,之前手工创建的文件是不存在的。

3) 基于容器创建的镜像,就相当于容器的快照, 可以删除原来的容器, 但是不能删除原来的镜像

4) 基于镜像创建的镜像,原来的镜像就是新镜像的 low 层 (build), tag 则是没有区别

5) 容器启动以后,镜像就存在于容器的 lower 层,所有的写入都是在 upper

3 Docker 容器管理

3.1 创建容器常用选项

  1. # 查看创建容器的帮助文档
  2. docker run --help

命令格式:docker run [OPTIONS] IMAGE [COMMAND] [ARGS……]

选项 描述
-i, —interactive 交互式
-t , —tty 分配一个伪终端
-d, —detachr 运行容器到后台
-e,—env 设置环境变量
-p,—publish list 发布容器端口到主机
-P,—publish-all 发布容器所有EXPOSE的端口到宿主机随机端口
—name string 指定容器名称
-h, —hostname 设置容器主机名
—ip string 指定容器IP,只能用于自定义网络
—network 连接容器到一个网络
—mount mount(新方式) 将文件系统附加到容器
-v,—volume list 绑定挂载一个卷
—restart string 容器退出时重启策略,默认no,可选值:[always l on-failure]
  1. # Step 1: 进入到容器的系统内部
  2. # 启动一个Ubuntu容器,操作系统类容器需要有进程夯筑容器运行
  3. $ docker run -it -d --name ubuntu-node ubuntu /bin/bash
  4. $ docker exec -it ubuntu-node /bin/bash | docker attach ubuntu-node
  5. # 查看容器的版本(ubuntu)
  6. root@9650093ce0c2:/# cat /etc/os-release
  7. NAME="Ubuntu"
  8. VERSION="20.04.3 LTS (Focal Fossa)"
  9. ID=ubuntu
  10. ID_LIKE=debian
  11. PRETTY_NAME="Ubuntu 20.04.3 LTS"
  12. VERSION_ID="20.04"
  13. HOME_URL="https://www.ubuntu.com/"
  14. SUPPORT_URL="https://help.ubuntu.com/"
  15. BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
  16. PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
  17. VERSION_CODENAME=focal
  18. UBUNTU_CODENAME=focal
  19. # 查看容器的进程
  20. root@9650093ce0c2:/# ps
  21. PID TTY TIME CMD
  22. 27 pts/3 00:00:00 bash
  23. 35 pts/3 00:00:00 ps
  24. # Step 2: 启动Nginx容器,并暴露80端口映射到宿主机的8080端口
  25. docker run -d --name nginx-node -p 8080:80 --restart=always nginx
  26. sudo curl localhost:8080
  27. # Step 3: 测试多个容器参数
  28. $ docker run -it -d -e env=prod --name container-nginx \
  29. -p 8088:80 --restart=always -h nginx-node nginx
  30. # 查看最新创建的容器信息
  31. $ docker ps -l
  32. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  33. 1dcbec1b129c nginx "/docker-entrypoint.…" 6 seconds ago Up 5 seconds 0.0.0.0:8088->80/tcp, :::8088->80/tcp container-nginx
  34. $ sudo curl localhost:8088
  35. # 进入到container-nginx容器中
  36. $ docker exec -it container-nginx /bin/bash # docker container exec -it container-nginx /bin/bash
  37. root@nginx-node:/# hostname
  38. nginx-node
  39. root@nginx-node:/# echo $env
  40. prod
  41. root@nginx-node:/# echo "Hello Nginx Container" > /usr/share/nginx/html/index.html
  42. root@nginx-node:/# curl localhost
  43. Hello Nginx Container
  44. root@nginx-node:/# exit
  45. # Step 4: 重启Docker服务后该容器会自动启动(--restart=always)
  46. $ systemctl restart docker
  47. $ docker ps
  48. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  49. 1dcbec1b129c nginx "/docker-entrypoint.…" 4 minutes ago Up 9 seconds 0.0.0.0:8088->80/tcp, :::8088->80/tcp container-nginx
  50. $ docker top container-nginx
  51. UID PID PPID C STIME TTY TIME CMD
  52. root 17541 17512 0 02:52 ? 00:00:00 nginx: master process nginx -g daemon off;
  53. systemd+ 17595 17541 0 02:52 ? 00:00:00 nginx: worker process
  54. systemd+ 17596 17541 0 02:52 ? 00:00:00 nginx: worker process
  55. # Step 5: 查看容器的详细信息显示
  56. $ docker inspect container-nginx
  57. # Step 6: 查看容器的进程
  58. $ docker run -itd --name centos-node1 centos:centos7.9.2009 /bin/bash
  59. $ docker top centos-node1
  60. UID PID PPID C STIME TTY TIME CMD
  61. root 17393 17357 3 02:51 ? 00:00:00 /bin/bash

:::color1 Docker 容器需要用阻塞进程夯筑进程,使得Docker 容器持续运行!

:::

3.2 容器资源限制

默认创建的容器使用宿主机所有资源。

命令格式:docker run [OPTIONS] IMAGE [COMMAND] [ARGS……]

选项 描述
-m,—memory 容器可以使用的最大内存量
—memory-swap 允许交换到磁盘的内存量
—memory-swappiness=<0-100> 容器使用SWAP分区交换的百分比(0-100,默认为-1)
—oom-kill-disable 禁用OOM Killer
—cpus 可以使用的CPU数量
—cpuset-cpus 限制容器使用特定的CPU核心,如(0-3 , 0 , 1)
—cpu-shares CPU共享(相对权重)

范例:创建容器资源限制

  1. # -m="300m" 使用300M内存
  2. # --cpus="1" 使用一颗CPU
  3. $ docker run -it -d --name ubuntu-container -m="300m" --cpus="1" ubuntu /bin/bash
  4. # 查看容器的资源
  5. $ docker stats --no-stream ubuntu-container
  6. CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
  7. d74184890bae ubuntu-container 0.00% 540KiB / 300MiB 0.18% 656B / 0B 0B / 0B 1

示例:

  1. # 内存限额
  2. # 允许容器最多使用500M内存和600M的Swarp,并且禁用OOM Killer
  3. docker run -it -d --name nginx-limit1 --memory="500m" --memory-swap="600m" --oom-kill-disable nginx
  4. # CPU限额
  5. # 允许容器最多使用一个半的CPU
  6. docker run -it -d --name nginx-cpu1 --cpus="1.5" nginx
  7. # 允许容器最多使用50%的CPU
  8. docker run -it -d --name nginx-cpu2 --cpus=".5" nginx

:::color1

linux oom机制(out of memory)
linux内核根据应用程序的需求来分配内存,但通常来说应用程序使用不完,为了提高性能,会把没用完的这部分留作他用,每个进程都能够使用。
但是内核直接回收会比较麻烦,所以选择了一种过度分配机制,间接利用这部分没用完的内存。但是如果大多数应用程序都把自己的内存消耗完了,会导致所有内存使用数加起来超过了本来有的内存,包括swap。这是就必须杀掉一些进程来腾出内存空间,保证系统正常运行。 杀掉进程的过程可以参考linux/mm/oom_kill.c 大致为给每一个进程打分,得分最高的被oom-killer杀掉 可以通过修改 /proc/sys/vm/panic_on_oom 文件来调整oom-killer的行为,禁止杀掉进程,但这会触发kernal panic(重要!!!如果遇到panic 也可以考虑往这方面排错查看)
当该文件为1时,直接panic;为0时,将通过oom-killer杀掉部分进程(默认值为0)
也可使用此命令,效果相同 <font style="color:rgb(51, 51, 51);">sysctl -w vm.panic_on_oom=1 && sysctl -p</font> 也可以通过修改一些内核参数来避免系统一直不停的杀进程。 也可以不允许过度分配内存,这样也就不会出现oom的问题(非常不推荐,内存浪费严重) sysctl -w vm.overcommit_memory=2 三个取值 0 1 2 默认值为0
0表示当用户请求更多内存时,内核尝试估算剩余的可用内存,计算方式为sqp总量加slab中可释放的总量+NR_FILE_PAGES总量 如果申请的内存超过这个数值,再进行一次计算(这里不懂),还是超过就分配失败
1表示允许超量使用内存,直到用完为止,主要用于科学计算
2表示绝不过量使用内存,即整个系统内存地址空间不能超过sqp分区+50%的ram值 查看进程的oom_score /proc/PID/oom_score中 当得分为0时禁止杀掉该进程
另外两个文件 oom_score_adj 惩罚机制,计算得分时会额外计算这个文件中的数值,越大计算出来的得分就越大 取值范围正副1000 默认值0
oom_adj 取值范围-17-15 -17表示永不杀死这个进程 默认值0

:::

3.3 容器资源配额扩容

  1. docker update # 在线更新容器配置
  2. $ docker update --help
  3. Usage: docker update [OPTIONS] CONTAINER [CONTAINER...]
  4. Update configuration of one or more containers
  5. Options:
  6. --blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
  7. --cpu-period int Limit CPU CFS (Completely Fair Scheduler) period 限制CPU CFS(完全公平调度程序)周期
  8. --cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota 限制CPU CFS(完全公平调度程序)配额
  9. --cpu-rt-period int Limit the CPU real-time period in microseconds CPU实时周期限制在微秒内
  10. --cpu-rt-runtime int Limit the CPU real-time runtime in microseconds CPU实时运行时限制在微秒内
  11. -c, --cpu-shares int CPU shares (relative weight) CPU份额(相对权重)
  12. --cpus decimal Number of CPUs cpu个数
  13. --cpuset-cpus string CPUs in which to allow execution (0-3, 0,1) 允许执行的cpu (0- 3,0,1)
  14. --cpuset-mems string MEMs in which to allow execution (0-3, 0,1) 允许执行(0- 3,0,1)的MEMs
  15. --kernel-memory bytes Kernel memory limit 内核内存限制
  16. -m, --memory bytes Memory limit 内存限制
  17. --memory-reservation bytes Memory soft limit 内存软限制
  18. --memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap 交换限制等于内存加交换:'-1'以启用无限交换
  19. --pids-limit int Tune container pids limit (set -1 for unlimited) 调优容器pid限制(设置-1表示无限制)
  20. --restart string Restart policy to apply when a container exits

3.4 管理容器常用命令

命令格式:docker container COMMAND

选项 描述
ls 列出容器
inspect 查看一个或多个容器详细信息
exec 在运行容器中执行命令
commit 创建—个新镜像来自—个容器
cp 拷贝文件/文件夹到一个容器
logs 获取一个容器日志
port 列出或指定容器端口映射
top 显示一个容器运行的进程
stats 显示容器资源使用统计
stop / start / restart 停止/启动一个或多个容器
rm 删除─个或多个容器
prune 移除已停止的容器

范例:常用管理命令

  1. # Step 1: 列出当前DockerHost容器
  2. $ docker ps
  3. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  4. d74184890bae ubuntu "/bin/bash" 3 minutes ago Up 3 minutes ubuntu-container
  5. 1dcbec1b129c nginx "/docker-entrypoint.…" 14 minutes ago Up 10 minutes 0.0.0.0:8088->80/tcp, :::8088->80/tcp container-nginx
  6. # 列出当前DockerHost所有容器
  7. $ docker ps -a
  8. # 列出最新创建的容器
  9. $ docker ps -l
  10. # Step 2: 查看容器的详细信息显示
  11. $ docker inspect [Container_ID|Container_Name]
  12. # Step 3: 进入到容器或者直接在DockerHost执行容器命令
  13. $ docker exec -it ubuntu-container /bin/bash
  14. $ docker exec ubuntu-container cat /etc/os-release
  15. NAME="Ubuntu"
  16. VERSION="20.04.3 LTS (Focal Fossa)"
  17. ID=ubuntu
  18. ID_LIKE=debian
  19. PRETTY_NAME="Ubuntu 20.04.3 LTS"
  20. VERSION_ID="20.04"
  21. HOME_URL="https://www.ubuntu.com/"
  22. SUPPORT_URL="https://help.ubuntu.com/"
  23. BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
  24. PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
  25. VERSION_CODENAME=focal
  26. UBUNTU_CODENAME=focal
  27. # Step 4: 查看容器日志
  28. docker logs container-nginx
  29. # Step 5: 将容器提交成一个镜像
  30. $ docker exec -it container-nginx /bin/bash
  31. root@nginx-node:/# echo "Hello Nginx Container" > /usr/share/nginx/html/index.html
  32. root@nginx-node:/# exit
  33. $ docker commit -a "zhongzw <zhongzhiwei@kubesphere.com>" -m "修改nginx默认页面" container-nginx mynginx:1.1.0
  34. $ docker images
  35. REPOSITORY TAG IMAGE ID CREATED SIZE
  36. mynginx 1.1.0 20cad473dbf9 13 seconds ago 141MB
  37. $ docker image history mynginx:1.1.0
  38. IMAGE CREATED CREATED BY SIZE COMMENT
  39. 20cad473dbf9 27 seconds ago nginx -g daemon off; 1.12kB 修改nginx默认页面
  40. 605c77e624dd 8 months ago /bin/sh -c #(nop) CMD ["nginx" "-g" "daemon… 0B
  41. <missing> 8 months ago /bin/sh -c #(nop) STOPSIGNAL SIGQUIT 0B
  42. <missing> 8 months ago /bin/sh -c #(nop) EXPOSE 80 0B
  43. <missing> 8 months ago /bin/sh -c #(nop) ENTRYPOINT ["/docker-entr… 0B
  44. <missing> 8 months ago /bin/sh -c #(nop) COPY file:09a214a3e07c919a… 4.61kB
  45. <missing> 8 months ago /bin/sh -c #(nop) COPY file:0fd5fca330dcd6a7… 1.04kB
  46. <missing> 8 months ago /bin/sh -c #(nop) COPY file:0b866ff3fc1ef5b0… 1.96kB
  47. <missing> 8 months ago /bin/sh -c #(nop) COPY file:65504f71f5855ca0… 1.2kB
  48. <missing> 8 months ago /bin/sh -c set -x && addgroup --system -… 61.1MB
  49. <missing> 8 months ago /bin/sh -c #(nop) ENV PKG_RELEASE=1~bullseye 0B
  50. <missing> 8 months ago /bin/sh -c #(nop) ENV NJS_VERSION=0.7.1 0B
  51. <missing> 8 months ago /bin/sh -c #(nop) ENV NGINX_VERSION=1.21.5 0B
  52. <missing> 9 months ago /bin/sh -c #(nop) LABEL maintainer=NGINX Do… 0B
  53. <missing> 9 months ago /bin/sh -c #(nop) CMD ["bash"] 0B
  54. <missing> 9 months ago /bin/sh -c #(nop) ADD file:09675d11695f65c55… 80.4MB
  55. # 将新镜像运行成容器
  56. docker run -it -d --name mynginx-container --restart=always -p 8888:80 mynginx:1.1.0
  57. sudo curl localhost:8888
  58. # Step 5: 容器与宿主机之间的文件拷贝
  59. Usage: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
  60. docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
  61. $ echo "hello docker" > docker.txt
  62. $ docker cp docker.txt ubuntu-container:/tmp
  63. $ docker exec ubuntu-container cat /tmp/docker.txt
  64. hello docker
  65. $ docker cp ubuntu-container:/etc/passwd /tmp
  66. $ cat /tmp/passwd
  67. # Step 7: 查看容器暴露的端口
  68. $ docker port mynginx-container
  69. 80/tcp -> 0.0.0.0:8888
  70. 80/tcp -> :::8888
  71. # Step 8: 容器运行的进程
  72. $ docker top mynginx-container
  73. # Step 9: 查看容器的资源利用率
  74. $ docker stats mynginx-container
  75. $ docker stats --no-stream mynginx-container
  76. # Step 10: 删除容器
  77. $ docker rm -f mynginx-container
  78. # 只查看容器的ID
  79. $ docker ps -q
  80. # 删除所有容器(-f 强制删除;-a 全部容器)
  81. $ docker rm -f $(docker ps -qa)
  82. # Step 11: 移除已经停止的容器
  83. $ docker container prune
  84. # 容器名称是不能重复的

3.5 容器实现核心技术: Namespace

在容器化中,一台物理计算机可以运行多个不同操作系统,那就需要解决”隔离性”,彼此感知不到对方存在,有问题互不影响。

Linux内核从<font style="color:#E8323C;">2.4.19</font>版本开始引入了namespace概念,其目的是将特定的全局系统资源通过抽象方法使得namespace中的进程看起来拥有自己隔离的资源。Docker就是借助这个机制实现了容器资源隔离。 Linux的Namespace机制提供了6种不同命名空间: + IPC:隔离进程间通信 + MOUNT:隔离文件系统挂载点 + NET:隔离网络协议栈 + PID:隔离进程号,进程命名空间是一个父子结构,子空间对父空间可见 + USER:隔离用户 + UTS:隔离主机名和域名 bash # $$ 显示当前进程号 $ ll /proc/$$/ns total 0 lrwxrwxrwx 1 root root 0 Nov 30 13:17 ipc -> ipc:[4026531839] lrwxrwxrwx 1 root root 0 Nov 30 13:17 mnt -> mnt:[4026531840] lrwxrwxrwx 1 root root 0 Nov 30 13:17 net -> net:[4026531956] lrwxrwxrwx 1 root root 0 Nov 30 13:17 pid -> pid:[4026531836] lrwxrwxrwx 1 root root 0 Nov 30 13:17 user -> user:[4026531837] lrwxrwxrwx 1 root root 0 Nov 30 13:17 uts -> uts:[4026531838] # 创建Busybox容器 $ docker run -it -d --name busybox-node1 busybox /bin/sh # 隔离网络协议栈 / # ip addr 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue 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 588: eth0@if589: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue link/ether 02:42:ac:11:00:0f brd ff:ff:ff:ff:ff:ff inet 172.17.0.15/16 brd 172.17.255.255 scope global eth0 valid_lft forever preferred_lft forever # 隔离进程号,进程命名空间是一个父子结构,子空间对父空间可见 / # ps -ef PID USER TIME COMMAND 1 root 0:00 /bin/sh 7 root 0:00 /bin/sh 14 root 0:00 ps -ef # 隔离用户 / # cat /etc/passwd root:x:0:0:root:/root:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/false bin:x:2:2:bin:/bin:/bin/false sys:x:3:3:sys:/dev:/bin/false sync:x:4:100:sync:/bin:/bin/sync mail:x:8:8:mail:/var/spool/mail:/bin/false www-data:x:33:33:www-data:/var/www:/bin/false operator:x:37:37:Operator:/var:/bin/false nobody:x:65534:65534:nobody:/home:/bin/false # 隔离主机名和域名 / # hostname 264a7a3e091d $ docker run -it -d --name busybox-node2 busybox /bin/sh / # ip addr 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue 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 590: eth0@if591: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue link/ether 02:42:ac:11:00:10 brd ff:ff:ff:ff:ff:ff inet 172.17.0.16/16 brd 172.17.255.255 scope global eth0 valid_lft forever preferred_lft forever ## 3.6 容器实现核心技术: CGroups Docker利用namespace实现了容器之间资源隔离,但是namespace不能对容器资源限制,比如CPU、内存。 如果某一个容器属于CPU密集型任务,那么会影响其他容器使用CPU,导致多个容器相互影响并且抢占资源。 如何对多个容器的资源使用进行限制就成了容器化的主要问题。 答:引入Control Groups(简称CGroups),限制容器资源 CGroups:所有的任务就是运行在系统中的一个进程,而CGroups以某种标准讲一组进程为目标进行资源分配和控制。例如CPU、内存、带宽等,并且可以<font style="color:#E8323C;">动态配置</font>

CGroups主要功能:

  • 限制进程组使用的资源数量 ( Resource limitation ) : 可以为进程组设定资源使用上限,例如内存
  • 进程组优先级控制( Prioritization ) : 可以为进程组分配特定CPU、磁盘IO吞吐量
  • 记录进程组使用的资源数量 ( Accounting ) : 例如使用记录某个进程组使用的CPU时间
  • 进程组控制 ( Control ) : 可以将进程组挂起和恢复

ls /sys/fs/cgroup/ -l查看cgroups可控制的资源:

  • blkio : 对快设备的IO进行限制。
  • cpu : 限制CPU时间片的分配,与cpuacct挂载同一目录。
  • cpuacct : 生成cgroup中的任务占用CPU资源的报告,与cpu挂载同一目录。
  • cpuset : 给cgroup中的任务分配独立的CPU(多核处理器)和内存节点。
  • devices : 允许或者拒绝cgroup 中的任务访问设备。
  • freezer : 暂停/恢复cgroup 中的任务。
  • hugetlb : 限制使用的内存页数量。
  • memory : 对cgroup中任务的可用内存进行限制,并自动生成资源占用报告。
  • net cls : 使用等级识别符(classid)标记网络数据包,这让 Linux流量控制程序(tc)可以识别来自特定从cgroup任务的数据包,并进行网络限制。
  • net_prio : 允许基于cgroup设置网络流量的优先级。
  • perf_event : 允许使用perf工具来监控cgroup。
  • pids:限制任务的数量。

容器实际资源限制位置:

/sys/fs/cgroup/<资源名>/docker/<容器ID>

3.7 Docker核心组件之间关系

01 Docker 基础部分 - 图18

Docker Daemon:Docker守护进程,负责与Docker Clinet交互,并管理镜像、容器。

Containerd:是一个简单的守护进程[ 为了兼容OCI标准 ],向上给Docker Daemon提供接口,向下通过containerd-shim结合runC管理容器。

runC:一个命令行工具,它根据OCI标准来创建和运行容器[ 由lib-Container剥离出来 ]。

01 Docker 基础部分 - 图19

总结:

:::color1 Namespace

命名空间,Linux内核提供的一种对进程资源隔离的机制,例如进程、网络、挂载点等资源。

CGroups

控制组,Linux内核提供的一种对进程组限制资源的机制;例如CPU、内存等资源。

UnionFS

联合文件系统,支持将不同位置的目录挂载到同一虚拟文件系统,形成一种分层的模型。

:::

4 Docker 容器数据持久化

4.1 将数据从宿主机挂载到容器中的三种方式

Docker提供三种方式将数据从宿主机挂载到容器中:

  • volumes:Docker管理宿主机文件系统的一部分(/var/lib/docker/volumes)。保存数据的最佳方式。
  • bind mounts:将宿主机上的任意位置的文件或者目录挂载到容器中。
  • tmpfs:挂载存储在主机系统的内存中,而不会写入主机的文件系统。如果不希望将数据持久存储在任何位置,可以使用tmpfs,同时避免写入容器可写层提高性能。[ 使用场景很少 ]

01 Docker 基础部分 - 图20

4.2 Volume

管理卷:

  1. $ docker volume create nginx-vol
  2. $ docker volume ls
  3. $ docker volume inspect nginx-vol
  4. [
  5. {
  6. "CreatedAt": "2022-11-30T14:16:36+08:00",
  7. "Driver": "local",
  8. "Labels": {},
  9. "Mountpoint": "/var/lib/docker/volumes/nginx-vol/_data",
  10. "Name": "nginx-vol",
  11. "Options": {},
  12. "Scope": "local"
  13. }
  14. ]

用卷创建一个容器:

  1. $ docker run -d --name=nginx-test --mount src=nginx-vol,dst=/usr/share/nginx/html nginx
  2. $ docker run -d --name=nginx-test -v nginx-vol:/usr/share/nginx/html nginx
  3. # 使用匿名卷
  4. $ docker run -d --name nginx-volume -v /usr/share/nginx/html/ nginx

清理:

  1. $ docker stop nginx-test
  2. $ docker rm nginx-test
  3. $ docker volume rm nginx-vol

注意:

  1. 如果没有指定卷,自动创建。

4.3 Bind Mounts

用卷创建一个容器:

  1. $ docker run -d --name=nginx-test --mount type=bind,src=/app/wwwroot,dst=/usr/share/nginx/html nginx
  2. $ docker run -d --name=nginx-test -v /app/wwwroot:/usr/share/nginx/html nginx

验证绑定:

  1. $ docker inspect nginx-test

清理:

  1. $ docker stop nginx-test
  2. $ docker rm nginx-test

注意:

  1. 如果源文件/目录没有存在如果挂载目标在容器中非空目录,则该目录现有内容将被隐藏。
  2. 不会自动创建,会抛出一个错误。[ 新版的Docker会自动创建 ]

01 Docker 基础部分 - 图21

5 Docker 容器网络

5.1 四种网络模式

01 Docker 基础部分 - 图22

  • bridge

—net=bridge

默认网络,Docker启动后创建一个docker0网桥,默认创建的容器也是添加到这个网桥中。也可以自定义网络,相比默认的具备内部DNS发现,可以通过容器名容器之间网络通信。

  • host

—net=host

容器不会获得一个独立的network namespace,而是与宿主机共用一个。这就意味着容器不会有自己的网卡信息,而是使用宿主机的。容器除了网络,其他都是隔离的。

  • none

—net=none

获取独立的network namespace,但不为容器进行任何网络配置,需要我们手动配置。

  • container

—net=container:Name/ID

与指定的容器使用同一个network namespace,具有同样的网络配置信息,两个容器除了网络,其他都还是隔离的。

网络模式 配置 说明
host —network host 容器和宿主机共享 Network namespace
container —network container:NAME_OR_ID 容器和另外一个容器共享 Network namespace
none —network none 容器有独立的 Network namespace,但并没有对其进行任何网络设置,如分配 veth pair 和网桥连接,配置 IP 等
bridge —network bridge 默认模式

01 Docker 基础部分 - 图23

  1. $ yum install -y bridge-utils
  2. $ brctl show
  3. bridge name bridge id STP enabled interfaces
  4. docker0 8000.0242c776c496 no vethfff7deb
  5. $ docker ps
  6. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  7. 4c85101b19d3 centos:centos7.9.2009 "/bin/bash" 6 hours ago Up 6 hours centos-node1
  8. # 创建Docker测试网络
  9. $ docker network create test_network
  10. # 使用该测试网络创建容器
  11. $ docker run -it -d --name nginx-node1 --network test_network nginx
  12. $ docker inspect -f "{{.NetworkSettings.Networks.test_network.IPAddress}}" nginx-node1
  13. 172.18.0.2
  14. # 默认使用bridge网络(IP地址可以通信,不能使用主机名通信)
  15. $ docker run -it -d --name busybox-node1 --hostname busybox-node1 busybox
  16. $ docker run -it -d --name busybox-node2 --hostname busybox-node2 busybox
  17. $ docker exec -it busybox-node1 ip addr
  18. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  19. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  20. inet 127.0.0.1/8 scope host lo
  21. valid_lft forever preferred_lft forever
  22. 22: eth0@if23: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  23. link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
  24. inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
  25. valid_lft forever preferred_lft forever
  26. $ docker exec -it busybox-node2 ip addr
  27. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  28. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  29. inet 127.0.0.1/8 scope host lo
  30. valid_lft forever preferred_lft forever
  31. 24: eth0@if25: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  32. link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
  33. inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
  34. valid_lft forever preferred_lft forever
  35. # IP地址可以通信,主机名无法通信
  36. $ docker exec -it busybox-node1 ping -c 1 -W 1 172.17.0.3
  37. PING 172.17.0.3 (172.17.0.3): 56 data bytes
  38. 64 bytes from 172.17.0.3: seq=0 ttl=64 time=0.300 ms
  39. --- 172.17.0.3 ping statistics ---
  40. 1 packets transmitted, 1 packets received, 0% packet loss
  41. $ docker exec -it busybox-node1 ping -c 1 -W 1 busybox-node2
  42. ping: bad address 'busybox-node2'
  43. # 使用自定义网络(桥接)内部会有DNS解析,做了IP地址和主机名的绑定关系

范例:自定义网络

  1. $ docker run -it -d --name busybox-node-test1 --hostname busybox-node-test1 --network test_network busybox
  2. $ docker run -it -d --name busybox-node-test2 --hostname busybox-node-test2 --network test_network busybox
  3. $ docker exec -it busybox-node-test1 ip addr
  4. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  5. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  6. inet 127.0.0.1/8 scope host lo
  7. valid_lft forever preferred_lft forever
  8. 26: eth0@if27: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  9. link/ether 02:42:ac:12:00:03 brd ff:ff:ff:ff:ff:ff
  10. inet 172.18.0.3/16 brd 172.18.255.255 scope global eth0
  11. valid_lft forever preferred_lft forever
  12. $ docker exec -it busybox-node-test2 ip addr
  13. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  14. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  15. inet 127.0.0.1/8 scope host lo
  16. valid_lft forever preferred_lft forever
  17. 28: eth0@if29: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  18. link/ether 02:42:ac:12:00:04 brd ff:ff:ff:ff:ff:ff
  19. inet 172.18.0.4/16 brd 172.18.255.255 scope global eth0
  20. valid_lft forever preferred_lft forever
  21. $ docker exec -it busybox-node-test2 ping -c 1 -W 1 172.18.0.4
  22. PING 172.18.0.4 (172.18.0.4): 56 data bytes
  23. 64 bytes from 172.18.0.4: seq=0 ttl=64 time=0.132 ms
  24. --- 172.18.0.4 ping statistics ---
  25. 1 packets transmitted, 1 packets received, 0% packet loss
  26. round-trip min/avg/max = 0.132/0.132/0.132 ms
  27. $ docker exec -it busybox-node-test2 ping -c 1 -W 1 busybox-node-test2
  28. PING busybox-node-test2 (172.18.0.4): 56 data bytes
  29. 64 bytes from 172.18.0.4: seq=0 ttl=64 time=0.104 ms
  30. --- busybox-node-test2 ping statistics ---
  31. 1 packets transmitted, 1 packets received, 0% packet loss
  32. round-trip min/avg/max = 0.104/0.104/0.104 ms

范例:使用 host 网络模式

  1. $ docker run -it --network host --name busybox-host --hostname busybox-host busybox
  2. # 共享宿主机的网络命名空间
  3. / # ifconfig
  4. docker0 Link encap:Ethernet HWaddr 02:42:C7:76:C4:96
  5. inet addr:172.17.0.1 Bcast:172.17.255.255 Mask:255.255.0.0
  6. inet6 addr: fe80::42:c7ff:fe76:c496/64 Scope:Link
  7. UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
  8. RX packets:9 errors:0 dropped:0 overruns:0 frame:0
  9. TX packets:17 errors:0 dropped:0 overruns:0 carrier:0
  10. collisions:0 txqueuelen:0
  11. RX bytes:516 (516.0 B) TX bytes:2016 (1.9 KiB)
  12. eth0 Link encap:Ethernet HWaddr 00:0C:29:0F:DD:0C
  13. inet addr:10.0.0.100 Bcast:10.0.0.255 Mask:255.255.255.0
  14. inet6 addr: fe80::20c:29ff:fe0f:dd0c/64 Scope:Link
  15. UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
  16. RX packets:119699 errors:0 dropped:0 overruns:0 frame:0
  17. TX packets:46469 errors:0 dropped:0 overruns:0 carrier:0
  18. collisions:0 txqueuelen:1000
  19. RX bytes:161358423 (153.8 MiB) TX bytes:3476608 (3.3 MiB)
  20. lo Link encap:Local Loopback
  21. inet addr:127.0.0.1 Mask:255.0.0.0
  22. inet6 addr: ::1/128 Scope:Host
  23. UP LOOPBACK RUNNING MTU:65536 Metric:1
  24. RX packets:995 errors:0 dropped:0 overruns:0 frame:0
  25. TX packets:995 errors:0 dropped:0 overruns:0 carrier:0
  26. collisions:0 txqueuelen:1000
  27. RX bytes:91025 (88.8 KiB) TX bytes:91025 (88.8 KiB)
  28. # ...省略部分输出...

范例:使用 Container 网络

  1. $ docker run -it --network container:busybox-node1 -d --name busybox-container1 busybox
  2. $ docker exec busybox-node1 ip addr
  3. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  4. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  5. inet 127.0.0.1/8 scope host lo
  6. valid_lft forever preferred_lft forever
  7. 22: eth0@if23: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  8. link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
  9. inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
  10. valid_lft forever preferred_lft forever
  11. $ docker exec -it busybox-container1 ip addr
  12. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  13. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  14. inet 127.0.0.1/8 scope host lo
  15. valid_lft forever preferred_lft forever
  16. 22: eth0@if23: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  17. link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
  18. inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
  19. valid_lft forever preferred_lft forever
  20. # 这是Kubernetes Pod最小调度单位默认的网络模式

范例:none 网络模式

  1. $ docker run -it --name busybox-none --network none --hostname busybox-none busybox /bin/sh
  2. / # ip addr
  3. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  4. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  5. inet 127.0.0.1/8 scope host lo
  6. valid_lft forever preferred_lft forever

:::color1 应用场景:

bridge :Docker 默认桥接网络

host :希望使用宿主机网络

none :手动配置容器网络,对接公司的IPAM

container :希望容器与另一个容器在一个网络命名空间,LNMP

:::

5.2 Docker网络模型容器

01 Docker 基础部分 - 图24

veth pair:成对出现的一种虚拟网络设备,数据从一端进,从另一端出。用于解决网络命名空间之间隔离。

docker0:网桥是一个二层网络设备,通过网桥可以将Linux支持的不同的端口连接起来,并实现类似交换机那样的多对多的通信。

5.3 网络访问原理

  1. # docker 启动后会产生一个 docker0 的桥接设备
  2. # docker0 可以理解为是一个交换机,是将容器接入到交换机中,实现容器与容器之间的通信
  3. # 并且可以将数据包传递到宿主机处理。
  4. $ ifconfig docker0
  5. docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
  6. inet 172.17.0.1 netmask 255.255.0.0 broadcast 172.17.255.255
  7. inet6 fe80::42:45ff:fe1c:2b38 prefixlen 64 scopeid 0x20<link>
  8. ether 02:42:45:1c:2b:38 txqueuelen 0 (Ethernet)
  9. RX packets 32 bytes 3436 (3.3 KiB)
  10. RX errors 0 dropped 0 overruns 0 frame 0
  11. TX packets 47 bytes 3446 (3.3 KiB)
  12. TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

Docker 使用 iptables 实现网络通信

  1. 外部访问容器:

01 Docker 基础部分 - 图25

  1. iptables -t nat -vnL DOCKER
  1. 容器访问外部:

01 Docker 基础部分 - 图26

  1. iptables -t nat -vnL POSTROUTING
范例:外部访问容器 bash # 查看宿主机容器进程 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES busybox-node ec4e0869e87a nginx "/docker-entrypoint.…" 25 minutes ago Up 25 minutes 0.0.0.0:88->80/tcp, :::88->80/tcp web01 # 外部访问容器(iptables-DNAT) $ iptables -t nat -vnL DOCKER 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:88 to:172.17.0.2:80 # iptables 判断本机的88端口要转发到172.17.0.2:80端口 # 宿主机会判断路由表信息 $ route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 10.0.0.2 0.0.0.0 UG 100 0 0 eth0 10.0.0.0 0.0.0.0 255.255.255.0 U 100 0 0 eth0 172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0 # 数据包会转发到docker0网桥,docker0又是一个二层交换机。 # docker0 会发送ARP广播,找到172.17.0.2的容器,就可以基于MAC地址进行通信 ### 所以在外部访问容器中关键在于 DNAT,路由表 范例:容器访问外部
  1. $ docker run -it -d --name busybox-node busybox
  2. $ docker exec -it busybox-node /bin/sh
  3. # 可以访问外网
  4. / # ping -c 1 -W 1 www.baidu.com
  5. PING www.baidu.com (183.232.231.174): 56 data bytes
  6. 64 bytes from 183.232.231.174: seq=0 ttl=127 time=15.140 ms
  7. --- www.baidu.com ping statistics ---
  8. 1 packets transmitted, 1 packets received, 0% packet loss
  9. round-trip min/avg/max = 15.140/15.140/15.140 ms
  10. # 查看网卡信息
  11. / # ifconfig
  12. eth0 Link encap:Ethernet HWaddr 02:42:AC:11:00:04
  13. inet addr:172.17.0.4 Bcast:172.17.255.255 Mask:255.255.0.0
  14. UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
  15. RX packets:13 errors:0 dropped:0 overruns:0 frame:0
  16. TX packets:5 errors:0 dropped:0 overruns:0 carrier:0
  17. collisions:0 txqueuelen:0
  18. RX bytes:1100 (1.0 KiB) TX bytes:328 (328.0 B)
  19. lo Link encap:Local Loopback
  20. inet addr:127.0.0.1 Mask:255.0.0.0
  21. UP LOOPBACK RUNNING MTU:65536 Metric:1
  22. RX packets:0 errors:0 dropped:0 overruns:0 frame:0
  23. TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
  24. collisions:0 txqueuelen:1000
  25. RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
  26. # 查看容器路由表
  27. / # route -n
  28. Kernel IP routing table
  29. Destination Gateway Genmask Flags Metric Ref Use Iface
  30. 0.0.0.0 172.17.0.1 0.0.0.0 UG 0 0 0 eth0
  31. 172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0
  32. # 查看宿主机容器进程
  33. $ docker ps
  34. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  35. 8d12c3faadd3 busybox "sh" 8 minutes ago Up 8 minutes busybox-node
  36. ec4e0869e87a nginx "/docker-entrypoint.…" 32 minutes ago Up 32 minutes 0.0.0.0:88->80/tcp, :::88->80/tcp web01
  37. # 可以判断到容器的下一跳就是docker0网桥设备,并且将数据包丢到docker0
  38. # docker0 设备将数据包转发到宿主机,# 例如容器ping百度,源IP:容器IP,目的IP:百度IP
  39. # 宿主机会查找路由表
  40. $ route -n
  41. Kernel IP routing table
  42. Destination Gateway Genmask Flags Metric Ref Use Iface
  43. 0.0.0.0 10.0.0.2 0.0.0.0 UG 100 0 0 eth0
  44. 10.0.0.0 0.0.0.0 255.255.255.0 U 100 0 0 eth0
  45. 172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0
  46. # 容器访问外部(iptables-SNAT)
  47. $ iptables -t nat -vnL POSTROUTING
  48. Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
  49. pkts bytes target prot opt in out source destination
  50. 3 202 MASQUERADE all -- * !docker0 172.17.0.0/16 0.0.0.0/0 # SNAT策略
  51. 0 0 MASQUERADE tcp -- * * 172.17.0.2 172.17.0.2 tcp dpt:80
  52. # 经过iptables的策略,将数据包的源IP改成为宿主机的IP发送出去
  53. # 经过宿主机的网关,发送到互联网中

5.4 容器网络实现核心技术:lptables

5.4.1 四表五链

:::color1 netfilter:IP包过滤;iptables:用户态工具

:::

01 Docker 基础部分 - 图27

5.4.2 操作命令

01 Docker 基础部分 - 图28

:::color1 Linux IP信息包过滤原理

:::

Docker 主要通过 <font style="color:#DF2A3F;">netfilter/iptables</font> 实现网络通信。

iptablesnetfilteriptables组成,netfilter组件是Linux内核集成的信息包过滤系统,它维护一个信息包过滤表,这个表用于控制信息包过滤处理的规则集。而iptables只是一个在用户空间的工具,用于增删改查这个过滤表的规则。发送方对数据进行TCP/IP封装,接收方则对数据进行TCP/IP的解封装。

01 Docker 基础部分 - 图29

参考文献:[ https://blog.csdn.net/weixin_45186298/article/details/122910466 ]

01 Docker 基础部分 - 图30

四表五链功能性介绍

iptables是(4张)表的集合:filter、nat、mangle、raw

表是(5条)链的集合:PREROUTING、INPUT、OUTPUT、FORWARD、POSTROUTING

  1. INPUT

画板

:::warning 客户端发起连接到Apache服务器的时候,数据报文到服务器的网卡处,首先判断 Router Table 的路由表信息,判断该用户的请求是不是本机的,如果不是则丢弃;如果是本机就会交给 netfilter 进行下一步处理。netfilter 会寻找匹配相应的规则,例如:如果目标端口是80的话,就允许放行,这样用户的数据报文就可以到 Http 应用进行处理并得到响应数据报文。

即 INPUT (入站)链。iptables 的规则就是写在 链上的。可以理解为所有入站的数据报文都要经过 iptables 的 INPUT 链,才能到达上层的用户空间。这就要看 INPUT 链的规则是如何编写的,需要匹配规则,如果是放行就放行,如果是拒绝就是拒绝。

:::

  1. OUTPUT

画板

:::warning 当用户在服务器上操作时,执行 curl 命令请求到 WebServer 的时候,数据报文会向到 netfilter 进行处理,netfilter 将数据报文先后转发到服务器的网卡处,通过 Router Table 路由表中进行转发到 WebServer 进行处理。则 netfilter 的 OUTPUT 链就是用来处理出站的规则匹配。

OUTPUT (出站)链的主要功能就是对机器出去的数据报文进行对应的过滤操作。

:::

  1. FORWORD

画板

:::info 将Linux服务器充当是路由器。并且Linux 服务器开启 net.ipv4.ip_forward = 1 路由转发功能,当 Client 客户端发起请求到目标地址是 WebServer,Client 发送的数据包会到路由器(Linux服务器)eth0网卡,因为开启了路由转发功能,所以会将数据包转发到 eth1网卡。只要涉及到转发,那么就会经过 netfilter 的 FORWORD 链。

FORWORD (转发)链的主要功能就是处理机器的转发数据报文进行规则匹配。

:::

  1. PREROUTING

画板

:::info PREROUTING 链在还没有路由表判断之前就对数据报文进行对应的修改。

PREROUTING (路由前)链翻译过来就是路由表之前对数据报文处理的一个接口

:::

  1. POSTROUTING

画板

:::info POSTROUTING 是先经过路由表判断之后,才到POSTROUTING 进行下一步的处理。

POSTROUTING (路由后)链翻译过来就是路由表之后对数据报文处理的一个接口

:::

:::info 链的作用是承载防火墙的规则,链则是存放在表中。

:::

规则链:承载防火墙规则

处理入站数据包:INPUT

处理出站数据包:OUTPUT

处理转发数据包:FORWARD

在进行路由选择前应用规则(处理数据包):修改目标地址 PREROUTING

在进行路由选择后应用规则(处理数据包):修改源地址 POSTROUTING

规则表:承载防火墙链

raw 表:确定是否对该数据包进行状态跟踪

  • 一旦我们的数据包经过防火墙以后,正常情况下会对数据包进行跟踪,跟踪会消耗资源。可以通过 raw 表将这些数据包进行跳出,不进行状态跟踪。

mangle 表:为数据包设置标记,例如:TTL MARK

  • 可以在数据包打上固定标签的 mangle 表
nat 表:修改数据包中的源、目的IP地址或者端口(实现地址转换)
  • 功能可以有端口映射,SNAT,DNAT
filter 表:确定是否放行该数据包(过滤)
  • 基础类防火墙最主要的表,会对数据包进行过滤

:::info 主要的是 nat 表和 filter 表,raw 表和mangle 表的使用较少。

:::

防火墙链表结构

01 Docker 基础部分 - 图36

不同表下面拥有的链也是不同的。只要知道要做的防火墙规则是怎么样的,只需要匹配对应的功能,再来选择对应的入站和出站。这样就知道 netfilter 的规则是写在哪张表的哪条链上。(红色标记是重点),例如在NAT表中的PREROUTING 链和 POSTROUTING 链是各自实现SNAT和DNAT的功能。

01 Docker 基础部分 - 图37

类别 选项 用途
添加新的规则 -A 在链的末尾追加一条规则
-I 在链的开头(或者指定序号)插入一条规则
查看规则列表 -L 列出所有的规则条目
-n 以数字形式形式地址,端口等信息
-v 以更加详细的方式显示规则信息(显示当前过滤的数据包和过滤的字节数)
—line-numbers 查看规则时,显示规则的序号
删除、清空规则 -D 删除链内指定序号(或者内容)的一条规则
-F 清空所有的规则
设置默认策略 -P 为指定的链设置默认规则

:::color1 容器访问外部,外部访问容器

:::

  1. # 9443 端口是 HTTPS
  2. # --restart=always 在Docker重启服务之后会自动启动
  3. $ docker run -d -p 8000:8000 -p 9000:9000 -p 9443:9443 --name portainer \
  4. --restart=always \
  5. -v /var/run/docker.sock:/var/run/docker.sock \
  6. -v portainer_data:/data \
  7. portainer/portainer
  8. $ docker ps
  9. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  10. 5f0ef6e5cb9d portainer/portainer "/portainer" 7 days ago Up 10 hours 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp, 0.0.0.0:9000->9000/tcp, :::9000->9000/tcp, 0.0.0.0:9443->9443/tcp, :::9443->9443/tcp portainer
  11. $ docker port portainer
  12. 8000/tcp -> 0.0.0.0:8000
  13. 8000/tcp -> :::8000
  14. 9000/tcp -> 0.0.0.0:9000
  15. 9000/tcp -> :::9000
  16. 9443/tcp -> 0.0.0.0:9443
  17. 9443/tcp -> :::9443
  18. $ iptables -vnL -t nat
  19. # 容器访问外部
  20. Chain POSTROUTING (policy ACCEPT 767 packets, 50988 bytes)
  21. pkts bytes target prot opt in out source destination
  22. 0 0 MASQUERADE tcp -- * * 172.17.0.2 172.17.0.2 tcp dpt:9443
  23. 0 0 MASQUERADE tcp -- * * 172.17.0.2 172.17.0.2 tcp dpt:9000
  24. 0 0 MASQUERADE tcp -- * * 172.17.0.2 172.17.0.2 tcp dpt:8000
  25. # 外部访问容器
  26. Chain DOCKER (2 references)
  27. pkts bytes target prot opt in out source destination
  28. 5 204 DNAT tcp -- !docker0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9443 to:172.17.0.2:9443
  29. 56 2988 DNAT tcp -- !docker0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9000 to:172.17.0.2:9000
  30. 14 688 DNAT tcp -- !docker0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8000 to:172.17.0.2:8000
  31. # 可以访问 Portainer 的页面
  32. # ● 第一次登录需创建admin,访问地址:IP地址:9000 <http://IP:9000/#/init/admin>
  33. # ● 设置admin用户和密码后首次登录

5.4.3 IPtables 工作流程

01 Docker 基础部分 - 图38

INPUT链:接收的数据包是本机(入站)时,应用此链中的规则。

OUTPUT链:本机向外发送数据包(出站)时,应用此链中的规则。

FORWARD链:需要通过防火墙中转发送给其他地址的数据包(转发)时,应用测链中的规则。

PREROUTING链:在对数据包做路由选择之前,应用此链中的规则。<font style="color:#E8323C;">SNAT</font>

POSTROUTING链:在对数据包做路由选择之后,应用此链中的规则。<font style="color:#E8323C;">DNAT</font>

  1. MASQUERADE 动态源地址转换
  2. SNAT 固定IP地址
  3. # SNAT 修改源IP地址为宿主机IP向外发出
  4. 容器访问外部
  5. -A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
  6. # 所有数据包来源IP来自 172.17.0.0/16 这个网段都要做源地址转换
  7. # DNAT 目标地址转换,修改数据包目标IP地址
  8. 外部访问容器
  9. -A DOCKER ! -i docker0 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.17.0.5:80
  10. # 生产环境中不会轻易手动修改iptables转发规则

5.5 跨主机网络:实现Docker主机容器通信

01 Docker 基础部分 - 图39

Flannel是CoreOS维护的一个网络组件,在每个主机上运行守护进程负责维护本地路由转发,Flannel使用ETCD来存储容器网络与主机之前的关系。

其他主流容器跨主机网络方案:

  1. 桥接宿主机网络
  2. 端口映射
  3. Docker网络驱动
  • Overlay:基于VXLAN封装实现Docker原生Overlay网络
  • Macvlan:Docker主机网卡接口逻辑上分为多个子接口,每个子接口标识一个VLAN。容器接口直接连接Docker主机网卡接口,通过路由策略转发到另一台Docker主机[ 是Docker做了一定的实现,是利用Linux内核的Macvlan的模块 ]
  1. 第三方网络项目
    1. 隧道方案
      1. Flannel:支持UDP和VXLAN封装传输方式
      2. Weave:支持UDP (sleeve模式)和VXLAN(优先fastdp模式
      3. OpenvSwitch:是一种虚拟的二层交换机,支持VXLAN和GRE协议
    2. 路由方案
      1. Calico:支持BGP协议和IPIP隧道。每台宿住主机作为虚拟路由,通过BGP协议实现不同主机容器间通信

5.5.1 Flannel实现Docker主机容器通信

1、etcd安装并配置

  1. # etcd 部署一台即可
  2. $ yum install etcd -y
  3. $ vi /etc/etcd/etcd.conf
  4. ETCD_DATA_DIR="/var/lib/etcd/default.etcd"
  5. ETCD_LISTEN_CLIENT_URLS= "http://10.0.0.54:2379"
  6. ETCD_NAME="default"
  7. ETCD_ADVERTISE_CLIENT_URLS="http://10.0.0.54:2379"
  8. $ systemctl enable --now etcd

2、flanneld安装并配置

  1. # 所有节点执行
  2. $ yum install flannel -y
  3. $ vi /etc/sysconfig/flanneld
  4. FLANNEL_ETCD_ENDPOINTS="http://10.0.0.54:2379"
  5. FLANNEL_ETCD_PREFIX="/atomic.io/network"
  6. # 以下步骤可省略
  7. $ mkdir -pv /atomic.io/network
  8. $ systemctl enable --now flanneld

3、向etcd写入子网

  1. $ etcdctl --endpoints="http://10.0.0.54:2379" set /atomic.io/network/config '{"Network": "172.17.0.0/16","Backend": {"Type": "vxlan"}}'
  2. # 查看Flannel日志
  3. $ cat /var/run/flannel/docker
  4. DOCKER_OPT_BIP="--bip=172.17.92.1/24"
  5. DOCKER_OPT_IPMASQ="--ip-masq=true"
  6. DOCKER_OPT_MTU="--mtu=1450"
  7. DOCKER_NETWORK_OPTIONS=" --bip=172.17.92.1/24 --ip-masq=true --mtu=1450"

4、配置Docker使用flannel生成的网络信息

  1. # vi /usr/lib/systemd/system/docker.service
  2. EnvironmentFile=/run/flannel/docker
  3. ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock $DOCKER_NETWORK_OPTIONS

5、启动所有服务并设置开机启动

  1. $ systemctl daemon-reload && systemctl restart docker
  2. # systemctl start docker
  3. $ systemctl enable --now docker
  4. $ ps -ef | grep docker
  5. root 3015 1 0 22:06 ? 00:00:00 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --bip=172.17.92.1/24 --ip-masq=true --mtu=1450
  6. root 3158 1679 0 22:06 pts/0 00:00:00 grep --color=auto docker
  7. # 从节点会同步flanneld配置
  8. $ cat /var/run/flannel/docker
  9. DOCKER_OPT_BIP="--bip=172.17.95.1/24"
  10. DOCKER_OPT_IPMASQ="--ip-masq=true"
  11. DOCKER_OPT_MTU="--mtu=1450"
  12. DOCKER_NETWORK_OPTIONS=" --bip=172.17.95.1/24 --ip-masq=true --mtu=1450"
  13. $ vi /usr/lib/systemd/system/docker.service
  14. EnvironmentFile=/run/flannel/docker
  15. ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock $DOCKER_NETWORK_OPTIONS
  16. $ systemctl daemon-reload && systemctl restart docker
  17. $ ps -ef | grep docker
  18. root 2588 1 1 22:09 ? 00:00:00 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --bip=172.17.95.1/24 --ip-masq=true --mtu=1450
  19. root 2724 2383 0 22:09 pts/1 00:00:00 grep --color=auto docker

6、将两台主机防火墙关闭以及iptables放通

  1. # FORWAD 设置 ACCEPT 允许
  2. iptables -P FORWARD ACCEPT
  3. # iptables -I FORWARD --dst 172.17.0.0/16 -j ACCEPT
  4. # 要先启动flanneld 再启动docker
  5. $ systemctl restart flanneld && systemctl restart docker

7、在两台主机创建容器相互ping验证

  1. # Docker-Node1
  2. $ docker run -it --name busybox-node1 --hostname busybox-node1 -d busybox
  3. / # ip addr
  4. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  5. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  6. inet 127.0.0.1/8 scope host lo
  7. valid_lft forever preferred_lft forever
  8. 9: eth0@if10: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1450 qdisc noqueue
  9. link/ether 02:42:ac:11:5c:02 brd ff:ff:ff:ff:ff:ff
  10. inet 172.17.92.2/24 brd 172.17.92.255 scope global eth0
  11. valid_lft forever preferred_lft forever
  12. / # ping -c 2 -W 1 172.17.95.2
  13. PING 172.17.95.2 (172.17.95.2): 56 data bytes
  14. 64 bytes from 172.17.95.2: seq=0 ttl=62 time=1.851 ms
  15. 64 bytes from 172.17.95.2: seq=1 ttl=62 time=0.509 ms
  16. --- 172.17.95.2 ping statistics ---
  17. 2 packets transmitted, 2 packets received, 0% packet loss
  18. round-trip min/avg/max = 0.509/1.180/1.851 ms
  19. # Docker-Node2
  20. $ docker run -it --name busybox-node2 --hostname busybox-node2 -d busybox
  21. / # ip addr
  22. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  23. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  24. inet 127.0.0.1/8 scope host lo
  25. valid_lft forever preferred_lft forever
  26. 9: eth0@if10: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1450 qdisc noqueue
  27. link/ether 02:42:ac:11:5f:02 brd ff:ff:ff:ff:ff:ff
  28. inet 172.17.95.2/24 brd 172.17.95.255 scope global eth0
  29. valid_lft forever preferred_lft forever
  30. / # ping -c 2 -W 1 172.17.92.2
  31. PING 172.17.92.2 (172.17.92.2): 56 data bytes
  32. 64 bytes from 172.17.92.2: seq=0 ttl=62 time=0.493 ms
  33. 64 bytes from 172.17.92.2: seq=1 ttl=62 time=0.600 ms
  34. --- 172.17.92.2 ping statistics ---
  35. 2 packets transmitted, 2 packets received, 0% packet loss
  36. round-trip min/avg/max = 0.493/0.546/0.600 ms

5.5.2 Weave 部署实现Docker主机容器通信

官方文档: https://www.weave.works/docs/net/latest/install/installing-weave

使用前提:

  1. 确保Linux内核版本3.8+Docker1.10+
  2. 节点之间如果有防火墙时,必须彼此放行TCP 6783UDP 6783/6784端口,这是Weave控制和数据端口。
  3. 主机名不能相同,通过主机名标识子网。

部署:

安装Docker

  1. # step 1: 安装必要的一些系统工具
  2. sudo apt-get update
  3. sudo apt-get -y install apt-transport-https ca-certificates curl software-properties-common
  4. # step 2: 安装GPG证书
  5. curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add -
  6. # Step 3: 写入软件源信息
  7. sudo add-apt-repository "deb [arch=amd64] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
  8. # Step 4: 更新并安装Docker-CE
  9. sudo apt-get -y update
  10. sudo apt-get -y install docker-ce
  11. # 安装指定版本的Docker-CE:
  12. # Step 1: 查找Docker-CE的版本:
  13. # apt-cache madison docker-ce
  14. # docker-ce | 17.03.1~ce-0~ubuntu-xenial | https://mirrors.aliyun.com/docker-ce/linux/ubuntu xenial/stable amd64 Packages
  15. # docker-ce | 17.03.0~ce-0~ubuntu-xenial | https://mirrors.aliyun.com/docker-ce/linux/ubuntu xenial/stable amd64 Packages
  16. # Step 2: 安装指定版本的Docker-CE: (VERSION例如上面的17.03.1~ce-0~ubuntu-xenial)
  17. # sudo apt-get -y install docker-ce=[VERSION]
  18. sudo mkdir -p /etc/docker
  19. sudo tee /etc/docker/daemon.json <<-'EOF'
  20. {
  21. "registry-mirrors": ["https://po13h3y1.mirror.aliyuncs.com","http://hub-mirror.c.163.com","https://mirror.ccs.tencentyun.com","http://f1361db2.m.daocloud.io"],
  22. "exec-opts": ["native.cgroupdriver=systemd"],
  23. "log-driver": "json-file",
  24. "log-opts": {
  25. "max-size": "100m"
  26. },
  27. "storage-driver": "overlay2"
  28. }
  29. EOF
  30. sudo systemctl daemon-reload && sudo systemctl restart docker
  1. 安装 Weave
  1. sudo curl -L git.io/weave -o /usr/local/bin/weave
  2. sudo chmod a+x /usr/local/bin/weave
  1. 启动并与其他主机建立连接
  1. # 10.0.0.100
  2. weave-01:~# weave launch 10.0.0.101
  3. # 10.0.0.101
  4. # 格式: weave launch <ip address>
  5. weave-02:~# weave launch 10.0.0.100
  6. # 查看 weave 进程(Docker 和 相同)
  7. $ docker ps -a
  8. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  9. a0cdadd6af76 weaveworks/weave:2.8.1 "/home/weave/weaver …" 2 minutes ago Up 2 minutes weave
  10. 6c99e03d4cbc weaveworks/weaveexec:2.8.1 "data-only" 2 minutes ago Created weavevolumes-2.8.1
  11. 9df415d01bfc weaveworks/weavedb:latest "data-only" 2 minutes ago Created weavedb
  12. $ ps -ef | grep weave
  13. root 9051 9033 0 12:32 ? 00:00:00 /home/weave/weaver --port 6783 --nickname ubuntu-cluster01 --host-root=/host --docker-bridge docker0 --weave-bridge weave --datapath datapath --ipalloc-range 10.32.0.0/12 --dns-listen-address 172.17.0.1:53 --http-addr 127.0.0.1:6784 --status-addr 127.0.0.1:6782 --resolv-conf /var/run/weave/etc/stub-resolv.conf -H unix:///var/run/weave/weave.sock --plugin --proxy 10.0.0.101
  14. root 9641 1372 0 12:35 pts/0 00:00:00 grep --color=auto weave
  15. # 查看Weave状态
  16. $ weave status connections
  17. <- 10.0.0.101:36825 established fastdp be:df:a6:58:c4:5b(ubuntu-cluster02) mtu=1376
  18. $ weave status
  19. Version: 2.8.1 (up to date; next check at 2022/11/26 17:31:37)
  20. Service: router
  21. Protocol: weave 1..2
  22. Name: 62:31:18:ff:de:8a(ubuntu-cluster01)
  23. Encryption: disabled
  24. PeerDiscovery: enabled
  25. Targets: 1
  26. Connections: 1 (1 established)
  27. Peers: 2 (with 2 established connections)
  28. TrustedSubnets: none
  29. Service: ipam
  30. Status: idle
  31. Range: 10.32.0.0/12
  32. DefaultSubnet: 10.32.0.0/12
  33. Service: dns
  34. Domain: weave.local.
  35. Upstream: none
  36. TTL: 1
  37. Entries: 0
  38. Service: proxy
  39. Address: unix:///var/run/weave/weave.sock
  40. Service: plugin (legacy)
  41. DriverName: weave
  42. # 查看Docker Network
  43. $ docker network ls
  44. NETWORK ID NAME DRIVER SCOPE
  45. 56ae06b199c5 bridge bridge local
  46. 79fd1c4f4207 host host local
  47. 7ed85ed91100 none null local
  48. 2670edf4b724 weave weavemesh local
  1. 使用Weave网络创建容器
  1. # 方式1:
  2. eval $(weave env) # 所有节点执行,创建的容器默认会添加到 Weave 网络中
  3. # ubuntu-cluster01 执行
  4. $ docker run -it busybox
  5. / # ip addr
  6. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  7. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  8. inet 127.0.0.1/8 scope host lo
  9. valid_lft forever preferred_lft forever
  10. 20: eth0@if21: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  11. link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
  12. inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
  13. valid_lft forever preferred_lft forever
  14. 22: ethwe@if23: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1376 qdisc noqueue
  15. link/ether 22:61:ef:5a:96:77 brd ff:ff:ff:ff:ff:ff
  16. inet 10.32.0.2/12 brd 10.47.255.255 scope global ethwe
  17. valid_lft forever preferred_lft forever
  18. # 容器连通性测试
  19. / # ping -c 1 -W 1 10.40.0.1
  20. PING 10.40.0.1 (10.40.0.1): 56 data bytes
  21. 64 bytes from 10.40.0.1: seq=0 ttl=64 time=1.490 ms
  22. --- 10.40.0.1 ping statistics ---
  23. 1 packets transmitted, 1 packets received, 0% packet loss
  24. round-trip min/avg/max = 1.490/1.490/1.490 ms
  25. # 容器可以连通宿主机外网
  26. / # ping -c 1 -W 1 www.baidu.com
  27. PING www.baidu.com (183.232.231.174): 56 data bytes
  28. 64 bytes from 183.232.231.174: seq=0 ttl=127 time=30.830 ms
  29. --- www.baidu.com ping statistics ---
  30. 1 packets transmitted, 1 packets received, 0% packet loss
  31. round-trip min/avg/max = 30.830/30.830/30.830 ms
  32. # ubuntu-cluster02 执行
  33. $ docker run -it busybox
  34. / # ip addr
  35. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  36. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  37. inet 127.0.0.1/8 scope host lo
  38. valid_lft forever preferred_lft forever
  39. 17: eth0@if18: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  40. link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
  41. inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
  42. valid_lft forever preferred_lft forever
  43. 19: ethwe@if20: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1376 qdisc noqueue
  44. link/ether 6a:bb:65:d3:80:f0 brd ff:ff:ff:ff:ff:ff
  45. inet 10.40.0.1/12 brd 10.47.255.255 scope global ethwe
  46. valid_lft forever preferred_lft forever
  47. ########################################################################################################################
  48. # 所有节点执行
  49. # 方式2:
  50. docker run -it -d --net=weave busybox
  51. # Weave 要比 Flannel 更加的强大
  52. # ubuntu-cluster01 执行
  53. $ docker ps
  54. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  55. d6c7802450de busybox "sh" 2 minutes ago Up 2 minutes funny_saha
  56. a0cdadd6af76 weaveworks/weave:2.8.1 "/home/weave/weaver …" 10 minutes ago Up 10 minutes weave
  57. $ docker exec -it funny_saha /bin/sh
  58. / # ip addr
  59. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  60. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  61. inet 127.0.0.1/8 scope host lo
  62. valid_lft forever preferred_lft forever
  63. 15: ethwe0@if16: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1376 qdisc noqueue
  64. link/ether 52:fc:49:07:dc:40 brd ff:ff:ff:ff:ff:ff
  65. inet 10.32.0.1/12 brd 10.47.255.255 scope global ethwe0
  66. valid_lft forever preferred_lft forever
  67. 18: eth0@if19: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  68. link/ether 02:42:ac:12:00:02 brd ff:ff:ff:ff:ff:ff
  69. inet 172.18.0.2/16 brd 172.18.255.255 scope global eth0
  70. valid_lft forever preferred_lft forever
  71. # 容器连通性测试
  72. / # ping -c 1 -W 1 10.40.0.0
  73. PING 10.40.0.0 (10.40.0.0): 56 data bytes
  74. 64 bytes from 10.40.0.0: seq=0 ttl=64 time=2.450 ms
  75. --- 10.40.0.0 ping statistics ---
  76. 1 packets transmitted, 1 packets received, 0% packet loss
  77. round-trip min/avg/max = 2.450/2.450/2.450 ms
  78. # ubuntu-cluster02 执行
  79. $ docker ps
  80. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  81. 24fa2ba12eb7 busybox "sh" 2 minutes ago Up 2 minutes keen_wozniak
  82. 198bba761658 weaveworks/weave:2.8.1 "/home/weave/weaver …" 9 minutes ago Up 9 minutes weave
  83. $ docker exec -it keen_wozniak /bin/sh
  84. / # ip addr
  85. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  86. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  87. inet 127.0.0.1/8 scope host lo
  88. valid_lft forever preferred_lft forever
  89. 12: ethwe0@if13: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1376 qdisc noqueue
  90. link/ether 16:c7:c5:66:81:08 brd ff:ff:ff:ff:ff:ff
  91. inet 10.40.0.0/12 brd 10.47.255.255 scope global ethwe0
  92. valid_lft forever preferred_lft forever
  93. 15: eth0@if16: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  94. link/ether 02:42:ac:12:00:02 brd ff:ff:ff:ff:ff:ff
  95. inet 172.18.0.2/16 brd 172.18.255.255 scope global eth0
  96. valid_lft forever preferred_lft forever
  1. 查看Weave的信息
  1. # 查看当前分配的容器
  2. $ weave ps
  3. weave:expose 62:31:18:ff:de:8a
  4. 3be8f8e8f68a 22:61:ef:5a:96:77 10.32.0.2/12
  5. d6c7802450de 52:fc:49:07:dc:40 10.32.0.1/12
  6. # 查看weave相互之间节点建立的关系
  7. $ weave status peers
  8. 62:31:18:ff:de:8a(ubuntu-cluster01)
  9. <- 10.0.0.101:36825 be:df:a6:58:c4:5b(ubuntu-cluster02) established
  10. be:df:a6:58:c4:5b(ubuntu-cluster02)
  11. -> 10.0.0.100:6783 62:31:18:ff:de:8a(ubuntu-cluster01) established
  12. # 查看weave版本
  13. $ weave version
  14. weave script 2.8.1
  15. weave 2.8.1
  16. # 查看网桥信息
  17. $ apt install -y bridge-utils
  18. $ brctl show
  19. bridge name bridge id STP enabled interfaces
  20. docker0 8000.0242cc4c48a4 no vethdc43521
  21. docker_gwbridge 8000.0242b455ce02 no vetha714a91
  22. weave 8000.623118ffde8a no vethwe-bridge
  23. vethwepl11240
  24. vethwlb3b8944d3

5.5.2.1 Weave 命令

  1. # 安装weave
  2. curl -L git.io/weave -o /usr/local/bin/weave
  3. # 通过weave setup预先将weave相关的容器Image下载到各个节点
  4. weave setup
  5. # 启动跨多节点(peer) weave network
  6. weave launch no-dns 192.168.56.7 192.168.59
  7. # 查看节点weave之间的连接状态:
  8. weave status connections
  9. # weave网络的整体状态:
  10. weave status
  11. # 查看状态详情
  12. weave status connections
  13. # 查看weave相互之间节点建立的关系
  14. weave status peers
  15. # 查看当前分配的容器
  16. weave ps
  17. # 查看weave当前版本
  18. weave version
  19. # 启动并与其他主机建立连接,启动weave并下载镜像
  20. weave launch
  21. # 进行连接 IP连接对端服务器
  22. weave launch
  23. # 使用weave代理
  24. weave env
  25. # 执行输出|来自weave env的输出
  26. export DOCKER_HOST=unix:///var/run/weave/weave.sock
  27. # 关闭weave
  28. weave stop
  29. # 关闭weave env代理
  30. export DOCKER=OPTS=

5.5.2.2 Weave 工作原理

01 Docker 基础部分 - 图40

1、ethwe 会将数据包发送给vethwe-bridge网桥。

2、vethwe-bridge接收到数据包后由weave去处理这个数据,通过UDP6783数据端口依照weave的路由表转发到下一路由节点。

3、如果该节点就是目的地,本地weave会把信息转发到内核的TCP协议站,再转发到目的节点。

weave通过在docker集群的每个主机上启动虚拟路由器,将主机作为路由器,形成互联互通的网络拓扑,在此基础上,实现容器的跨主机通信。其主机网络拓扑参见下图:

01 Docker 基础部分 - 图41

如上图所示,在每一个部署Docker的主机(可能是物理机也可能是虚拟机)上都部署有一个W(即weave router,它本身也可以以一个容器的形式部署)。weave网络是由这些weave routers组成的对等端点(peer)构成,并且可以通过weave命令行定制网络拓扑。

每个部署了weave router的主机之间都会建立TCP和UDP两个连接,保证weave router之间控制面流量和数据面流量的通过。控制面由weave routers之间建立的TCP连接构成,通过它进行握手和拓扑关系信息的交换通信。控制面的通信可以被配置为加密通信。而数据面由weave routers之间建立的UDP连接构成,这些连接大部分都会加密。这些连接都是全双工的,并且可以穿越防火墙。 当容器通过weave进行跨主机通信时,其网络通信模型可以参考下图:

01 Docker 基础部分 - 图42

从上面的网络模型图中可以看出,对每一个weave网络中的容器,weave都会创建一个网桥,并且在网桥和每个容器之间创建一个veth pair,一端作为容器网卡加入到容器的网络命名空间中,并为容器网卡配置ip和相应的掩码,一端连接在网桥上,最终通过宿主机上weave router将流量转发到对端主机上。

其基本过程如下:

1)容器流量通过veth pair到达宿主机上weave router网桥上。

2)weave router在混杂模式下使用pcap在网桥上截获网络数据包,并排除由内核直接通过网桥转发的数据流量,例如本子网内部、本地容器之间的数据以及宿主机和本地容器之间的流量。捕获的包通过UDP转发到所其他主机的weave router端。

3)在接收端,weave router通过pcap将包注入到网桥上的接口,通过网桥的上的veth pair,将流量分发到容器的网卡上。weave默认基于UDP承载容器之间的数据包,并且可以完全自定义整个集群的网络拓扑,但从性能和使用角度来看,还是有比较大的缺陷的:

→ weave自定义容器数据包的封包解包方式,不够通用,传输效率比较低,性能上的损失也比较大。

→ 集群配置比较负载,需要通过weave命令行来手工构建网络拓扑,在大规模集群的情况下,加重了管理员的负担。

5.5.2.3 Weave 其他功能

  • IP地址管理(IPAM)

Weave 自动为容器分配唯一的IP地址。可通过weave ps查看命名和发现

  • 命名的容器

自动会注册到Weave DNS中,并可以通过容器名称访问。

  1. # ubuntu-cluster01 执行
  2. $ docker run -itd --name busybox-node1 busybox
  3. $ docker exec -it busybox-node1 /bin/sh
  4. / # ip addr
  5. 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
  6. link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  7. inet 127.0.0.1/8 scope host lo
  8. valid_lft forever preferred_lft forever
  9. 30: eth0@if31: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
  10. link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
  11. inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
  12. valid_lft forever preferred_lft forever
  13. 32: ethwe@if33: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1376 qdisc noqueue
  14. link/ether da:87:cf:3d:95:0d brd ff:ff:ff:ff:ff:ff
  15. inet 10.32.0.3/12 brd 10.47.255.255 scope global ethwe
  16. valid_lft forever preferred_lft forever
  17. # ubuntu-cluster02 执行
  18. $ docker run -itd --name busybox-node2 busybox
  19. $ docker exec -it busybox-node2 /bin/sh
  20. / # ping -c 1 -W 1 busybox-node1
  21. PING busybox-node1 (10.32.0.3): 56 data bytes
  22. 64 bytes from 10.32.0.3: seq=0 ttl=64 time=1.232 ms
  23. --- busybox-node1 ping statistics ---
  24. 1 packets transmitted, 1 packets received, 0% packet loss
  25. round-trip min/avg/max = 1.232/1.232/1.232 ms
  • 负载均衡

允许注册多个相同名称的容器(不同服务器的相同容器名),Weave DNS随机为每个请求返回地址,提供基本的负载均衡功能。

  1. # 所有节点执行
  2. $ docker run -itd --name busybox1 busybox
  3. # 其中一个节点执行
  4. $ docker run -it --name busybox-cmd busybox
  5. / # ping -c 1 -W 1 busybox1
  6. PING busybox1 (10.32.0.4): 56 data bytes
  7. 64 bytes from 10.32.0.4: seq=0 ttl=64 time=1.560 ms
  8. --- busybox1 ping statistics ---
  9. 1 packets transmitted, 1 packets received, 0% packet loss
  10. round-trip min/avg/max = 1.560/1.560/1.560 ms
  11. / # ping -c 1 -W 1 busybox1
  12. PING busybox1 (10.40.0.3): 56 data bytes
  13. 64 bytes from 10.40.0.3: seq=0 ttl=64 time=0.197 ms
  14. --- busybox1 ping statistics ---
  15. 1 packets transmitted, 1 packets received, 0% packet loss
  16. round-trip min/avg/max = 0.197/0.197/0.197 ms
  17. # 会响应两个容器的IP地址,实现基本的负载均衡功能
  • 手动指定IP地址
  1. docker run -it -e WEAVE_CIDR=10.32.0.100/24 busybox
  • 动态拓扑

可以在不停止或重新配置剩余Docker主机的情况下添加主机到Weave网络中或从Weave网络中删除

  • 容错

weave peer不断交换拓扑信息,监视和建立与其他peer的网络连接。如果有主机或网络出现故障,Weave会绕过这个主机,保证两边容器可以继续通信,当恢复时,恢复完全连接。

:::color1 这也是 Weave 比 Flannel 功能强大的原因。实现的效果类似,只不过 Weave 从部署到功能上要比 Flannel 强大。

:::

6 使用 Dockerfile 定制容器镜像

6.1 Dockerfile介绍

Docker通过Dockerfile自动构建镜像,Dockerfile是一个包含用于组建镜像的文本文件,由一条一条的指令组成。

01 Docker 基础部分 - 图43

6.2 Dockerfile常用指令

一个镜像或者容器就是运行一个服务,不要当成虚拟机使用

指令 描述
FROM 构建新镜像是基于哪个镜像
LABEL 标签
RUN 构建镜像时运行的Shell命令
COPY 拷贝文件或目录到镜像中
ADD 解压压缩包并拷贝
ENV 设置环境变量
USER 为RUN、CMD和ENTRYPOINT执行命令指定运行用户
EXPOSE 声明容器运行的服务端口
WORKDIR 为RUN、CMD、ENTRYPOINT、COPY和ADD设置工作目录
CMD 运行容器时默认执行,如果有多个CMD指令,最后一个生效
ENTRYPOINT 如果与CMD一起用,CMD将作为ENTRYPOINT的默认参数,如果如果有多个ENTRYPOINT指令,最后一个生效

:::color1 镜像分类:

  1. 基础镜像:例如CentOS,Ubuntu,Alpine
  2. 环境镜像:例如Java,PHP,Go
  3. 项目镜像:将项目与环境镜像打包一起

:::

范例:创建Dockerfile

  1. $ mkdir -pv dockerfile/dockerfile-centos && cd dockerfile/dockerfile-centos
  2. $ vim Dockerfile
  3. FROM centos:centos7.9.2009
  4. LABEL maintainer <zhongzhiwei zhongzhiwei@kubesphere.io>
  5. # 设置容器环境变量
  6. ENV OS="centos"
  7. # 指定工作目录
  8. WORKDIR /tmp
  9. COPY hello.txt /tmp
  10. RUN yum install -y vim
  11. EXPOSE 8080
  12. CMD [ "sleep","3600" ]
  13. $ echo "Hello Dockerfile World" > hello.txt
  1. $ docker build -t centos-test:v1.0 -f Dockerfile .
  2. $ docker images centos-test
  3. REPOSITORY TAG IMAGE ID CREATED SIZE
  4. centos-test v1.0 38ae2bb8aeb8 About a minute ago 448MB
  5. # 将镜像运行成容器
  6. $ docker run -it --name centos-vim --rm centos-test:v1.0 /bin/bash
  7. [root@b730624cd590 tmp]# which vim
  8. /usr/bin/vim
  9. [root@b730624cd590 tmp]# pwd
  10. /tmp
  11. [root@b730624cd590 tmp]# cat hello.txt
  12. Hello Dockerfile World

6.3 docker build构建镜像

  1. Usage: docker build [OPTIONS] PATH |URL / - [flags]
  2. Options:
  3. -t, --tag list # 镜像名称
  4. -f, --file string # 指定Dockerfile文件位置
  5. # docker build -t shykes/myapp .
  6. # docker build -t shykes/myapp -f /path/Dockerfile/path
  7. # docker build -t shykes/myapp http://www.example.com/Dockerfile

6.4 CMD与ENTRYPOINT区别

CMD用法:

  • CMD [ “executable”, “param1”, “param2” ]:exec形式 ( 首选 ) [ 不能直接調用环境变量 ]
  • CMD [ “param1”, “param2”]:作为ENTRYPOINT的默认参数
  • CMD command param1 param2: Shell形式

ENTRYPOINT用法:

  • ENTRYPOINT [ “executable” , “param1” , “param2” ]
  • ENTRYPOINT command param1 param2

范例:CMD用法

  1. $ vim dockerfile-cmd/run.sh
  2. #!/bin/bash
  3. echo ${1}
  4. sleep 36000
  5. $ chmod +x dockerfile-cmd/run.sh
  6. $ vim dockerfile-cmd/Dockerfile
  7. FROM centos:centos7.9.2009
  8. LABEL maintainer <zhongzhiwei zhongzhiwei@kubesphere.io>
  9. COPY run.sh /usr/bin/
  10. CMD [ "run.sh","KubeSphere" ]
  11. # CMD [ "/bin/sh","-c","/usr/bin/run.sh KubeSphere" ]
  12. $ docker build -t centos-test:v1.0 -f Dockerfile .
  13. $ docker run -it -d centos-test:v1.0
  14. $ docker ps
  15. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  16. deecf9094d01 centos-test:v1.0 "run.sh KubeSphere" 27 seconds ago Up 25 seconds hopeful_turing
  17. $ docker logs hopeful_turing
  18. KubeSphere
  1. $ vim dockerfile-cmd/run.sh
  2. #!/bin/bash
  3. echo ${1}
  4. sleep 36000
  5. $ chmod +x dockerfile-cmd/run.sh
  6. $ vim dockerfile-cmd/Dockerfile
  7. FROM centos:centos7.9.2009
  8. LABEL maintainer <zhongzhiwei zhongzhiwei@kubesphere.io>
  9. COPY run.sh /usr/bin/
  10. CMD run.sh KubeSphere
  11. $ cd dockerfile-cmd
  12. $ docker build -t centos-test:v2.0 -f Dockerfile .
  13. $ docker run -it -d centos-test:v2.0
  14. $ docker ps
  15. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  16. 0d6af53d047a centos-test:v2.0 "/bin/sh -c 'run.sh …" 4 seconds ago Up 3 seconds sad_cannon
  17. $ docker logs sad_cannon
  18. KubeSphere
  19. # CMD 会被docker run最后的COMMAND覆盖

范例:ENTRYPOINT用法

  1. $ vim dockerfile-cmd/run.sh
  2. #!/bin/bash
  3. echo ${1}
  4. sleep 36000
  5. $ chmod +x dockerfile-cmd/run.sh
  6. $ vim dockerfile-entrypoint/Dockerfile
  7. FROM centos:centos7.9.2009
  8. LABEL maintainer <zhongzhiwei zhongzhiwei@kubesphere.io>
  9. ENV NAME=kubepshere
  10. COPY run.sh /usr/bin/
  11. ENTRYPOINT /usr/bin/run.sh $NAME
  12. $ cd dockerfile-entrypoint
  13. $ docker build -t centos-entrypoint:v1.0 -f Dockerfile .
  14. $ docker run -it -d centos-entrypoint:v1.0
  15. $ docker ps
  16. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  17. a255c579d2ce centos-entrypoint:v1.0 "/bin/sh -c '/usr/bi…" 2 seconds ago Up 1 second eloquent_montalcini
  18. $ docker logs eloquent_montalcini
  19. kubepshere
  20. # ENTRYPOINT 的参数需要 --entrypoint 替换
  1. $ vim Dockerfile
  2. FROM centos:centos7.9.2009
  3. LABEL maintainer <zhongzhiwei zhongzhiwei@kubesphere.io>
  4. ENV NAME=kubepshere
  5. COPY run.sh /usr/bin/
  6. ENTRYPOINT [ "echo" ]
  7. CMD [ "hello" ]
  8. # [ENTRYPOINT] [CMD]
  9. $ docker build -t centos-entrypoint:v2.0 -f Dockerfile .
  10. $ docker run -it --name centos-entrypoint -d centos-entrypoint:v2.0
  11. $ docker logs centos-entrypoint
  12. hello

:::color1 小结:

  1. CMDENTRYPOINT指令都可以用来定义运行容器时所使用的默认命令
  2. Dockerfile至少指定一个CMDENTRYPOINT
  3. CMD可以用作ENTRYPOINT默认参数,或者用作容器的默认命令
  4. docker run指定<command>时,将会覆盖CMD
  5. 如果是可执行文件,希望运行时传参,应该使用ENTRYPOINT

:::

6.5 前端项目镜像构建与部署:Nginx

  1. $ vim Dockerfile
  2. FROM centos:centos7.9.2009
  3. LABEL maintainer www.kubesphere.io
  4. # 设置阿里云Yum源环境
  5. # RUN curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo && \
  6. # curl -o /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
  7. RUN yum install -y gcc gcc-c++ make \
  8. openssl-devel pcre-devel gd-devel \
  9. iproute net-tools telnet wget curl && \
  10. yum clean all && \
  11. rm -rf /var/cache/yum/*
  12. # http://nginx.org/download/nginx-1.21.1.tar.gz 下载到Dockerfile同级目录
  13. ADD nginx-1.21.1.tar.gz /
  14. RUN cd nginx-1.21.1 && \
  15. ./configure --prefix=/usr/local/nginx \
  16. --with-http_ssl_module \
  17. --with-http_stub_status_module && \
  18. make -j 4 && make install && \
  19. mkdir /usr/local/nginx/conf/vhost && \
  20. cd / && rm -rf nginx* && \
  21. ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
  22. useradd nginx
  23. # 设置环境变量
  24. ENV PATH $PATH:/usr/local/nginx/sbin
  25. # 拷贝配置文件
  26. COPY nginx.conf /usr/local/nginx/conf/nginx.conf
  27. # 设置工作目录
  28. WORKDIR /usr/local/nginx
  29. EXPOSE 80
  30. CMD ["nginx", "-g", "daemon off;"]
  31. $ vim nginx.conf
  32. user nginx;
  33. worker_processes auto;
  34. error_log logs/error.log info;
  35. pid logs/nginx.pid;
  36. events {
  37. worker_connections 1024;
  38. }
  39. http {
  40. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  41. '$status $body_bytes_sent "$http_referer" '
  42. '"$http_user_agent" "$http_x_forwarded_for"';
  43. access_log logs/access.log main;
  44. sendfile on;
  45. tcp_nopush on;
  46. tcp_nodelay on;
  47. keepalive_timeout 65;
  48. types_hash_max_size 2048;
  49. include mime.types;
  50. default_type application/octet-stream;
  51. include /etc/nginx/conf.d/*.conf;
  52. server {
  53. listen 80 default_server;
  54. listen [::]:80 default_server;
  55. server_name _;
  56. root /usr/share/nginx/html;
  57. include /usr/local/nginx/conf/vhost/*.conf;
  58. location / {
  59. root html;
  60. index index.html index.htm;
  61. }
  62. # location ~* \.php$ {
  63. # root html;
  64. # fastcgi_pass php:9000;
  65. # fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  66. # include fastcgi_params;
  67. # }
  68. # error_page 404 /404.html;
  69. # location = /40x.html {
  70. # }
  71. # error_page 500 502 503 504 /50x.html;
  72. # location = /50x.html {
  73. # }
  74. }
  75. }
  1. $ docker build -t centos-nginx:v1.0 -f Dockerfile .
  2. $ docker run -it -d -p 10880:80 --name centos-nginx-node1 centos-nginx:v1.0
  3. # 查看Docker运行状态
  4. $ docker ps -l
  5. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  6. 438a2806319d centos-nginx:v1.0 "nginx -g 'daemon of…" 22 seconds ago Up 21 seconds 0.0.0.0:10880->80/tcp, :::10880->80/tcp centos-nginx-node1
  7. $ curl 127.0.0.1:10880
  8. <!DOCTYPE html>
  9. <html>
  10. <head>
  11. <title>Welcome to nginx!</title>
  12. <style>
  13. body {
  14. width: 35em;
  15. margin: 0 auto;
  16. font-family: Tahoma, Verdana, Arial, sans-serif;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <h1>Welcome to nginx!</h1>
  22. <p>If you see this page, the nginx web server is successfully installed and
  23. working. Further configuration is required.</p>
  24. <p>For online documentation and support please refer to
  25. <a href="http://nginx.org/">nginx.org</a>.<br/>
  26. Commercial support is available at
  27. <a href="http://nginx.com/">nginx.com</a>.</p>
  28. <p><em>Thank you for using nginx.</em></p>
  29. </body>
  30. </html>
  31. # 浏览器访问:http://<IP地址>:10880

01 Docker 基础部分 - 图44

  1. $ docker run -it -d -p 10990:80 --name centos-nginx-node2 -v /opt/wwwroot:/usr/local/nginx/html centos-nginx:v1.0
  2. $ docker ps -l
  3. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  4. 03ff752bf295 centos-nginx:v1.0 "nginx -g 'daemon of…" 22 seconds ago Up 21 seconds 0.0.0.0:10990->80/tcp, :::10990->80/tcp centos-nginx-node2
  5. $ echo "<h1>Hello NGINX Docker</h1>" > /opt/wwwroot/index.html
  6. $ curl 127.0.0.1:10990
  7. <h1>Hello NGINX Docker</h1>
  8. # 浏览器访问:http://<IP地址>:10990

01 Docker 基础部分 - 图45

6.6 PHP项目镜像构建:PHP

  1. FROM centos:centos7.9.2009
  2. MAINTAINER zhongzhiwei www.kubespehre.io
  3. RUN yum install epel-release -y && \
  4. yum install -y gcc gcc-c++ make gd-devel libxml2-devel \
  5. libcurl-devel libjpeg-devel libpng-devel openssl-devel \
  6. libmcrypt-devel libxslt-devel libtidy-devel autoconf \
  7. iproute net-tools telnet wget curl && \
  8. yum clean all &&\
  9. rm -rf /var/cache/yum/*
  10. # wget http://cn2.php.net/get/php-5.6.36.tar.gz/from/this/mirror -O php-5.6.36.tar.gz
  11. ADD php-5.6.36.tar.gz /
  12. RUN cd php-5.6.36 && \
  13. ./configure --prefix=/usr/local/php \
  14. --with-config-file-path=/usr/local/php/etc \
  15. --enable-fpm --enable-opcache \
  16. --with-mysql --with-mysqli --with-pdo-mysql \
  17. --with-openssl --with-zlib --with-curl --with-gd \
  18. --with-jpeg-dir --with-png-dir --with-freetype-dir \
  19. --enable-mbstring --with-mcrypt --enable-hash && \
  20. make -j 4 && make install && \
  21. cp php.ini-production /usr/local/php/etc/php.ini && \
  22. cp sapi/fpm/php-fpm.conf /usr/local/php/etc/php-fpm.conf && \
  23. sed -i "90a \daemonize = no" /usr/local/php/etc/php-fpm.conf && \
  24. mkdir -p /usr/local/php/log && \
  25. cd / && rm -rf php* && \
  26. ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
  27. ENV PATH $PATH:/usr/local/php/sbin
  28. COPY php.ini /usr/local/php/etc/
  29. COPY php-fpm.conf /usr/local/php/etc/
  30. # 设置工作目录
  31. WORKDIR /usr/local/php
  32. EXPOSE 9000
  33. CMD ["php-fpm"]

范例:PHP 配置文件示例

  1. cat > php-fpm.conf <<-'EOF'
  2. ;;;;;;;;;;;;;;;;;;;;;
  3. ; FPM Configuration ;
  4. ;;;;;;;;;;;;;;;;;;;;;
  5. ; All relative paths in this configuration file are relative to PHP's install
  6. ; prefix (/usr/local/php). This prefix can be dynamically changed by using the
  7. ; '-p' argument from the command line.
  8. ; Include one or more files. If glob(3) exists, it is used to include a bunch of
  9. ; files from a glob(3) pattern. This directive can be used everywhere in the
  10. ; file.
  11. ; Relative path can also be used. They will be prefixed by:
  12. ; - the global prefix if it's been set (-p argument)
  13. ; - /usr/local/php otherwise
  14. ;include=etc/fpm.d/*.conf
  15. ;;;;;;;;;;;;;;;;;;
  16. ; Global Options ;
  17. ;;;;;;;;;;;;;;;;;;
  18. [global]
  19. ; Pid file
  20. ; Note: the default prefix is /usr/local/php/var
  21. ; Default Value: none
  22. ;pid = run/php-fpm.pid
  23. ; Error log file
  24. ; If it's set to "syslog", log is sent to syslogd instead of being written
  25. ; in a local file.
  26. ; Note: the default prefix is /usr/local/php/var
  27. ; Default Value: log/php-fpm.log
  28. ;error_log = log/php-fpm.log
  29. ; syslog_facility is used to specify what type of program is logging the
  30. ; message. This lets syslogd specify that messages from different facilities
  31. ; will be handled differently.
  32. ; See syslog(3) for possible values (ex daemon equiv LOG_DAEMON)
  33. ; Default Value: daemon
  34. ;syslog.facility = daemon
  35. ; syslog_ident is prepended to every message. If you have multiple FPM
  36. ; instances running on the same server, you can change the default value
  37. ; which must suit common needs.
  38. ; Default Value: php-fpm
  39. ;syslog.ident = php-fpm
  40. ; Log level
  41. ; Possible Values: alert, error, warning, notice, debug
  42. ; Default Value: notice
  43. ;log_level = notice
  44. ; If this number of child processes exit with SIGSEGV or SIGBUS within the time
  45. ; interval set by emergency_restart_interval then FPM will restart. A value
  46. ; of '0' means 'Off'.
  47. ; Default Value: 0
  48. ;emergency_restart_threshold = 0
  49. ; Interval of time used by emergency_restart_interval to determine when
  50. ; a graceful restart will be initiated. This can be useful to work around
  51. ; accidental corruptions in an accelerator's shared memory.
  52. ; Available Units: s(econds), m(inutes), h(ours), or d(ays)
  53. ; Default Unit: seconds
  54. ; Default Value: 0
  55. ;emergency_restart_interval = 0
  56. ; Time limit for child processes to wait for a reaction on signals from master.
  57. ; Available units: s(econds), m(inutes), h(ours), or d(ays)
  58. ; Default Unit: seconds
  59. ; Default Value: 0
  60. ;process_control_timeout = 0
  61. ; The maximum number of processes FPM will fork. This has been design to control
  62. ; the global number of processes when using dynamic PM within a lot of pools.
  63. ; Use it with caution.
  64. ; Note: A value of 0 indicates no limit
  65. ; Default Value: 0
  66. ; process.max = 128
  67. ; Specify the nice(2) priority to apply to the master process (only if set)
  68. ; The value can vary from -19 (highest priority) to 20 (lower priority)
  69. ; Note: - It will only work if the FPM master process is launched as root
  70. ; - The pool process will inherit the master process priority
  71. ; unless it specified otherwise
  72. ; Default Value: no set
  73. ; process.priority = -19
  74. ; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
  75. ; Default Value: yes
  76. ;daemonize = yes
  77. daemonize = no
  78. ; Set open file descriptor rlimit for the master process.
  79. ; Default Value: system defined value
  80. ;rlimit_files = 1024
  81. ; Set max core size rlimit for the master process.
  82. ; Possible Values: 'unlimited' or an integer greater or equal to 0
  83. ; Default Value: system defined value
  84. ;rlimit_core = 0
  85. ; Specify the event mechanism FPM will use. The following is available:
  86. ; - select (any POSIX os)
  87. ; - poll (any POSIX os)
  88. ; - epoll (linux >= 2.5.44)
  89. ; - kqueue (FreeBSD >= 4.1, OpenBSD >= 2.9, NetBSD >= 2.0)
  90. ; - /dev/poll (Solaris >= 7)
  91. ; - port (Solaris >= 10)
  92. ; Default Value: not set (auto detection)
  93. ;events.mechanism = epoll
  94. ; When FPM is build with systemd integration, specify the interval,
  95. ; in second, between health report notification to systemd.
  96. ; Set to 0 to disable.
  97. ; Available Units: s(econds), m(inutes), h(ours)
  98. ; Default Unit: seconds
  99. ; Default value: 10
  100. ;systemd_interval = 10
  101. ;;;;;;;;;;;;;;;;;;;;
  102. ; Pool Definitions ;
  103. ;;;;;;;;;;;;;;;;;;;;
  104. ; Multiple pools of child processes may be started with different listening
  105. ; ports and different management options. The name of the pool will be
  106. ; used in logs and stats. There is no limitation on the number of pools which
  107. ; FPM can handle. Your system will tell you anyway :)
  108. ; Start a new pool named 'www'.
  109. ; the variable $pool can we used in any directive and will be replaced by the
  110. ; pool name ('www' here)
  111. [www]
  112. ; Per pool prefix
  113. ; It only applies on the following directives:
  114. ; - 'access.log'
  115. ; - 'slowlog'
  116. ; - 'listen' (unixsocket)
  117. ; - 'chroot'
  118. ; - 'chdir'
  119. ; - 'php_values'
  120. ; - 'php_admin_values'
  121. ; When not set, the global prefix (or /usr/local/php) applies instead.
  122. ; Note: This directive can also be relative to the global prefix.
  123. ; Default Value: none
  124. ;prefix = /path/to/pools/$pool
  125. ; Unix user/group of processes
  126. ; Note: The user is mandatory. If the group is not set, the default user's group
  127. ; will be used.
  128. user = nobody
  129. group = nobody
  130. ; The address on which to accept FastCGI requests.
  131. ; Valid syntaxes are:
  132. ; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
  133. ; a specific port;
  134. ; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
  135. ; a specific port;
  136. ; 'port' - to listen on a TCP socket to all IPv4 addresses on a
  137. ; specific port;
  138. ; '[::]:port' - to listen on a TCP socket to all addresses
  139. ; (IPv6 and IPv4-mapped) on a specific port;
  140. ; '/path/to/unix/socket' - to listen on a unix socket.
  141. ; Note: This value is mandatory.
  142. listen = 127.0.0.1:9000
  143. ; Set listen(2) backlog.
  144. ; Default Value: 65535 (-1 on FreeBSD and OpenBSD)
  145. ;listen.backlog = 65535
  146. ; Set permissions for unix socket, if one is used. In Linux, read/write
  147. ; permissions must be set in order to allow connections from a web server. Many
  148. ; BSD-derived systems allow connections regardless of permissions.
  149. ; Default Values: user and group are set as the running user
  150. ; mode is set to 0660
  151. ;listen.owner = nobody
  152. ;listen.group = nobody
  153. ;listen.mode = 0660
  154. ; When POSIX Access Control Lists are supported you can set them using
  155. ; these options, value is a comma separated list of user/group names.
  156. ; When set, listen.owner and listen.group are ignored
  157. ;listen.acl_users =
  158. ;listen.acl_groups =
  159. ; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect.
  160. ; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
  161. ; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
  162. ; must be separated by a comma. If this value is left blank, connections will be
  163. ; accepted from any ip address.
  164. ; Default Value: any
  165. ;listen.allowed_clients = 127.0.0.1
  166. ; Specify the nice(2) priority to apply to the pool processes (only if set)
  167. ; The value can vary from -19 (highest priority) to 20 (lower priority)
  168. ; Note: - It will only work if the FPM master process is launched as root
  169. ; - The pool processes will inherit the master process priority
  170. ; unless it specified otherwise
  171. ; Default Value: no set
  172. ; process.priority = -19
  173. ; Set the process dumpable flag (PR_SET_DUMPABLE prctl) even if the process user
  174. ; or group is differrent than the master process user. It allows to create process
  175. ; core dump and ptrace the process for the pool user.
  176. ; Default Value: no
  177. ; process.dumpable = yes
  178. ; Choose how the process manager will control the number of child processes.
  179. ; Possible Values:
  180. ; static - a fixed number (pm.max_children) of child processes;
  181. ; dynamic - the number of child processes are set dynamically based on the
  182. ; following directives. With this process management, there will be
  183. ; always at least 1 children.
  184. ; pm.max_children - the maximum number of children that can
  185. ; be alive at the same time.
  186. ; pm.start_servers - the number of children created on startup.
  187. ; pm.min_spare_servers - the minimum number of children in 'idle'
  188. ; state (waiting to process). If the number
  189. ; of 'idle' processes is less than this
  190. ; number then some children will be created.
  191. ; pm.max_spare_servers - the maximum number of children in 'idle'
  192. ; state (waiting to process). If the number
  193. ; of 'idle' processes is greater than this
  194. ; number then some children will be killed.
  195. ; ondemand - no children are created at startup. Children will be forked when
  196. ; new requests will connect. The following parameter are used:
  197. ; pm.max_children - the maximum number of children that
  198. ; can be alive at the same time.
  199. ; pm.process_idle_timeout - The number of seconds after which
  200. ; an idle process will be killed.
  201. ; Note: This value is mandatory.
  202. pm = dynamic
  203. ; The number of child processes to be created when pm is set to 'static' and the
  204. ; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
  205. ; This value sets the limit on the number of simultaneous requests that will be
  206. ; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
  207. ; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
  208. ; CGI. The below defaults are based on a server without much resources. Don't
  209. ; forget to tweak pm.* to fit your needs.
  210. ; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
  211. ; Note: This value is mandatory.
  212. pm.max_children = 5
  213. ; The number of child processes created on startup.
  214. ; Note: Used only when pm is set to 'dynamic'
  215. ; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
  216. pm.start_servers = 2
  217. ; The desired minimum number of idle server processes.
  218. ; Note: Used only when pm is set to 'dynamic'
  219. ; Note: Mandatory when pm is set to 'dynamic'
  220. pm.min_spare_servers = 1
  221. ; The desired maximum number of idle server processes.
  222. ; Note: Used only when pm is set to 'dynamic'
  223. ; Note: Mandatory when pm is set to 'dynamic'
  224. pm.max_spare_servers = 3
  225. ; The number of seconds after which an idle process will be killed.
  226. ; Note: Used only when pm is set to 'ondemand'
  227. ; Default Value: 10s
  228. ;pm.process_idle_timeout = 10s;
  229. ; The number of requests each child process should execute before respawning.
  230. ; This can be useful to work around memory leaks in 3rd party libraries. For
  231. ; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
  232. ; Default Value: 0
  233. ;pm.max_requests = 500
  234. ; The URI to view the FPM status page. If this value is not set, no URI will be
  235. ; recognized as a status page. It shows the following informations:
  236. ; pool - the name of the pool;
  237. ; process manager - static, dynamic or ondemand;
  238. ; start time - the date and time FPM has started;
  239. ; start since - number of seconds since FPM has started;
  240. ; accepted conn - the number of request accepted by the pool;
  241. ; listen queue - the number of request in the queue of pending
  242. ; connections (see backlog in listen(2));
  243. ; max listen queue - the maximum number of requests in the queue
  244. ; of pending connections since FPM has started;
  245. ; listen queue len - the size of the socket queue of pending connections;
  246. ; idle processes - the number of idle processes;
  247. ; active processes - the number of active processes;
  248. ; total processes - the number of idle + active processes;
  249. ; max active processes - the maximum number of active processes since FPM
  250. ; has started;
  251. ; max children reached - number of times, the process limit has been reached,
  252. ; when pm tries to start more children (works only for
  253. ; pm 'dynamic' and 'ondemand');
  254. ; Value are updated in real time.
  255. ; Example output:
  256. ; pool: www
  257. ; process manager: static
  258. ; start time: 01/Jul/2011:17:53:49 +0200
  259. ; start since: 62636
  260. ; accepted conn: 190460
  261. ; listen queue: 0
  262. ; max listen queue: 1
  263. ; listen queue len: 42
  264. ; idle processes: 4
  265. ; active processes: 11
  266. ; total processes: 15
  267. ; max active processes: 12
  268. ; max children reached: 0
  269. ;
  270. ; By default the status page output is formatted as text/plain. Passing either
  271. ; 'html', 'xml' or 'json' in the query string will return the corresponding
  272. ; output syntax. Example:
  273. ; http://www.foo.bar/status
  274. ; http://www.foo.bar/status?json
  275. ; http://www.foo.bar/status?html
  276. ; http://www.foo.bar/status?xml
  277. ;
  278. ; By default the status page only outputs short status. Passing 'full' in the
  279. ; query string will also return status for each pool process.
  280. ; Example:
  281. ; http://www.foo.bar/status?full
  282. ; http://www.foo.bar/status?json&full
  283. ; http://www.foo.bar/status?html&full
  284. ; http://www.foo.bar/status?xml&full
  285. ; The Full status returns for each process:
  286. ; pid - the PID of the process;
  287. ; state - the state of the process (Idle, Running, ...);
  288. ; start time - the date and time the process has started;
  289. ; start since - the number of seconds since the process has started;
  290. ; requests - the number of requests the process has served;
  291. ; request duration - the duration in µs of the requests;
  292. ; request method - the request method (GET, POST, ...);
  293. ; request URI - the request URI with the query string;
  294. ; content length - the content length of the request (only with POST);
  295. ; user - the user (PHP_AUTH_USER) (or '-' if not set);
  296. ; script - the main script called (or '-' if not set);
  297. ; last request cpu - the %cpu the last request consumed
  298. ; it's always 0 if the process is not in Idle state
  299. ; because CPU calculation is done when the request
  300. ; processing has terminated;
  301. ; last request memory - the max amount of memory the last request consumed
  302. ; it's always 0 if the process is not in Idle state
  303. ; because memory calculation is done when the request
  304. ; processing has terminated;
  305. ; If the process is in Idle state, then informations are related to the
  306. ; last request the process has served. Otherwise informations are related to
  307. ; the current request being served.
  308. ; Example output:
  309. ; ************************
  310. ; pid: 31330
  311. ; state: Running
  312. ; start time: 01/Jul/2011:17:53:49 +0200
  313. ; start since: 63087
  314. ; requests: 12808
  315. ; request duration: 1250261
  316. ; request method: GET
  317. ; request URI: /test_mem.php?N=10000
  318. ; content length: 0
  319. ; user: -
  320. ; script: /home/fat/web/docs/php/test_mem.php
  321. ; last request cpu: 0.00
  322. ; last request memory: 0
  323. ;
  324. ; Note: There is a real-time FPM status monitoring sample web page available
  325. ; It's available in: /usr/local/php/share/php/fpm/status.html
  326. ;
  327. ; Note: The value must start with a leading slash (/). The value can be
  328. ; anything, but it may not be a good idea to use the .php extension or it
  329. ; may conflict with a real PHP file.
  330. ; Default Value: not set
  331. ;pm.status_path = /status
  332. ; The ping URI to call the monitoring page of FPM. If this value is not set, no
  333. ; URI will be recognized as a ping page. This could be used to test from outside
  334. ; that FPM is alive and responding, or to
  335. ; - create a graph of FPM availability (rrd or such);
  336. ; - remove a server from a group if it is not responding (load balancing);
  337. ; - trigger alerts for the operating team (24/7).
  338. ; Note: The value must start with a leading slash (/). The value can be
  339. ; anything, but it may not be a good idea to use the .php extension or it
  340. ; may conflict with a real PHP file.
  341. ; Default Value: not set
  342. ;ping.path = /ping
  343. ; This directive may be used to customize the response of a ping request. The
  344. ; response is formatted as text/plain with a 200 response code.
  345. ; Default Value: pong
  346. ;ping.response = pong
  347. ; The access log file
  348. ; Default: not set
  349. ;access.log = log/$pool.access.log
  350. ; The access log format.
  351. ; The following syntax is allowed
  352. ; %%: the '%' character
  353. ; %C: %CPU used by the request
  354. ; it can accept the following format:
  355. ; - %{user}C for user CPU only
  356. ; - %{system}C for system CPU only
  357. ; - %{total}C for user + system CPU (default)
  358. ; %d: time taken to serve the request
  359. ; it can accept the following format:
  360. ; - %{seconds}d (default)
  361. ; - %{miliseconds}d
  362. ; - %{mili}d
  363. ; - %{microseconds}d
  364. ; - %{micro}d
  365. ; %e: an environment variable (same as $_ENV or $_SERVER)
  366. ; it must be associated with embraces to specify the name of the env
  367. ; variable. Some exemples:
  368. ; - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
  369. ; - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
  370. ; %f: script filename
  371. ; %l: content-length of the request (for POST request only)
  372. ; %m: request method
  373. ; %M: peak of memory allocated by PHP
  374. ; it can accept the following format:
  375. ; - %{bytes}M (default)
  376. ; - %{kilobytes}M
  377. ; - %{kilo}M
  378. ; - %{megabytes}M
  379. ; - %{mega}M
  380. ; %n: pool name
  381. ; %o: output header
  382. ; it must be associated with embraces to specify the name of the header:
  383. ; - %{Content-Type}o
  384. ; - %{X-Powered-By}o
  385. ; - %{Transfert-Encoding}o
  386. ; - ....
  387. ; %p: PID of the child that serviced the request
  388. ; %P: PID of the parent of the child that serviced the request
  389. ; %q: the query string
  390. ; %Q: the '?' character if query string exists
  391. ; %r: the request URI (without the query string, see %q and %Q)
  392. ; %R: remote IP address
  393. ; %s: status (response code)
  394. ; %t: server time the request was received
  395. ; it can accept a strftime(3) format:
  396. ; %d/%b/%Y:%H:%M:%S %z (default)
  397. ; %T: time the log has been written (the request has finished)
  398. ; it can accept a strftime(3) format:
  399. ; %d/%b/%Y:%H:%M:%S %z (default)
  400. ; %u: remote user
  401. ;
  402. ; Default: "%R - %u %t \"%m %r\" %s"
  403. ;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"
  404. ; The log file for slow requests
  405. ; Default Value: not set
  406. ; Note: slowlog is mandatory if request_slowlog_timeout is set
  407. ;slowlog = log/$pool.log.slow
  408. ; The timeout for serving a single request after which a PHP backtrace will be
  409. ; dumped to the 'slowlog' file. A value of '0s' means 'off'.
  410. ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
  411. ; Default Value: 0
  412. ;request_slowlog_timeout = 0
  413. ; The timeout for serving a single request after which the worker process will
  414. ; be killed. This option should be used when the 'max_execution_time' ini option
  415. ; does not stop script execution for some reason. A value of '0' means 'off'.
  416. ; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
  417. ; Default Value: 0
  418. ;request_terminate_timeout = 0
  419. ; Set open file descriptor rlimit.
  420. ; Default Value: system defined value
  421. ;rlimit_files = 1024
  422. ; Set max core size rlimit.
  423. ; Possible Values: 'unlimited' or an integer greater or equal to 0
  424. ; Default Value: system defined value
  425. ;rlimit_core = 0
  426. ; Chroot to this directory at the start. This value must be defined as an
  427. ; absolute path. When this value is not set, chroot is not used.
  428. ; Note: you can prefix with '$prefix' to chroot to the pool prefix or one
  429. ; of its subdirectories. If the pool prefix is not set, the global prefix
  430. ; will be used instead.
  431. ; Note: chrooting is a great security feature and should be used whenever
  432. ; possible. However, all PHP paths will be relative to the chroot
  433. ; (error_log, sessions.save_path, ...).
  434. ; Default Value: not set
  435. ;chroot =
  436. ; Chdir to this directory at the start.
  437. ; Note: relative path can be used.
  438. ; Default Value: current directory or / when chroot
  439. ;chdir = /var/www
  440. ; Redirect worker stdout and stderr into main error log. If not set, stdout and
  441. ; stderr will be redirected to /dev/null according to FastCGI specs.
  442. ; Note: on highloaded environement, this can cause some delay in the page
  443. ; process time (several ms).
  444. ; Default Value: no
  445. ;catch_workers_output = yes
  446. ; Clear environment in FPM workers
  447. ; Prevents arbitrary environment variables from reaching FPM worker processes
  448. ; by clearing the environment in workers before env vars specified in this
  449. ; pool configuration are added.
  450. ; Setting to "no" will make all environment variables available to PHP code
  451. ; via getenv(), $_ENV and $_SERVER.
  452. ; Default Value: yes
  453. ;clear_env = no
  454. ; Limits the extensions of the main script FPM will allow to parse. This can
  455. ; prevent configuration mistakes on the web server side. You should only limit
  456. ; FPM to .php extensions to prevent malicious users to use other extensions to
  457. ; exectute php code.
  458. ; Note: set an empty value to allow all extensions.
  459. ; Default Value: .php
  460. ;security.limit_extensions = .php .php3 .php4 .php5
  461. ; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
  462. ; the current environment.
  463. ; Default Value: clean env
  464. ;env[HOSTNAME] = $HOSTNAME
  465. ;env[PATH] = /usr/local/bin:/usr/bin:/bin
  466. ;env[TMP] = /tmp
  467. ;env[TMPDIR] = /tmp
  468. ;env[TEMP] = /tmp
  469. ; Additional php.ini defines, specific to this pool of workers. These settings
  470. ; overwrite the values previously defined in the php.ini. The directives are the
  471. ; same as the PHP SAPI:
  472. ; php_value/php_flag - you can set classic ini defines which can
  473. ; be overwritten from PHP call 'ini_set'.
  474. ; php_admin_value/php_admin_flag - these directives won't be overwritten by
  475. ; PHP call 'ini_set'
  476. ; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.
  477. ; Defining 'extension' will load the corresponding shared extension from
  478. ; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
  479. ; overwrite previously defined php.ini values, but will append the new value
  480. ; instead.
  481. ; Note: path INI options can be relative and will be expanded with the prefix
  482. ; (pool, global or /usr/local/php)
  483. ; Default Value: nothing is defined by default except the values in php.ini and
  484. ; specified at startup with the -d argument
  485. ;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
  486. ;php_flag[display_errors] = off
  487. ;php_admin_value[error_log] = /var/log/fpm-php.www.log
  488. ;php_admin_flag[log_errors] = on
  489. ;php_admin_value[memory_limit] = 32M
  490. EOF
  491. cat > php.ini <<-'EOF'
  492. [PHP]
  493. ;;;;;;;;;;;;;;;;;;;
  494. ; About php.ini ;
  495. ;;;;;;;;;;;;;;;;;;;
  496. ; PHP's initialization file, generally called php.ini, is responsible for
  497. ; configuring many of the aspects of PHP's behavior.
  498. ; PHP attempts to find and load this configuration from a number of locations.
  499. ; The following is a summary of its search order:
  500. ; 1. SAPI module specific location.
  501. ; 2. The PHPRC environment variable. (As of PHP 5.2.0)
  502. ; 3. A number of predefined registry keys on Windows (As of PHP 5.2.0)
  503. ; 4. Current working directory (except CLI)
  504. ; 5. The web server's directory (for SAPI modules), or directory of PHP
  505. ; (otherwise in Windows)
  506. ; 6. The directory from the --with-config-file-path compile time option, or the
  507. ; Windows directory (C:\windows or C:\winnt)
  508. ; See the PHP docs for more specific information.
  509. ; http://php.net/configuration.file
  510. ; The syntax of the file is extremely simple. Whitespace and lines
  511. ; beginning with a semicolon are silently ignored (as you probably guessed).
  512. ; Section headers (e.g. [Foo]) are also silently ignored, even though
  513. ; they might mean something in the future.
  514. ; Directives following the section heading [PATH=/www/mysite] only
  515. ; apply to PHP files in the /www/mysite directory. Directives
  516. ; following the section heading [HOST=www.example.com] only apply to
  517. ; PHP files served from www.example.com. Directives set in these
  518. ; special sections cannot be overridden by user-defined INI files or
  519. ; at runtime. Currently, [PATH=] and [HOST=] sections only work under
  520. ; CGI/FastCGI.
  521. ; http://php.net/ini.sections
  522. ; Directives are specified using the following syntax:
  523. ; directive = value
  524. ; Directive names are *case sensitive* - foo=bar is different from FOO=bar.
  525. ; Directives are variables used to configure PHP or PHP extensions.
  526. ; There is no name validation. If PHP can't find an expected
  527. ; directive because it is not set or is mistyped, a default value will be used.
  528. ; The value can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one
  529. ; of the INI constants (On, Off, True, False, Yes, No and None) or an expression
  530. ; (e.g. E_ALL & ~E_NOTICE), a quoted string ("bar"), or a reference to a
  531. ; previously set variable or directive (e.g. ${foo})
  532. ; Expressions in the INI file are limited to bitwise operators and parentheses:
  533. ; | bitwise OR
  534. ; ^ bitwise XOR
  535. ; & bitwise AND
  536. ; ~ bitwise NOT
  537. ; ! boolean NOT
  538. ; Boolean flags can be turned on using the values 1, On, True or Yes.
  539. ; They can be turned off using the values 0, Off, False or No.
  540. ; An empty string can be denoted by simply not writing anything after the equal
  541. ; sign, or by using the None keyword:
  542. ; foo = ; sets foo to an empty string
  543. ; foo = None ; sets foo to an empty string
  544. ; foo = "None" ; sets foo to the string 'None'
  545. ; If you use constants in your value, and these constants belong to a
  546. ; dynamically loaded extension (either a PHP extension or a Zend extension),
  547. ; you may only use these constants *after* the line that loads the extension.
  548. ;;;;;;;;;;;;;;;;;;;
  549. ; About this file ;
  550. ;;;;;;;;;;;;;;;;;;;
  551. ; PHP comes packaged with two INI files. One that is recommended to be used
  552. ; in production environments and one that is recommended to be used in
  553. ; development environments.
  554. ; php.ini-production contains settings which hold security, performance and
  555. ; best practices at its core. But please be aware, these settings may break
  556. ; compatibility with older or less security conscience applications. We
  557. ; recommending using the production ini in production and testing environments.
  558. ; php.ini-development is very similar to its production variant, except it is
  559. ; much more verbose when it comes to errors. We recommend using the
  560. ; development version only in development environments, as errors shown to
  561. ; application users can inadvertently leak otherwise secure information.
  562. ; This is php.ini-production INI file.
  563. ;;;;;;;;;;;;;;;;;;;
  564. ; Quick Reference ;
  565. ;;;;;;;;;;;;;;;;;;;
  566. ; The following are all the settings which are different in either the production
  567. ; or development versions of the INIs with respect to PHP's default behavior.
  568. ; Please see the actual settings later in the document for more details as to why
  569. ; we recommend these changes in PHP's behavior.
  570. ; display_errors
  571. ; Default Value: On
  572. ; Development Value: On
  573. ; Production Value: Off
  574. ; display_startup_errors
  575. ; Default Value: Off
  576. ; Development Value: On
  577. ; Production Value: Off
  578. ; error_reporting
  579. ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
  580. ; Development Value: E_ALL
  581. ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
  582. ; html_errors
  583. ; Default Value: On
  584. ; Development Value: On
  585. ; Production value: On
  586. ; log_errors
  587. ; Default Value: Off
  588. ; Development Value: On
  589. ; Production Value: On
  590. ; max_input_time
  591. ; Default Value: -1 (Unlimited)
  592. ; Development Value: 60 (60 seconds)
  593. ; Production Value: 60 (60 seconds)
  594. ; output_buffering
  595. ; Default Value: Off
  596. ; Development Value: 4096
  597. ; Production Value: 4096
  598. ; register_argc_argv
  599. ; Default Value: On
  600. ; Development Value: Off
  601. ; Production Value: Off
  602. ; request_order
  603. ; Default Value: None
  604. ; Development Value: "GP"
  605. ; Production Value: "GP"
  606. ; session.gc_divisor
  607. ; Default Value: 100
  608. ; Development Value: 1000
  609. ; Production Value: 1000
  610. ; session.hash_bits_per_character
  611. ; Default Value: 4
  612. ; Development Value: 5
  613. ; Production Value: 5
  614. ; short_open_tag
  615. ; Default Value: On
  616. ; Development Value: Off
  617. ; Production Value: Off
  618. ; track_errors
  619. ; Default Value: Off
  620. ; Development Value: On
  621. ; Production Value: Off
  622. ; url_rewriter.tags
  623. ; Default Value: "a=href,area=href,frame=src,form=,fieldset="
  624. ; Development Value: "a=href,area=href,frame=src,input=src,form=fakeentry"
  625. ; Production Value: "a=href,area=href,frame=src,input=src,form=fakeentry"
  626. ; variables_order
  627. ; Default Value: "EGPCS"
  628. ; Development Value: "GPCS"
  629. ; Production Value: "GPCS"
  630. ;;;;;;;;;;;;;;;;;;;;
  631. ; php.ini Options ;
  632. ;;;;;;;;;;;;;;;;;;;;
  633. ; Name for user-defined php.ini (.htaccess) files. Default is ".user.ini"
  634. ;user_ini.filename = ".user.ini"
  635. ; To disable this feature set this option to empty value
  636. ;user_ini.filename =
  637. ; TTL for user-defined php.ini files (time-to-live) in seconds. Default is 300 seconds (5 minutes)
  638. ;user_ini.cache_ttl = 300
  639. ;;;;;;;;;;;;;;;;;;;;
  640. ; Language Options ;
  641. ;;;;;;;;;;;;;;;;;;;;
  642. ; Enable the PHP scripting language engine under Apache.
  643. ; http://php.net/engine
  644. engine = On
  645. ; This directive determines whether or not PHP will recognize code between
  646. ; <? and ?> tags as PHP source which should be processed as such. It is
  647. ; generally recommended that <?php and ?> should be used and that this feature
  648. ; should be disabled, as enabling it may result in issues when generating XML
  649. ; documents, however this remains supported for backward compatibility reasons.
  650. ; Note that this directive does not control the <?= shorthand tag, which can be
  651. ; used regardless of this directive.
  652. ; Default Value: On
  653. ; Development Value: Off
  654. ; Production Value: Off
  655. ; http://php.net/short-open-tag
  656. short_open_tag = Off
  657. ; Allow ASP-style <% %> tags.
  658. ; http://php.net/asp-tags
  659. asp_tags = Off
  660. ; The number of significant digits displayed in floating point numbers.
  661. ; http://php.net/precision
  662. precision = 14
  663. ; Output buffering is a mechanism for controlling how much output data
  664. ; (excluding headers and cookies) PHP should keep internally before pushing that
  665. ; data to the client. If your application's output exceeds this setting, PHP
  666. ; will send that data in chunks of roughly the size you specify.
  667. ; Turning on this setting and managing its maximum buffer size can yield some
  668. ; interesting side-effects depending on your application and web server.
  669. ; You may be able to send headers and cookies after you've already sent output
  670. ; through print or echo. You also may see performance benefits if your server is
  671. ; emitting less packets due to buffered output versus PHP streaming the output
  672. ; as it gets it. On production servers, 4096 bytes is a good setting for performance
  673. ; reasons.
  674. ; Note: Output buffering can also be controlled via Output Buffering Control
  675. ; functions.
  676. ; Possible Values:
  677. ; On = Enabled and buffer is unlimited. (Use with caution)
  678. ; Off = Disabled
  679. ; Integer = Enables the buffer and sets its maximum size in bytes.
  680. ; Note: This directive is hardcoded to Off for the CLI SAPI
  681. ; Default Value: Off
  682. ; Development Value: 4096
  683. ; Production Value: 4096
  684. ; http://php.net/output-buffering
  685. output_buffering = 4096
  686. ; You can redirect all of the output of your scripts to a function. For
  687. ; example, if you set output_handler to "mb_output_handler", character
  688. ; encoding will be transparently converted to the specified encoding.
  689. ; Setting any output handler automatically turns on output buffering.
  690. ; Note: People who wrote portable scripts should not depend on this ini
  691. ; directive. Instead, explicitly set the output handler using ob_start().
  692. ; Using this ini directive may cause problems unless you know what script
  693. ; is doing.
  694. ; Note: You cannot use both "mb_output_handler" with "ob_iconv_handler"
  695. ; and you cannot use both "ob_gzhandler" and "zlib.output_compression".
  696. ; Note: output_handler must be empty if this is set 'On' !!!!
  697. ; Instead you must use zlib.output_handler.
  698. ; http://php.net/output-handler
  699. ;output_handler =
  700. ; Transparent output compression using the zlib library
  701. ; Valid values for this option are 'off', 'on', or a specific buffer size
  702. ; to be used for compression (default is 4KB)
  703. ; Note: Resulting chunk size may vary due to nature of compression. PHP
  704. ; outputs chunks that are few hundreds bytes each as a result of
  705. ; compression. If you prefer a larger chunk size for better
  706. ; performance, enable output_buffering in addition.
  707. ; Note: You need to use zlib.output_handler instead of the standard
  708. ; output_handler, or otherwise the output will be corrupted.
  709. ; http://php.net/zlib.output-compression
  710. zlib.output_compression = Off
  711. ; http://php.net/zlib.output-compression-level
  712. ;zlib.output_compression_level = -1
  713. ; You cannot specify additional output handlers if zlib.output_compression
  714. ; is activated here. This setting does the same as output_handler but in
  715. ; a different order.
  716. ; http://php.net/zlib.output-handler
  717. ;zlib.output_handler =
  718. ; Implicit flush tells PHP to tell the output layer to flush itself
  719. ; automatically after every output block. This is equivalent to calling the
  720. ; PHP function flush() after each and every call to print() or echo() and each
  721. ; and every HTML block. Turning this option on has serious performance
  722. ; implications and is generally recommended for debugging purposes only.
  723. ; http://php.net/implicit-flush
  724. ; Note: This directive is hardcoded to On for the CLI SAPI
  725. implicit_flush = Off
  726. ; The unserialize callback function will be called (with the undefined class'
  727. ; name as parameter), if the unserializer finds an undefined class
  728. ; which should be instantiated. A warning appears if the specified function is
  729. ; not defined, or if the function doesn't include/implement the missing class.
  730. ; So only set this entry, if you really want to implement such a
  731. ; callback-function.
  732. unserialize_callback_func =
  733. ; When floats & doubles are serialized store serialize_precision significant
  734. ; digits after the floating point. The default value ensures that when floats
  735. ; are decoded with unserialize, the data will remain the same.
  736. serialize_precision = 17
  737. ; open_basedir, if set, limits all file operations to the defined directory
  738. ; and below. This directive makes most sense if used in a per-directory
  739. ; or per-virtualhost web server configuration file.
  740. ; http://php.net/open-basedir
  741. ;open_basedir =
  742. ; This directive allows you to disable certain functions for security reasons.
  743. ; It receives a comma-delimited list of function names.
  744. ; http://php.net/disable-functions
  745. disable_functions =
  746. ; This directive allows you to disable certain classes for security reasons.
  747. ; It receives a comma-delimited list of class names.
  748. ; http://php.net/disable-classes
  749. disable_classes =
  750. ; Colors for Syntax Highlighting mode. Anything that's acceptable in
  751. ; <span style="color: ???????"> would work.
  752. ; http://php.net/syntax-highlighting
  753. ;highlight.string = #DD0000
  754. ;highlight.comment = #FF9900
  755. ;highlight.keyword = #007700
  756. ;highlight.default = #0000BB
  757. ;highlight.html = #000000
  758. ; If enabled, the request will be allowed to complete even if the user aborts
  759. ; the request. Consider enabling it if executing long requests, which may end up
  760. ; being interrupted by the user or a browser timing out. PHP's default behavior
  761. ; is to disable this feature.
  762. ; http://php.net/ignore-user-abort
  763. ;ignore_user_abort = On
  764. ; Determines the size of the realpath cache to be used by PHP. This value should
  765. ; be increased on systems where PHP opens many files to reflect the quantity of
  766. ; the file operations performed.
  767. ; http://php.net/realpath-cache-size
  768. ;realpath_cache_size = 16k
  769. ; Duration of time, in seconds for which to cache realpath information for a given
  770. ; file or directory. For systems with rarely changing files, consider increasing this
  771. ; value.
  772. ; http://php.net/realpath-cache-ttl
  773. ;realpath_cache_ttl = 120
  774. ; Enables or disables the circular reference collector.
  775. ; http://php.net/zend.enable-gc
  776. zend.enable_gc = On
  777. ; If enabled, scripts may be written in encodings that are incompatible with
  778. ; the scanner. CP936, Big5, CP949 and Shift_JIS are the examples of such
  779. ; encodings. To use this feature, mbstring extension must be enabled.
  780. ; Default: Off
  781. ;zend.multibyte = Off
  782. ; Allows to set the default encoding for the scripts. This value will be used
  783. ; unless "declare(encoding=...)" directive appears at the top of the script.
  784. ; Only affects if zend.multibyte is set.
  785. ; Default: ""
  786. ;zend.script_encoding =
  787. ;;;;;;;;;;;;;;;;;
  788. ; Miscellaneous ;
  789. ;;;;;;;;;;;;;;;;;
  790. ; Decides whether PHP may expose the fact that it is installed on the server
  791. ; (e.g. by adding its signature to the Web server header). It is no security
  792. ; threat in any way, but it makes it possible to determine whether you use PHP
  793. ; on your server or not.
  794. ; http://php.net/expose-php
  795. expose_php = On
  796. ;;;;;;;;;;;;;;;;;;;
  797. ; Resource Limits ;
  798. ;;;;;;;;;;;;;;;;;;;
  799. ; Maximum execution time of each script, in seconds
  800. ; http://php.net/max-execution-time
  801. ; Note: This directive is hardcoded to 0 for the CLI SAPI
  802. max_execution_time = 30
  803. ; Maximum amount of time each script may spend parsing request data. It's a good
  804. ; idea to limit this time on productions servers in order to eliminate unexpectedly
  805. ; long running scripts.
  806. ; Note: This directive is hardcoded to -1 for the CLI SAPI
  807. ; Default Value: -1 (Unlimited)
  808. ; Development Value: 60 (60 seconds)
  809. ; Production Value: 60 (60 seconds)
  810. ; http://php.net/max-input-time
  811. max_input_time = 60
  812. ; Maximum input variable nesting level
  813. ; http://php.net/max-input-nesting-level
  814. ;max_input_nesting_level = 64
  815. ; How many GET/POST/COOKIE input variables may be accepted
  816. ; max_input_vars = 1000
  817. ; Maximum amount of memory a script may consume (128MB)
  818. ; http://php.net/memory-limit
  819. memory_limit = 128M
  820. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  821. ; Error handling and logging ;
  822. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  823. ; This directive informs PHP of which errors, warnings and notices you would like
  824. ; it to take action for. The recommended way of setting values for this
  825. ; directive is through the use of the error level constants and bitwise
  826. ; operators. The error level constants are below here for convenience as well as
  827. ; some common settings and their meanings.
  828. ; By default, PHP is set to take action on all errors, notices and warnings EXCEPT
  829. ; those related to E_NOTICE and E_STRICT, which together cover best practices and
  830. ; recommended coding standards in PHP. For performance reasons, this is the
  831. ; recommend error reporting setting. Your production server shouldn't be wasting
  832. ; resources complaining about best practices and coding standards. That's what
  833. ; development servers and development settings are for.
  834. ; Note: The php.ini-development file has this setting as E_ALL. This
  835. ; means it pretty much reports everything which is exactly what you want during
  836. ; development and early testing.
  837. ;
  838. ; Error Level Constants:
  839. ; E_ALL - All errors and warnings (includes E_STRICT as of PHP 5.4.0)
  840. ; E_ERROR - fatal run-time errors
  841. ; E_RECOVERABLE_ERROR - almost fatal run-time errors
  842. ; E_WARNING - run-time warnings (non-fatal errors)
  843. ; E_PARSE - compile-time parse errors
  844. ; E_NOTICE - run-time notices (these are warnings which often result
  845. ; from a bug in your code, but it's possible that it was
  846. ; intentional (e.g., using an uninitialized variable and
  847. ; relying on the fact it is automatically initialized to an
  848. ; empty string)
  849. ; E_STRICT - run-time notices, enable to have PHP suggest changes
  850. ; to your code which will ensure the best interoperability
  851. ; and forward compatibility of your code
  852. ; E_CORE_ERROR - fatal errors that occur during PHP's initial startup
  853. ; E_CORE_WARNING - warnings (non-fatal errors) that occur during PHP's
  854. ; initial startup
  855. ; E_COMPILE_ERROR - fatal compile-time errors
  856. ; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
  857. ; E_USER_ERROR - user-generated error message
  858. ; E_USER_WARNING - user-generated warning message
  859. ; E_USER_NOTICE - user-generated notice message
  860. ; E_DEPRECATED - warn about code that will not work in future versions
  861. ; of PHP
  862. ; E_USER_DEPRECATED - user-generated deprecation warnings
  863. ;
  864. ; Common Values:
  865. ; E_ALL (Show all errors, warnings and notices including coding standards.)
  866. ; E_ALL & ~E_NOTICE (Show all errors, except for notices)
  867. ; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
  868. ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
  869. ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
  870. ; Development Value: E_ALL
  871. ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
  872. ; http://php.net/error-reporting
  873. error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
  874. ; This directive controls whether or not and where PHP will output errors,
  875. ; notices and warnings too. Error output is very useful during development, but
  876. ; it could be very dangerous in production environments. Depending on the code
  877. ; which is triggering the error, sensitive information could potentially leak
  878. ; out of your application such as database usernames and passwords or worse.
  879. ; For production environments, we recommend logging errors rather than
  880. ; sending them to STDOUT.
  881. ; Possible Values:
  882. ; Off = Do not display any errors
  883. ; stderr = Display errors to STDERR (affects only CGI/CLI binaries!)
  884. ; On or stdout = Display errors to STDOUT
  885. ; Default Value: On
  886. ; Development Value: On
  887. ; Production Value: Off
  888. ; http://php.net/display-errors
  889. display_errors = Off
  890. ; The display of errors which occur during PHP's startup sequence are handled
  891. ; separately from display_errors. PHP's default behavior is to suppress those
  892. ; errors from clients. Turning the display of startup errors on can be useful in
  893. ; debugging configuration problems. We strongly recommend you
  894. ; set this to 'off' for production servers.
  895. ; Default Value: Off
  896. ; Development Value: On
  897. ; Production Value: Off
  898. ; http://php.net/display-startup-errors
  899. display_startup_errors = Off
  900. ; Besides displaying errors, PHP can also log errors to locations such as a
  901. ; server-specific log, STDERR, or a location specified by the error_log
  902. ; directive found below. While errors should not be displayed on productions
  903. ; servers they should still be monitored and logging is a great way to do that.
  904. ; Default Value: Off
  905. ; Development Value: On
  906. ; Production Value: On
  907. ; http://php.net/log-errors
  908. log_errors = On
  909. ; Set maximum length of log_errors. In error_log information about the source is
  910. ; added. The default is 1024 and 0 allows to not apply any maximum length at all.
  911. ; http://php.net/log-errors-max-len
  912. log_errors_max_len = 1024
  913. ; Do not log repeated messages. Repeated errors must occur in same file on same
  914. ; line unless ignore_repeated_source is set true.
  915. ; http://php.net/ignore-repeated-errors
  916. ignore_repeated_errors = Off
  917. ; Ignore source of message when ignoring repeated messages. When this setting
  918. ; is On you will not log errors with repeated messages from different files or
  919. ; source lines.
  920. ; http://php.net/ignore-repeated-source
  921. ignore_repeated_source = Off
  922. ; If this parameter is set to Off, then memory leaks will not be shown (on
  923. ; stdout or in the log). This has only effect in a debug compile, and if
  924. ; error reporting includes E_WARNING in the allowed list
  925. ; http://php.net/report-memleaks
  926. report_memleaks = On
  927. ; This setting is on by default.
  928. ;report_zend_debug = 0
  929. ; Store the last error/warning message in $php_errormsg (boolean). Setting this value
  930. ; to On can assist in debugging and is appropriate for development servers. It should
  931. ; however be disabled on production servers.
  932. ; Default Value: Off
  933. ; Development Value: On
  934. ; Production Value: Off
  935. ; http://php.net/track-errors
  936. track_errors = Off
  937. ; Turn off normal error reporting and emit XML-RPC error XML
  938. ; http://php.net/xmlrpc-errors
  939. ;xmlrpc_errors = 0
  940. ; An XML-RPC faultCode
  941. ;xmlrpc_error_number = 0
  942. ; When PHP displays or logs an error, it has the capability of formatting the
  943. ; error message as HTML for easier reading. This directive controls whether
  944. ; the error message is formatted as HTML or not.
  945. ; Note: This directive is hardcoded to Off for the CLI SAPI
  946. ; Default Value: On
  947. ; Development Value: On
  948. ; Production value: On
  949. ; http://php.net/html-errors
  950. html_errors = On
  951. ; If html_errors is set to On *and* docref_root is not empty, then PHP
  952. ; produces clickable error messages that direct to a page describing the error
  953. ; or function causing the error in detail.
  954. ; You can download a copy of the PHP manual from http://php.net/docs
  955. ; and change docref_root to the base URL of your local copy including the
  956. ; leading '/'. You must also specify the file extension being used including
  957. ; the dot. PHP's default behavior is to leave these settings empty, in which
  958. ; case no links to documentation are generated.
  959. ; Note: Never use this feature for production boxes.
  960. ; http://php.net/docref-root
  961. ; Examples
  962. ;docref_root = "/phpmanual/"
  963. ; http://php.net/docref-ext
  964. ;docref_ext = .html
  965. ; String to output before an error message. PHP's default behavior is to leave
  966. ; this setting blank.
  967. ; http://php.net/error-prepend-string
  968. ; Example:
  969. ;error_prepend_string = "<span style='color: #ff0000'>"
  970. ; String to output after an error message. PHP's default behavior is to leave
  971. ; this setting blank.
  972. ; http://php.net/error-append-string
  973. ; Example:
  974. ;error_append_string = "</span>"
  975. ; Log errors to specified file. PHP's default behavior is to leave this value
  976. ; empty.
  977. ; http://php.net/error-log
  978. ; Example:
  979. ;error_log = php_errors.log
  980. ; Log errors to syslog (Event Log on Windows).
  981. ;error_log = syslog
  982. ;windows.show_crt_warning
  983. ; Default value: 0
  984. ; Development value: 0
  985. ; Production value: 0
  986. ;;;;;;;;;;;;;;;;;
  987. ; Data Handling ;
  988. ;;;;;;;;;;;;;;;;;
  989. ; The separator used in PHP generated URLs to separate arguments.
  990. ; PHP's default setting is "&".
  991. ; http://php.net/arg-separator.output
  992. ; Example:
  993. ;arg_separator.output = "&amp;"
  994. ; List of separator(s) used by PHP to parse input URLs into variables.
  995. ; PHP's default setting is "&".
  996. ; NOTE: Every character in this directive is considered as separator!
  997. ; http://php.net/arg-separator.input
  998. ; Example:
  999. ;arg_separator.input = ";&"
  1000. ; This directive determines which super global arrays are registered when PHP
  1001. ; starts up. G,P,C,E & S are abbreviations for the following respective super
  1002. ; globals: GET, POST, COOKIE, ENV and SERVER. There is a performance penalty
  1003. ; paid for the registration of these arrays and because ENV is not as commonly
  1004. ; used as the others, ENV is not recommended on productions servers. You
  1005. ; can still get access to the environment variables through getenv() should you
  1006. ; need to.
  1007. ; Default Value: "EGPCS"
  1008. ; Development Value: "GPCS"
  1009. ; Production Value: "GPCS";
  1010. ; http://php.net/variables-order
  1011. variables_order = "GPCS"
  1012. ; This directive determines which super global data (G,P & C) should be
  1013. ; registered into the super global array REQUEST. If so, it also determines
  1014. ; the order in which that data is registered. The values for this directive
  1015. ; are specified in the same manner as the variables_order directive,
  1016. ; EXCEPT one. Leaving this value empty will cause PHP to use the value set
  1017. ; in the variables_order directive. It does not mean it will leave the super
  1018. ; globals array REQUEST empty.
  1019. ; Default Value: None
  1020. ; Development Value: "GP"
  1021. ; Production Value: "GP"
  1022. ; http://php.net/request-order
  1023. request_order = "GP"
  1024. ; This directive determines whether PHP registers $argv & $argc each time it
  1025. ; runs. $argv contains an array of all the arguments passed to PHP when a script
  1026. ; is invoked. $argc contains an integer representing the number of arguments
  1027. ; that were passed when the script was invoked. These arrays are extremely
  1028. ; useful when running scripts from the command line. When this directive is
  1029. ; enabled, registering these variables consumes CPU cycles and memory each time
  1030. ; a script is executed. For performance reasons, this feature should be disabled
  1031. ; on production servers.
  1032. ; Note: This directive is hardcoded to On for the CLI SAPI
  1033. ; Default Value: On
  1034. ; Development Value: Off
  1035. ; Production Value: Off
  1036. ; http://php.net/register-argc-argv
  1037. register_argc_argv = Off
  1038. ; When enabled, the ENV, REQUEST and SERVER variables are created when they're
  1039. ; first used (Just In Time) instead of when the script starts. If these
  1040. ; variables are not used within a script, having this directive on will result
  1041. ; in a performance gain. The PHP directive register_argc_argv must be disabled
  1042. ; for this directive to have any affect.
  1043. ; http://php.net/auto-globals-jit
  1044. auto_globals_jit = On
  1045. ; Whether PHP will read the POST data.
  1046. ; This option is enabled by default.
  1047. ; Most likely, you won't want to disable this option globally. It causes $_POST
  1048. ; and $_FILES to always be empty; the only way you will be able to read the
  1049. ; POST data will be through the php://input stream wrapper. This can be useful
  1050. ; to proxy requests or to process the POST data in a memory efficient fashion.
  1051. ; http://php.net/enable-post-data-reading
  1052. ;enable_post_data_reading = Off
  1053. ; Maximum size of POST data that PHP will accept.
  1054. ; Its value may be 0 to disable the limit. It is ignored if POST data reading
  1055. ; is disabled through enable_post_data_reading.
  1056. ; http://php.net/post-max-size
  1057. post_max_size = 8M
  1058. ; Automatically add files before PHP document.
  1059. ; http://php.net/auto-prepend-file
  1060. auto_prepend_file =
  1061. ; Automatically add files after PHP document.
  1062. ; http://php.net/auto-append-file
  1063. auto_append_file =
  1064. ; By default, PHP will output a media type using the Content-Type header. To
  1065. ; disable this, simply set it to be empty.
  1066. ;
  1067. ; PHP's built-in default media type is set to text/html.
  1068. ; http://php.net/default-mimetype
  1069. default_mimetype = "text/html"
  1070. ; PHP's default character set is set to UTF-8.
  1071. ; http://php.net/default-charset
  1072. default_charset = "UTF-8"
  1073. ; PHP internal character encoding is set to empty.
  1074. ; If empty, default_charset is used.
  1075. ; http://php.net/internal-encoding
  1076. ;internal_encoding =
  1077. ; PHP input character encoding is set to empty.
  1078. ; If empty, default_charset is used.
  1079. ; http://php.net/input-encoding
  1080. ;input_encoding =
  1081. ; PHP output character encoding is set to empty.
  1082. ; If empty, default_charset is used.
  1083. ; See also output_buffer.
  1084. ; http://php.net/output-encoding
  1085. ;output_encoding =
  1086. ; Always populate the $HTTP_RAW_POST_DATA variable. PHP's default behavior is
  1087. ; to disable this feature and it will be removed in a future version.
  1088. ; If post reading is disabled through enable_post_data_reading,
  1089. ; $HTTP_RAW_POST_DATA is *NOT* populated.
  1090. ; http://php.net/always-populate-raw-post-data
  1091. ;always_populate_raw_post_data = -1
  1092. ;;;;;;;;;;;;;;;;;;;;;;;;;
  1093. ; Paths and Directories ;
  1094. ;;;;;;;;;;;;;;;;;;;;;;;;;
  1095. ; UNIX: "/path1:/path2"
  1096. ;include_path = ".:/php/includes"
  1097. ;
  1098. ; Windows: "\path1;\path2"
  1099. ;include_path = ".;c:\php\includes"
  1100. ;
  1101. ; PHP's default setting for include_path is ".;/path/to/php/pear"
  1102. ; http://php.net/include-path
  1103. ; The root of the PHP pages, used only if nonempty.
  1104. ; if PHP was not compiled with FORCE_REDIRECT, you SHOULD set doc_root
  1105. ; if you are running php as a CGI under any web server (other than IIS)
  1106. ; see documentation for security issues. The alternate is to use the
  1107. ; cgi.force_redirect configuration below
  1108. ; http://php.net/doc-root
  1109. doc_root =
  1110. ; The directory under which PHP opens the script using /~username used only
  1111. ; if nonempty.
  1112. ; http://php.net/user-dir
  1113. user_dir =
  1114. ; Directory in which the loadable extensions (modules) reside.
  1115. ; http://php.net/extension-dir
  1116. ; extension_dir = "./"
  1117. ; On windows:
  1118. ; extension_dir = "ext"
  1119. ; Directory where the temporary files should be placed.
  1120. ; Defaults to the system default (see sys_get_temp_dir)
  1121. ; sys_temp_dir = "/tmp"
  1122. ; Whether or not to enable the dl() function. The dl() function does NOT work
  1123. ; properly in multithreaded servers, such as IIS or Zeus, and is automatically
  1124. ; disabled on them.
  1125. ; http://php.net/enable-dl
  1126. enable_dl = Off
  1127. ; cgi.force_redirect is necessary to provide security running PHP as a CGI under
  1128. ; most web servers. Left undefined, PHP turns this on by default. You can
  1129. ; turn it off here AT YOUR OWN RISK
  1130. ; **You CAN safely turn this off for IIS, in fact, you MUST.**
  1131. ; http://php.net/cgi.force-redirect
  1132. ;cgi.force_redirect = 1
  1133. ; if cgi.nph is enabled it will force cgi to always sent Status: 200 with
  1134. ; every request. PHP's default behavior is to disable this feature.
  1135. ;cgi.nph = 1
  1136. ; if cgi.force_redirect is turned on, and you are not running under Apache or Netscape
  1137. ; (iPlanet) web servers, you MAY need to set an environment variable name that PHP
  1138. ; will look for to know it is OK to continue execution. Setting this variable MAY
  1139. ; cause security issues, KNOW WHAT YOU ARE DOING FIRST.
  1140. ; http://php.net/cgi.redirect-status-env
  1141. ;cgi.redirect_status_env =
  1142. ; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's
  1143. ; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
  1144. ; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting
  1145. ; this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting
  1146. ; of zero causes PHP to behave as before. Default is 1. You should fix your scripts
  1147. ; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
  1148. ; http://php.net/cgi.fix-pathinfo
  1149. ;cgi.fix_pathinfo=1
  1150. ; if cgi.discard_path is enabled, the PHP CGI binary can safely be placed outside
  1151. ; of the web tree and people will not be able to circumvent .htaccess security.
  1152. ; http://php.net/cgi.dicard-path
  1153. ;cgi.discard_path=1
  1154. ; FastCGI under IIS (on WINNT based OS) supports the ability to impersonate
  1155. ; security tokens of the calling client. This allows IIS to define the
  1156. ; security context that the request runs under. mod_fastcgi under Apache
  1157. ; does not currently support this feature (03/17/2002)
  1158. ; Set to 1 if running under IIS. Default is zero.
  1159. ; http://php.net/fastcgi.impersonate
  1160. ;fastcgi.impersonate = 1
  1161. ; Disable logging through FastCGI connection. PHP's default behavior is to enable
  1162. ; this feature.
  1163. ;fastcgi.logging = 0
  1164. ; cgi.rfc2616_headers configuration option tells PHP what type of headers to
  1165. ; use when sending HTTP response code. If set to 0, PHP sends Status: header that
  1166. ; is supported by Apache. When this option is set to 1, PHP will send
  1167. ; RFC2616 compliant header.
  1168. ; Default is zero.
  1169. ; http://php.net/cgi.rfc2616-headers
  1170. ;cgi.rfc2616_headers = 0
  1171. ; cgi.check_shebang_line controls whether CGI PHP checks for line starting with #!
  1172. ; (shebang) at the top of the running script. This line might be needed if the
  1173. ; script support running both as stand-alone script and via PHP CGI<. PHP in CGI
  1174. ; mode skips this line and ignores its content if this directive is turned on.
  1175. ; http://php.net/cgi.check-shebang-line
  1176. ;cgi.check_shebang_line=1
  1177. ;;;;;;;;;;;;;;;;
  1178. ; File Uploads ;
  1179. ;;;;;;;;;;;;;;;;
  1180. ; Whether to allow HTTP file uploads.
  1181. ; http://php.net/file-uploads
  1182. file_uploads = On
  1183. ; Temporary directory for HTTP uploaded files (will use system default if not
  1184. ; specified).
  1185. ; http://php.net/upload-tmp-dir
  1186. ;upload_tmp_dir =
  1187. ; Maximum allowed size for uploaded files.
  1188. ; http://php.net/upload-max-filesize
  1189. upload_max_filesize = 2M
  1190. ; Maximum number of files that can be uploaded via a single request
  1191. max_file_uploads = 20
  1192. ;;;;;;;;;;;;;;;;;;
  1193. ; Fopen wrappers ;
  1194. ;;;;;;;;;;;;;;;;;;
  1195. ; Whether to allow the treatment of URLs (like http:// or ftp://) as files.
  1196. ; http://php.net/allow-url-fopen
  1197. allow_url_fopen = On
  1198. ; Whether to allow include/require to open URLs (like http:// or ftp://) as files.
  1199. ; http://php.net/allow-url-include
  1200. allow_url_include = Off
  1201. ; Define the anonymous ftp password (your email address). PHP's default setting
  1202. ; for this is empty.
  1203. ; http://php.net/from
  1204. ;from="john@doe.com"
  1205. ; Define the User-Agent string. PHP's default setting for this is empty.
  1206. ; http://php.net/user-agent
  1207. ;user_agent="PHP"
  1208. ; Default timeout for socket based streams (seconds)
  1209. ; http://php.net/default-socket-timeout
  1210. default_socket_timeout = 60
  1211. ; If your scripts have to deal with files from Macintosh systems,
  1212. ; or you are running on a Mac and need to deal with files from
  1213. ; unix or win32 systems, setting this flag will cause PHP to
  1214. ; automatically detect the EOL character in those files so that
  1215. ; fgets() and file() will work regardless of the source of the file.
  1216. ; http://php.net/auto-detect-line-endings
  1217. ;auto_detect_line_endings = Off
  1218. ;;;;;;;;;;;;;;;;;;;;;;
  1219. ; Dynamic Extensions ;
  1220. ;;;;;;;;;;;;;;;;;;;;;;
  1221. ; If you wish to have an extension loaded automatically, use the following
  1222. ; syntax:
  1223. ;
  1224. ; extension=modulename.extension
  1225. ;
  1226. ; For example, on Windows:
  1227. ;
  1228. ; extension=msql.dll
  1229. ;
  1230. ; ... or under UNIX:
  1231. ;
  1232. ; extension=msql.so
  1233. ;
  1234. ; ... or with a path:
  1235. ;
  1236. ; extension=/path/to/extension/msql.so
  1237. ;
  1238. ; If you only provide the name of the extension, PHP will look for it in its
  1239. ; default extension directory.
  1240. ;
  1241. ; Windows Extensions
  1242. ; Note that ODBC support is built in, so no dll is needed for it.
  1243. ; Note that many DLL files are located in the extensions/ (PHP 4) ext/ (PHP 5)
  1244. ; extension folders as well as the separate PECL DLL download (PHP 5).
  1245. ; Be sure to appropriately set the extension_dir directive.
  1246. ;
  1247. ;extension=php_bz2.dll
  1248. ;extension=php_curl.dll
  1249. ;extension=php_fileinfo.dll
  1250. ;extension=php_gd2.dll
  1251. ;extension=php_gettext.dll
  1252. ;extension=php_gmp.dll
  1253. ;extension=php_intl.dll
  1254. ;extension=php_imap.dll
  1255. ;extension=php_interbase.dll
  1256. ;extension=php_ldap.dll
  1257. ;extension=php_mbstring.dll
  1258. ;extension=php_exif.dll ; Must be after mbstring as it depends on it
  1259. ;extension=php_mysql.dll
  1260. ;extension=php_mysqli.dll
  1261. ;extension=php_oci8_12c.dll ; Use with Oracle Database 12c Instant Client
  1262. ;extension=php_openssl.dll
  1263. ;extension=php_pdo_firebird.dll
  1264. ;extension=php_pdo_mysql.dll
  1265. ;extension=php_pdo_oci.dll
  1266. ;extension=php_pdo_odbc.dll
  1267. ;extension=php_pdo_pgsql.dll
  1268. ;extension=php_pdo_sqlite.dll
  1269. ;extension=php_pgsql.dll
  1270. ;extension=php_shmop.dll
  1271. ; The MIBS data available in the PHP distribution must be installed.
  1272. ; See http://www.php.net/manual/en/snmp.installation.php
  1273. ;extension=php_snmp.dll
  1274. ;extension=php_soap.dll
  1275. ;extension=php_sockets.dll
  1276. ;extension=php_sqlite3.dll
  1277. ;extension=php_sybase_ct.dll
  1278. ;extension=php_tidy.dll
  1279. ;extension=php_xmlrpc.dll
  1280. ;extension=php_xsl.dll
  1281. ;;;;;;;;;;;;;;;;;;;
  1282. ; Module Settings ;
  1283. ;;;;;;;;;;;;;;;;;;;
  1284. [CLI Server]
  1285. ; Whether the CLI web server uses ANSI color coding in its terminal output.
  1286. cli_server.color = On
  1287. [Date]
  1288. ; Defines the default timezone used by the date functions
  1289. ; http://php.net/date.timezone
  1290. ;date.timezone =
  1291. ; http://php.net/date.default-latitude
  1292. ;date.default_latitude = 31.7667
  1293. ; http://php.net/date.default-longitude
  1294. ;date.default_longitude = 35.2333
  1295. ; http://php.net/date.sunrise-zenith
  1296. ;date.sunrise_zenith = 90.583333
  1297. ; http://php.net/date.sunset-zenith
  1298. ;date.sunset_zenith = 90.583333
  1299. [filter]
  1300. ; http://php.net/filter.default
  1301. ;filter.default = unsafe_raw
  1302. ; http://php.net/filter.default-flags
  1303. ;filter.default_flags =
  1304. [iconv]
  1305. ; Use of this INI entry is deprecated, use global input_encoding instead.
  1306. ; If empty, default_charset or input_encoding or iconv.input_encoding is used.
  1307. ; The precedence is: default_charset < intput_encoding < iconv.input_encoding
  1308. ;iconv.input_encoding =
  1309. ; Use of this INI entry is deprecated, use global internal_encoding instead.
  1310. ; If empty, default_charset or internal_encoding or iconv.internal_encoding is used.
  1311. ; The precedence is: default_charset < internal_encoding < iconv.internal_encoding
  1312. ;iconv.internal_encoding =
  1313. ; Use of this INI entry is deprecated, use global output_encoding instead.
  1314. ; If empty, default_charset or output_encoding or iconv.output_encoding is used.
  1315. ; The precedence is: default_charset < output_encoding < iconv.output_encoding
  1316. ; To use an output encoding conversion, iconv's output handler must be set
  1317. ; otherwise output encoding conversion cannot be performed.
  1318. ;iconv.output_encoding =
  1319. [intl]
  1320. ;intl.default_locale =
  1321. ; This directive allows you to produce PHP errors when some error
  1322. ; happens within intl functions. The value is the level of the error produced.
  1323. ; Default is 0, which does not produce any errors.
  1324. ;intl.error_level = E_WARNING
  1325. ;intl.use_exceptions = 0
  1326. [sqlite3]
  1327. ;sqlite3.extension_dir =
  1328. [Pcre]
  1329. ;PCRE library backtracking limit.
  1330. ; http://php.net/pcre.backtrack-limit
  1331. ;pcre.backtrack_limit=100000
  1332. ;PCRE library recursion limit.
  1333. ;Please note that if you set this value to a high number you may consume all
  1334. ;the available process stack and eventually crash PHP (due to reaching the
  1335. ;stack size limit imposed by the Operating System).
  1336. ; http://php.net/pcre.recursion-limit
  1337. ;pcre.recursion_limit=100000
  1338. [Pdo]
  1339. ; Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off"
  1340. ; http://php.net/pdo-odbc.connection-pooling
  1341. ;pdo_odbc.connection_pooling=strict
  1342. ;pdo_odbc.db2_instance_name
  1343. [Pdo_mysql]
  1344. ; If mysqlnd is used: Number of cache slots for the internal result set cache
  1345. ; http://php.net/pdo_mysql.cache_size
  1346. pdo_mysql.cache_size = 2000
  1347. ; Default socket name for local MySQL connects. If empty, uses the built-in
  1348. ; MySQL defaults.
  1349. ; http://php.net/pdo_mysql.default-socket
  1350. pdo_mysql.default_socket=
  1351. [Phar]
  1352. ; http://php.net/phar.readonly
  1353. ;phar.readonly = On
  1354. ; http://php.net/phar.require-hash
  1355. ;phar.require_hash = On
  1356. ;phar.cache_list =
  1357. [mail function]
  1358. ; For Win32 only.
  1359. ; http://php.net/smtp
  1360. SMTP = localhost
  1361. ; http://php.net/smtp-port
  1362. smtp_port = 25
  1363. ; For Win32 only.
  1364. ; http://php.net/sendmail-from
  1365. ;sendmail_from = me@example.com
  1366. ; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
  1367. ; http://php.net/sendmail-path
  1368. ;sendmail_path =
  1369. ; Force the addition of the specified parameters to be passed as extra parameters
  1370. ; to the sendmail binary. These parameters will always replace the value of
  1371. ; the 5th parameter to mail().
  1372. ;mail.force_extra_parameters =
  1373. ; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
  1374. mail.add_x_header = On
  1375. ; The path to a log file that will log all mail() calls. Log entries include
  1376. ; the full path of the script, line number, To address and headers.
  1377. ;mail.log =
  1378. ; Log mail to syslog (Event Log on Windows).
  1379. ;mail.log = syslog
  1380. [SQL]
  1381. ; http://php.net/sql.safe-mode
  1382. sql.safe_mode = Off
  1383. [ODBC]
  1384. ; http://php.net/odbc.default-db
  1385. ;odbc.default_db = Not yet implemented
  1386. ; http://php.net/odbc.default-user
  1387. ;odbc.default_user = Not yet implemented
  1388. ; http://php.net/odbc.default-pw
  1389. ;odbc.default_pw = Not yet implemented
  1390. ; Controls the ODBC cursor model.
  1391. ; Default: SQL_CURSOR_STATIC (default).
  1392. ;odbc.default_cursortype
  1393. ; Allow or prevent persistent links.
  1394. ; http://php.net/odbc.allow-persistent
  1395. odbc.allow_persistent = On
  1396. ; Check that a connection is still valid before reuse.
  1397. ; http://php.net/odbc.check-persistent
  1398. odbc.check_persistent = On
  1399. ; Maximum number of persistent links. -1 means no limit.
  1400. ; http://php.net/odbc.max-persistent
  1401. odbc.max_persistent = -1
  1402. ; Maximum number of links (persistent + non-persistent). -1 means no limit.
  1403. ; http://php.net/odbc.max-links
  1404. odbc.max_links = -1
  1405. ; Handling of LONG fields. Returns number of bytes to variables. 0 means
  1406. ; passthru.
  1407. ; http://php.net/odbc.defaultlrl
  1408. odbc.defaultlrl = 4096
  1409. ; Handling of binary data. 0 means passthru, 1 return as is, 2 convert to char.
  1410. ; See the documentation on odbc_binmode and odbc_longreadlen for an explanation
  1411. ; of odbc.defaultlrl and odbc.defaultbinmode
  1412. ; http://php.net/odbc.defaultbinmode
  1413. odbc.defaultbinmode = 1
  1414. ;birdstep.max_links = -1
  1415. [Interbase]
  1416. ; Allow or prevent persistent links.
  1417. ibase.allow_persistent = 1
  1418. ; Maximum number of persistent links. -1 means no limit.
  1419. ibase.max_persistent = -1
  1420. ; Maximum number of links (persistent + non-persistent). -1 means no limit.
  1421. ibase.max_links = -1
  1422. ; Default database name for ibase_connect().
  1423. ;ibase.default_db =
  1424. ; Default username for ibase_connect().
  1425. ;ibase.default_user =
  1426. ; Default password for ibase_connect().
  1427. ;ibase.default_password =
  1428. ; Default charset for ibase_connect().
  1429. ;ibase.default_charset =
  1430. ; Default timestamp format.
  1431. ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
  1432. ; Default date format.
  1433. ibase.dateformat = "%Y-%m-%d"
  1434. ; Default time format.
  1435. ibase.timeformat = "%H:%M:%S"
  1436. [MySQL]
  1437. ; Allow accessing, from PHP's perspective, local files with LOAD DATA statements
  1438. ; http://php.net/mysql.allow_local_infile
  1439. mysql.allow_local_infile = On
  1440. ; Allow or prevent persistent links.
  1441. ; http://php.net/mysql.allow-persistent
  1442. mysql.allow_persistent = On
  1443. ; If mysqlnd is used: Number of cache slots for the internal result set cache
  1444. ; http://php.net/mysql.cache_size
  1445. mysql.cache_size = 2000
  1446. ; Maximum number of persistent links. -1 means no limit.
  1447. ; http://php.net/mysql.max-persistent
  1448. mysql.max_persistent = -1
  1449. ; Maximum number of links (persistent + non-persistent). -1 means no limit.
  1450. ; http://php.net/mysql.max-links
  1451. mysql.max_links = -1
  1452. ; Default port number for mysql_connect(). If unset, mysql_connect() will use
  1453. ; the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/services or the
  1454. ; compile-time value defined MYSQL_PORT (in that order). Win32 will only look
  1455. ; at MYSQL_PORT.
  1456. ; http://php.net/mysql.default-port
  1457. mysql.default_port =
  1458. ; Default socket name for local MySQL connects. If empty, uses the built-in
  1459. ; MySQL defaults.
  1460. ; http://php.net/mysql.default-socket
  1461. mysql.default_socket =
  1462. ; Default host for mysql_connect() (doesn't apply in safe mode).
  1463. ; http://php.net/mysql.default-host
  1464. mysql.default_host =
  1465. ; Default user for mysql_connect() (doesn't apply in safe mode).
  1466. ; http://php.net/mysql.default-user
  1467. mysql.default_user =
  1468. ; Default password for mysql_connect() (doesn't apply in safe mode).
  1469. ; Note that this is generally a *bad* idea to store passwords in this file.
  1470. ; *Any* user with PHP access can run 'echo get_cfg_var("mysql.default_password")
  1471. ; and reveal this password! And of course, any users with read access to this
  1472. ; file will be able to reveal the password as well.
  1473. ; http://php.net/mysql.default-password
  1474. mysql.default_password =
  1475. ; Maximum time (in seconds) for connect timeout. -1 means no limit
  1476. ; http://php.net/mysql.connect-timeout
  1477. mysql.connect_timeout = 60
  1478. ; Trace mode. When trace_mode is active (=On), warnings for table/index scans and
  1479. ; SQL-Errors will be displayed.
  1480. ; http://php.net/mysql.trace-mode
  1481. mysql.trace_mode = Off
  1482. [MySQLi]
  1483. ; Maximum number of persistent links. -1 means no limit.
  1484. ; http://php.net/mysqli.max-persistent
  1485. mysqli.max_persistent = -1
  1486. ; Allow accessing, from PHP's perspective, local files with LOAD DATA statements
  1487. ; http://php.net/mysqli.allow_local_infile
  1488. ;mysqli.allow_local_infile = On
  1489. ; Allow or prevent persistent links.
  1490. ; http://php.net/mysqli.allow-persistent
  1491. mysqli.allow_persistent = On
  1492. ; Maximum number of links. -1 means no limit.
  1493. ; http://php.net/mysqli.max-links
  1494. mysqli.max_links = -1
  1495. ; If mysqlnd is used: Number of cache slots for the internal result set cache
  1496. ; http://php.net/mysqli.cache_size
  1497. mysqli.cache_size = 2000
  1498. ; Default port number for mysqli_connect(). If unset, mysqli_connect() will use
  1499. ; the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/services or the
  1500. ; compile-time value defined MYSQL_PORT (in that order). Win32 will only look
  1501. ; at MYSQL_PORT.
  1502. ; http://php.net/mysqli.default-port
  1503. mysqli.default_port = 3306
  1504. ; Default socket name for local MySQL connects. If empty, uses the built-in
  1505. ; MySQL defaults.
  1506. ; http://php.net/mysqli.default-socket
  1507. mysqli.default_socket =
  1508. ; Default host for mysql_connect() (doesn't apply in safe mode).
  1509. ; http://php.net/mysqli.default-host
  1510. mysqli.default_host =
  1511. ; Default user for mysql_connect() (doesn't apply in safe mode).
  1512. ; http://php.net/mysqli.default-user
  1513. mysqli.default_user =
  1514. ; Default password for mysqli_connect() (doesn't apply in safe mode).
  1515. ; Note that this is generally a *bad* idea to store passwords in this file.
  1516. ; *Any* user with PHP access can run 'echo get_cfg_var("mysqli.default_pw")
  1517. ; and reveal this password! And of course, any users with read access to this
  1518. ; file will be able to reveal the password as well.
  1519. ; http://php.net/mysqli.default-pw
  1520. mysqli.default_pw =
  1521. ; Allow or prevent reconnect
  1522. mysqli.reconnect = Off
  1523. [mysqlnd]
  1524. ; Enable / Disable collection of general statistics by mysqlnd which can be
  1525. ; used to tune and monitor MySQL operations.
  1526. ; http://php.net/mysqlnd.collect_statistics
  1527. mysqlnd.collect_statistics = On
  1528. ; Enable / Disable collection of memory usage statistics by mysqlnd which can be
  1529. ; used to tune and monitor MySQL operations.
  1530. ; http://php.net/mysqlnd.collect_memory_statistics
  1531. mysqlnd.collect_memory_statistics = Off
  1532. ; Records communication from all extensions using mysqlnd to the specified log
  1533. ; file.
  1534. ; http://php.net/mysqlnd.debug
  1535. ;mysqlnd.debug =
  1536. ; Defines which queries will be logged.
  1537. ; http://php.net/mysqlnd.log_mask
  1538. ;mysqlnd.log_mask = 0
  1539. ; Default size of the mysqlnd memory pool, which is used by result sets.
  1540. ; http://php.net/mysqlnd.mempool_default_size
  1541. ;mysqlnd.mempool_default_size = 16000
  1542. ; Size of a pre-allocated buffer used when sending commands to MySQL in bytes.
  1543. ; http://php.net/mysqlnd.net_cmd_buffer_size
  1544. ;mysqlnd.net_cmd_buffer_size = 2048
  1545. ; Size of a pre-allocated buffer used for reading data sent by the server in
  1546. ; bytes.
  1547. ; http://php.net/mysqlnd.net_read_buffer_size
  1548. ;mysqlnd.net_read_buffer_size = 32768
  1549. ; Timeout for network requests in seconds.
  1550. ; http://php.net/mysqlnd.net_read_timeout
  1551. ;mysqlnd.net_read_timeout = 31536000
  1552. ; SHA-256 Authentication Plugin related. File with the MySQL server public RSA
  1553. ; key.
  1554. ; http://php.net/mysqlnd.sha256_server_public_key
  1555. ;mysqlnd.sha256_server_public_key =
  1556. [OCI8]
  1557. ; Connection: Enables privileged connections using external
  1558. ; credentials (OCI_SYSOPER, OCI_SYSDBA)
  1559. ; http://php.net/oci8.privileged-connect
  1560. ;oci8.privileged_connect = Off
  1561. ; Connection: The maximum number of persistent OCI8 connections per
  1562. ; process. Using -1 means no limit.
  1563. ; http://php.net/oci8.max-persistent
  1564. ;oci8.max_persistent = -1
  1565. ; Connection: The maximum number of seconds a process is allowed to
  1566. ; maintain an idle persistent connection. Using -1 means idle
  1567. ; persistent connections will be maintained forever.
  1568. ; http://php.net/oci8.persistent-timeout
  1569. ;oci8.persistent_timeout = -1
  1570. ; Connection: The number of seconds that must pass before issuing a
  1571. ; ping during oci_pconnect() to check the connection validity. When
  1572. ; set to 0, each oci_pconnect() will cause a ping. Using -1 disables
  1573. ; pings completely.
  1574. ; http://php.net/oci8.ping-interval
  1575. ;oci8.ping_interval = 60
  1576. ; Connection: Set this to a user chosen connection class to be used
  1577. ; for all pooled server requests with Oracle 11g Database Resident
  1578. ; Connection Pooling (DRCP). To use DRCP, this value should be set to
  1579. ; the same string for all web servers running the same application,
  1580. ; the database pool must be configured, and the connection string must
  1581. ; specify to use a pooled server.
  1582. ;oci8.connection_class =
  1583. ; High Availability: Using On lets PHP receive Fast Application
  1584. ; Notification (FAN) events generated when a database node fails. The
  1585. ; database must also be configured to post FAN events.
  1586. ;oci8.events = Off
  1587. ; Tuning: This option enables statement caching, and specifies how
  1588. ; many statements to cache. Using 0 disables statement caching.
  1589. ; http://php.net/oci8.statement-cache-size
  1590. ;oci8.statement_cache_size = 20
  1591. ; Tuning: Enables statement prefetching and sets the default number of
  1592. ; rows that will be fetched automatically after statement execution.
  1593. ; http://php.net/oci8.default-prefetch
  1594. ;oci8.default_prefetch = 100
  1595. ; Compatibility. Using On means oci_close() will not close
  1596. ; oci_connect() and oci_new_connect() connections.
  1597. ; http://php.net/oci8.old-oci-close-semantics
  1598. ;oci8.old_oci_close_semantics = Off
  1599. [PostgreSQL]
  1600. ; Allow or prevent persistent links.
  1601. ; http://php.net/pgsql.allow-persistent
  1602. pgsql.allow_persistent = On
  1603. ; Detect broken persistent links always with pg_pconnect().
  1604. ; Auto reset feature requires a little overheads.
  1605. ; http://php.net/pgsql.auto-reset-persistent
  1606. pgsql.auto_reset_persistent = Off
  1607. ; Maximum number of persistent links. -1 means no limit.
  1608. ; http://php.net/pgsql.max-persistent
  1609. pgsql.max_persistent = -1
  1610. ; Maximum number of links (persistent+non persistent). -1 means no limit.
  1611. ; http://php.net/pgsql.max-links
  1612. pgsql.max_links = -1
  1613. ; Ignore PostgreSQL backends Notice message or not.
  1614. ; Notice message logging require a little overheads.
  1615. ; http://php.net/pgsql.ignore-notice
  1616. pgsql.ignore_notice = 0
  1617. ; Log PostgreSQL backends Notice message or not.
  1618. ; Unless pgsql.ignore_notice=0, module cannot log notice message.
  1619. ; http://php.net/pgsql.log-notice
  1620. pgsql.log_notice = 0
  1621. [Sybase-CT]
  1622. ; Allow or prevent persistent links.
  1623. ; http://php.net/sybct.allow-persistent
  1624. sybct.allow_persistent = On
  1625. ; Maximum number of persistent links. -1 means no limit.
  1626. ; http://php.net/sybct.max-persistent
  1627. sybct.max_persistent = -1
  1628. ; Maximum number of links (persistent + non-persistent). -1 means no limit.
  1629. ; http://php.net/sybct.max-links
  1630. sybct.max_links = -1
  1631. ; Minimum server message severity to display.
  1632. ; http://php.net/sybct.min-server-severity
  1633. sybct.min_server_severity = 10
  1634. ; Minimum client message severity to display.
  1635. ; http://php.net/sybct.min-client-severity
  1636. sybct.min_client_severity = 10
  1637. ; Set per-context timeout
  1638. ; http://php.net/sybct.timeout
  1639. ;sybct.timeout=
  1640. ;sybct.packet_size
  1641. ; The maximum time in seconds to wait for a connection attempt to succeed before returning failure.
  1642. ; Default: one minute
  1643. ;sybct.login_timeout=
  1644. ; The name of the host you claim to be connecting from, for display by sp_who.
  1645. ; Default: none
  1646. ;sybct.hostname=
  1647. ; Allows you to define how often deadlocks are to be retried. -1 means "forever".
  1648. ; Default: 0
  1649. ;sybct.deadlock_retry_count=
  1650. [bcmath]
  1651. ; Number of decimal digits for all bcmath functions.
  1652. ; http://php.net/bcmath.scale
  1653. bcmath.scale = 0
  1654. [browscap]
  1655. ; http://php.net/browscap
  1656. ;browscap = extra/browscap.ini
  1657. [Session]
  1658. ; Handler used to store/retrieve data.
  1659. ; http://php.net/session.save-handler
  1660. session.save_handler = files
  1661. ; Argument passed to save_handler. In the case of files, this is the path
  1662. ; where data files are stored. Note: Windows users have to change this
  1663. ; variable in order to use PHP's session functions.
  1664. ;
  1665. ; The path can be defined as:
  1666. ;
  1667. ; session.save_path = "N;/path"
  1668. ;
  1669. ; where N is an integer. Instead of storing all the session files in
  1670. ; /path, what this will do is use subdirectories N-levels deep, and
  1671. ; store the session data in those directories. This is useful if
  1672. ; your OS has problems with many files in one directory, and is
  1673. ; a more efficient layout for servers that handle many sessions.
  1674. ;
  1675. ; NOTE 1: PHP will not create this directory structure automatically.
  1676. ; You can use the script in the ext/session dir for that purpose.
  1677. ; NOTE 2: See the section on garbage collection below if you choose to
  1678. ; use subdirectories for session storage
  1679. ;
  1680. ; The file storage module creates files using mode 600 by default.
  1681. ; You can change that by using
  1682. ;
  1683. ; session.save_path = "N;MODE;/path"
  1684. ;
  1685. ; where MODE is the octal representation of the mode. Note that this
  1686. ; does not overwrite the process's umask.
  1687. ; http://php.net/session.save-path
  1688. ;session.save_path = "/tmp"
  1689. ; Whether to use strict session mode.
  1690. ; Strict session mode does not accept uninitialized session ID and regenerate
  1691. ; session ID if browser sends uninitialized session ID. Strict mode protects
  1692. ; applications from session fixation via session adoption vulnerability. It is
  1693. ; disabled by default for maximum compatibility, but enabling it is encouraged.
  1694. ; https://wiki.php.net/rfc/strict_sessions
  1695. session.use_strict_mode = 0
  1696. ; Whether to use cookies.
  1697. ; http://php.net/session.use-cookies
  1698. session.use_cookies = 1
  1699. ; http://php.net/session.cookie-secure
  1700. ;session.cookie_secure =
  1701. ; This option forces PHP to fetch and use a cookie for storing and maintaining
  1702. ; the session id. We encourage this operation as it's very helpful in combating
  1703. ; session hijacking when not specifying and managing your own session id. It is
  1704. ; not the be-all and end-all of session hijacking defense, but it's a good start.
  1705. ; http://php.net/session.use-only-cookies
  1706. session.use_only_cookies = 1
  1707. ; Name of the session (used as cookie name).
  1708. ; http://php.net/session.name
  1709. session.name = PHPSESSID
  1710. ; Initialize session on request startup.
  1711. ; http://php.net/session.auto-start
  1712. session.auto_start = 0
  1713. ; Lifetime in seconds of cookie or, if 0, until browser is restarted.
  1714. ; http://php.net/session.cookie-lifetime
  1715. session.cookie_lifetime = 0
  1716. ; The path for which the cookie is valid.
  1717. ; http://php.net/session.cookie-path
  1718. session.cookie_path = /
  1719. ; The domain for which the cookie is valid.
  1720. ; http://php.net/session.cookie-domain
  1721. session.cookie_domain =
  1722. ; Whether or not to add the httpOnly flag to the cookie, which makes it inaccessible to browser scripting languages such as JavaScript.
  1723. ; http://php.net/session.cookie-httponly
  1724. session.cookie_httponly =
  1725. ; Handler used to serialize data. php is the standard serializer of PHP.
  1726. ; http://php.net/session.serialize-handler
  1727. session.serialize_handler = php
  1728. ; Defines the probability that the 'garbage collection' process is started
  1729. ; on every session initialization. The probability is calculated by using
  1730. ; gc_probability/gc_divisor. Where session.gc_probability is the numerator
  1731. ; and gc_divisor is the denominator in the equation. Setting this value to 1
  1732. ; when the session.gc_divisor value is 100 will give you approximately a 1% chance
  1733. ; the gc will run on any give request.
  1734. ; Default Value: 1
  1735. ; Development Value: 1
  1736. ; Production Value: 1
  1737. ; http://php.net/session.gc-probability
  1738. session.gc_probability = 1
  1739. ; Defines the probability that the 'garbage collection' process is started on every
  1740. ; session initialization. The probability is calculated by using the following equation:
  1741. ; gc_probability/gc_divisor. Where session.gc_probability is the numerator and
  1742. ; session.gc_divisor is the denominator in the equation. Setting this value to 1
  1743. ; when the session.gc_divisor value is 100 will give you approximately a 1% chance
  1744. ; the gc will run on any give request. Increasing this value to 1000 will give you
  1745. ; a 0.1% chance the gc will run on any give request. For high volume production servers,
  1746. ; this is a more efficient approach.
  1747. ; Default Value: 100
  1748. ; Development Value: 1000
  1749. ; Production Value: 1000
  1750. ; http://php.net/session.gc-divisor
  1751. session.gc_divisor = 1000
  1752. ; After this number of seconds, stored data will be seen as 'garbage' and
  1753. ; cleaned up by the garbage collection process.
  1754. ; http://php.net/session.gc-maxlifetime
  1755. session.gc_maxlifetime = 1440
  1756. ; NOTE: If you are using the subdirectory option for storing session files
  1757. ; (see session.save_path above), then garbage collection does *not*
  1758. ; happen automatically. You will need to do your own garbage
  1759. ; collection through a shell script, cron entry, or some other method.
  1760. ; For example, the following script would is the equivalent of
  1761. ; setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
  1762. ; find /path/to/sessions -cmin +24 -type f | xargs rm
  1763. ; Check HTTP Referer to invalidate externally stored URLs containing ids.
  1764. ; HTTP_REFERER has to contain this substring for the session to be
  1765. ; considered as valid.
  1766. ; http://php.net/session.referer-check
  1767. session.referer_check =
  1768. ; How many bytes to read from the file.
  1769. ; http://php.net/session.entropy-length
  1770. ;session.entropy_length = 32
  1771. ; Specified here to create the session id.
  1772. ; http://php.net/session.entropy-file
  1773. ; Defaults to /dev/urandom
  1774. ; On systems that don't have /dev/urandom but do have /dev/arandom, this will default to /dev/arandom
  1775. ; If neither are found at compile time, the default is no entropy file.
  1776. ; On windows, setting the entropy_length setting will activate the
  1777. ; Windows random source (using the CryptoAPI)
  1778. ;session.entropy_file = /dev/urandom
  1779. ; Set to {nocache,private,public,} to determine HTTP caching aspects
  1780. ; or leave this empty to avoid sending anti-caching headers.
  1781. ; http://php.net/session.cache-limiter
  1782. session.cache_limiter = nocache
  1783. ; Document expires after n minutes.
  1784. ; http://php.net/session.cache-expire
  1785. session.cache_expire = 180
  1786. ; trans sid support is disabled by default.
  1787. ; Use of trans sid may risk your users' security.
  1788. ; Use this option with caution.
  1789. ; - User may send URL contains active session ID
  1790. ; to other person via. email/irc/etc.
  1791. ; - URL that contains active session ID may be stored
  1792. ; in publicly accessible computer.
  1793. ; - User may access your site with the same session ID
  1794. ; always using URL stored in browser's history or bookmarks.
  1795. ; http://php.net/session.use-trans-sid
  1796. session.use_trans_sid = 0
  1797. ; Select a hash function for use in generating session ids.
  1798. ; Possible Values
  1799. ; 0 (MD5 128 bits)
  1800. ; 1 (SHA-1 160 bits)
  1801. ; This option may also be set to the name of any hash function supported by
  1802. ; the hash extension. A list of available hashes is returned by the hash_algos()
  1803. ; function.
  1804. ; http://php.net/session.hash-function
  1805. session.hash_function = 0
  1806. ; Define how many bits are stored in each character when converting
  1807. ; the binary hash data to something readable.
  1808. ; Possible values:
  1809. ; 4 (4 bits: 0-9, a-f)
  1810. ; 5 (5 bits: 0-9, a-v)
  1811. ; 6 (6 bits: 0-9, a-z, A-Z, "-", ",")
  1812. ; Default Value: 4
  1813. ; Development Value: 5
  1814. ; Production Value: 5
  1815. ; http://php.net/session.hash-bits-per-character
  1816. session.hash_bits_per_character = 5
  1817. ; The URL rewriter will look for URLs in a defined set of HTML tags.
  1818. ; form/fieldset are special; if you include them here, the rewriter will
  1819. ; add a hidden <input> field with the info which is otherwise appended
  1820. ; to URLs. If you want XHTML conformity, remove the form entry.
  1821. ; Note that all valid entries require a "=", even if no value follows.
  1822. ; Default Value: "a=href,area=href,frame=src,form=,fieldset="
  1823. ; Development Value: "a=href,area=href,frame=src,input=src,form=fakeentry"
  1824. ; Production Value: "a=href,area=href,frame=src,input=src,form=fakeentry"
  1825. ; http://php.net/url-rewriter.tags
  1826. url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"
  1827. ; Enable upload progress tracking in $_SESSION
  1828. ; Default Value: On
  1829. ; Development Value: On
  1830. ; Production Value: On
  1831. ; http://php.net/session.upload-progress.enabled
  1832. ;session.upload_progress.enabled = On
  1833. ; Cleanup the progress information as soon as all POST data has been read
  1834. ; (i.e. upload completed).
  1835. ; Default Value: On
  1836. ; Development Value: On
  1837. ; Production Value: On
  1838. ; http://php.net/session.upload-progress.cleanup
  1839. ;session.upload_progress.cleanup = On
  1840. ; A prefix used for the upload progress key in $_SESSION
  1841. ; Default Value: "upload_progress_"
  1842. ; Development Value: "upload_progress_"
  1843. ; Production Value: "upload_progress_"
  1844. ; http://php.net/session.upload-progress.prefix
  1845. ;session.upload_progress.prefix = "upload_progress_"
  1846. ; The index name (concatenated with the prefix) in $_SESSION
  1847. ; containing the upload progress information
  1848. ; Default Value: "PHP_SESSION_UPLOAD_PROGRESS"
  1849. ; Development Value: "PHP_SESSION_UPLOAD_PROGRESS"
  1850. ; Production Value: "PHP_SESSION_UPLOAD_PROGRESS"
  1851. ; http://php.net/session.upload-progress.name
  1852. ;session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS"
  1853. ; How frequently the upload progress should be updated.
  1854. ; Given either in percentages (per-file), or in bytes
  1855. ; Default Value: "1%"
  1856. ; Development Value: "1%"
  1857. ; Production Value: "1%"
  1858. ; http://php.net/session.upload-progress.freq
  1859. ;session.upload_progress.freq = "1%"
  1860. ; The minimum delay between updates, in seconds
  1861. ; Default Value: 1
  1862. ; Development Value: 1
  1863. ; Production Value: 1
  1864. ; http://php.net/session.upload-progress.min-freq
  1865. ;session.upload_progress.min_freq = "1"
  1866. [MSSQL]
  1867. ; Allow or prevent persistent links.
  1868. mssql.allow_persistent = On
  1869. ; Maximum number of persistent links. -1 means no limit.
  1870. mssql.max_persistent = -1
  1871. ; Maximum number of links (persistent+non persistent). -1 means no limit.
  1872. mssql.max_links = -1
  1873. ; Minimum error severity to display.
  1874. mssql.min_error_severity = 10
  1875. ; Minimum message severity to display.
  1876. mssql.min_message_severity = 10
  1877. ; Compatibility mode with old versions of PHP 3.0.
  1878. mssql.compatibility_mode = Off
  1879. ; Connect timeout
  1880. ;mssql.connect_timeout = 5
  1881. ; Query timeout
  1882. ;mssql.timeout = 60
  1883. ; Valid range 0 - 2147483647. Default = 4096.
  1884. ;mssql.textlimit = 4096
  1885. ; Valid range 0 - 2147483647. Default = 4096.
  1886. ;mssql.textsize = 4096
  1887. ; Limits the number of records in each batch. 0 = all records in one batch.
  1888. ;mssql.batchsize = 0
  1889. ; Specify how datetime and datetim4 columns are returned
  1890. ; On => Returns data converted to SQL server settings
  1891. ; Off => Returns values as YYYY-MM-DD hh:mm:ss
  1892. ;mssql.datetimeconvert = On
  1893. ; Use NT authentication when connecting to the server
  1894. mssql.secure_connection = Off
  1895. ; Specify max number of processes. -1 = library default
  1896. ; msdlib defaults to 25
  1897. ; FreeTDS defaults to 4096
  1898. ;mssql.max_procs = -1
  1899. ; Specify client character set.
  1900. ; If empty or not set the client charset from freetds.conf is used
  1901. ; This is only used when compiled with FreeTDS
  1902. ;mssql.charset = "ISO-8859-1"
  1903. [Assertion]
  1904. ; Assert(expr); active by default.
  1905. ; http://php.net/assert.active
  1906. ;assert.active = On
  1907. ; Issue a PHP warning for each failed assertion.
  1908. ; http://php.net/assert.warning
  1909. ;assert.warning = On
  1910. ; Don't bail out by default.
  1911. ; http://php.net/assert.bail
  1912. ;assert.bail = Off
  1913. ; User-function to be called if an assertion fails.
  1914. ; http://php.net/assert.callback
  1915. ;assert.callback = 0
  1916. ; Eval the expression with current error_reporting(). Set to true if you want
  1917. ; error_reporting(0) around the eval().
  1918. ; http://php.net/assert.quiet-eval
  1919. ;assert.quiet_eval = 0
  1920. [COM]
  1921. ; path to a file containing GUIDs, IIDs or filenames of files with TypeLibs
  1922. ; http://php.net/com.typelib-file
  1923. ;com.typelib_file =
  1924. ; allow Distributed-COM calls
  1925. ; http://php.net/com.allow-dcom
  1926. ;com.allow_dcom = true
  1927. ; autoregister constants of a components typlib on com_load()
  1928. ; http://php.net/com.autoregister-typelib
  1929. ;com.autoregister_typelib = true
  1930. ; register constants casesensitive
  1931. ; http://php.net/com.autoregister-casesensitive
  1932. ;com.autoregister_casesensitive = false
  1933. ; show warnings on duplicate constant registrations
  1934. ; http://php.net/com.autoregister-verbose
  1935. ;com.autoregister_verbose = true
  1936. ; The default character set code-page to use when passing strings to and from COM objects.
  1937. ; Default: system ANSI code page
  1938. ;com.code_page=
  1939. [mbstring]
  1940. ; language for internal character representation.
  1941. ; This affects mb_send_mail() and mbstrig.detect_order.
  1942. ; http://php.net/mbstring.language
  1943. ;mbstring.language = Japanese
  1944. ; Use of this INI entry is deprecated, use global internal_encoding instead.
  1945. ; internal/script encoding.
  1946. ; Some encoding cannot work as internal encoding. (e.g. SJIS, BIG5, ISO-2022-*)
  1947. ; If empty, default_charset or internal_encoding or iconv.internal_encoding is used.
  1948. ; The precedence is: default_charset < internal_encoding < iconv.internal_encoding
  1949. ;mbstring.internal_encoding =
  1950. ; Use of this INI entry is deprecated, use global input_encoding instead.
  1951. ; http input encoding.
  1952. ; mbstring.encoding_traslation = On is needed to use this setting.
  1953. ; If empty, default_charset or input_encoding or mbstring.input is used.
  1954. ; The precedence is: default_charset < intput_encoding < mbsting.http_input
  1955. ; http://php.net/mbstring.http-input
  1956. ;mbstring.http_input =
  1957. ; Use of this INI entry is deprecated, use global output_encoding instead.
  1958. ; http output encoding.
  1959. ; mb_output_handler must be registered as output buffer to function.
  1960. ; If empty, default_charset or output_encoding or mbstring.http_output is used.
  1961. ; The precedence is: default_charset < output_encoding < mbstring.http_output
  1962. ; To use an output encoding conversion, mbstring's output handler must be set
  1963. ; otherwise output encoding conversion cannot be performed.
  1964. ; http://php.net/mbstring.http-output
  1965. ;mbstring.http_output =
  1966. ; enable automatic encoding translation according to
  1967. ; mbstring.internal_encoding setting. Input chars are
  1968. ; converted to internal encoding by setting this to On.
  1969. ; Note: Do _not_ use automatic encoding translation for
  1970. ; portable libs/applications.
  1971. ; http://php.net/mbstring.encoding-translation
  1972. ;mbstring.encoding_translation = Off
  1973. ; automatic encoding detection order.
  1974. ; "auto" detect order is changed according to mbstring.language
  1975. ; http://php.net/mbstring.detect-order
  1976. ;mbstring.detect_order = auto
  1977. ; substitute_character used when character cannot be converted
  1978. ; one from another
  1979. ; http://php.net/mbstring.substitute-character
  1980. ;mbstring.substitute_character = none
  1981. ; overload(replace) single byte functions by mbstring functions.
  1982. ; mail(), ereg(), etc are overloaded by mb_send_mail(), mb_ereg(),
  1983. ; etc. Possible values are 0,1,2,4 or combination of them.
  1984. ; For example, 7 for overload everything.
  1985. ; 0: No overload
  1986. ; 1: Overload mail() function
  1987. ; 2: Overload str*() functions
  1988. ; 4: Overload ereg*() functions
  1989. ; http://php.net/mbstring.func-overload
  1990. ;mbstring.func_overload = 0
  1991. ; enable strict encoding detection.
  1992. ; Default: Off
  1993. ;mbstring.strict_detection = On
  1994. ; This directive specifies the regex pattern of content types for which mb_output_handler()
  1995. ; is activated.
  1996. ; Default: mbstring.http_output_conv_mimetype=^(text/|application/xhtml\+xml)
  1997. ;mbstring.http_output_conv_mimetype=
  1998. [gd]
  1999. ; Tell the jpeg decode to ignore warnings and try to create
  2000. ; a gd image. The warning will then be displayed as notices
  2001. ; disabled by default
  2002. ; http://php.net/gd.jpeg-ignore-warning
  2003. ;gd.jpeg_ignore_warning = 0
  2004. [exif]
  2005. ; Exif UNICODE user comments are handled as UCS-2BE/UCS-2LE and JIS as JIS.
  2006. ; With mbstring support this will automatically be converted into the encoding
  2007. ; given by corresponding encode setting. When empty mbstring.internal_encoding
  2008. ; is used. For the decode settings you can distinguish between motorola and
  2009. ; intel byte order. A decode setting cannot be empty.
  2010. ; http://php.net/exif.encode-unicode
  2011. ;exif.encode_unicode = ISO-8859-15
  2012. ; http://php.net/exif.decode-unicode-motorola
  2013. ;exif.decode_unicode_motorola = UCS-2BE
  2014. ; http://php.net/exif.decode-unicode-intel
  2015. ;exif.decode_unicode_intel = UCS-2LE
  2016. ; http://php.net/exif.encode-jis
  2017. ;exif.encode_jis =
  2018. ; http://php.net/exif.decode-jis-motorola
  2019. ;exif.decode_jis_motorola = JIS
  2020. ; http://php.net/exif.decode-jis-intel
  2021. ;exif.decode_jis_intel = JIS
  2022. [Tidy]
  2023. ; The path to a default tidy configuration file to use when using tidy
  2024. ; http://php.net/tidy.default-config
  2025. ;tidy.default_config = /usr/local/lib/php/default.tcfg
  2026. ; Should tidy clean and repair output automatically?
  2027. ; WARNING: Do not use this option if you are generating non-html content
  2028. ; such as dynamic images
  2029. ; http://php.net/tidy.clean-output
  2030. tidy.clean_output = Off
  2031. [soap]
  2032. ; Enables or disables WSDL caching feature.
  2033. ; http://php.net/soap.wsdl-cache-enabled
  2034. soap.wsdl_cache_enabled=1
  2035. ; Sets the directory name where SOAP extension will put cache files.
  2036. ; http://php.net/soap.wsdl-cache-dir
  2037. soap.wsdl_cache_dir="/tmp"
  2038. ; (time to live) Sets the number of second while cached file will be used
  2039. ; instead of original one.
  2040. ; http://php.net/soap.wsdl-cache-ttl
  2041. soap.wsdl_cache_ttl=86400
  2042. ; Sets the size of the cache limit. (Max. number of WSDL files to cache)
  2043. soap.wsdl_cache_limit = 5
  2044. [sysvshm]
  2045. ; A default size of the shared memory segment
  2046. ;sysvshm.init_mem = 10000
  2047. [ldap]
  2048. ; Sets the maximum number of open links or -1 for unlimited.
  2049. ldap.max_links = -1
  2050. [mcrypt]
  2051. ; For more information about mcrypt settings see http://php.net/mcrypt-module-open
  2052. ; Directory where to load mcrypt algorithms
  2053. ; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt)
  2054. ;mcrypt.algorithms_dir=
  2055. ; Directory where to load mcrypt modes
  2056. ; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt)
  2057. ;mcrypt.modes_dir=
  2058. [dba]
  2059. ;dba.default_handler=
  2060. [opcache]
  2061. ; Determines if Zend OPCache is enabled
  2062. ;opcache.enable=0
  2063. ; Determines if Zend OPCache is enabled for the CLI version of PHP
  2064. ;opcache.enable_cli=0
  2065. ; The OPcache shared memory storage size.
  2066. ;opcache.memory_consumption=64
  2067. ; The amount of memory for interned strings in Mbytes.
  2068. ;opcache.interned_strings_buffer=4
  2069. ; The maximum number of keys (scripts) in the OPcache hash table.
  2070. ; Only numbers between 200 and 100000 are allowed.
  2071. ;opcache.max_accelerated_files=2000
  2072. ; The maximum percentage of "wasted" memory until a restart is scheduled.
  2073. ;opcache.max_wasted_percentage=5
  2074. ; When this directive is enabled, the OPcache appends the current working
  2075. ; directory to the script key, thus eliminating possible collisions between
  2076. ; files with the same name (basename). Disabling the directive improves
  2077. ; performance, but may break existing applications.
  2078. ;opcache.use_cwd=1
  2079. ; When disabled, you must reset the OPcache manually or restart the
  2080. ; webserver for changes to the filesystem to take effect.
  2081. ;opcache.validate_timestamps=1
  2082. ; How often (in seconds) to check file timestamps for changes to the shared
  2083. ; memory storage allocation. ("1" means validate once per second, but only
  2084. ; once per request. "0" means always validate)
  2085. ;opcache.revalidate_freq=2
  2086. ; Enables or disables file search in include_path optimization
  2087. ;opcache.revalidate_path=0
  2088. ; If disabled, all PHPDoc comments are dropped from the code to reduce the
  2089. ; size of the optimized code.
  2090. ;opcache.save_comments=1
  2091. ; If disabled, PHPDoc comments are not loaded from SHM, so "Doc Comments"
  2092. ; may be always stored (save_comments=1), but not loaded by applications
  2093. ; that don't need them anyway.
  2094. ;opcache.load_comments=1
  2095. ; If enabled, a fast shutdown sequence is used for the accelerated code
  2096. ;opcache.fast_shutdown=0
  2097. ; Allow file existence override (file_exists, etc.) performance feature.
  2098. ;opcache.enable_file_override=0
  2099. ; A bitmask, where each bit enables or disables the appropriate OPcache
  2100. ; passes
  2101. ;opcache.optimization_level=0xffffffff
  2102. ;opcache.inherited_hack=1
  2103. ;opcache.dups_fix=0
  2104. ; The location of the OPcache blacklist file (wildcards allowed).
  2105. ; Each OPcache blacklist file is a text file that holds the names of files
  2106. ; that should not be accelerated. The file format is to add each filename
  2107. ; to a new line. The filename may be a full path or just a file prefix
  2108. ; (i.e., /var/www/x blacklists all the files and directories in /var/www
  2109. ; that start with 'x'). Line starting with a ; are ignored (comments).
  2110. ;opcache.blacklist_filename=
  2111. ; Allows exclusion of large files from being cached. By default all files
  2112. ; are cached.
  2113. ;opcache.max_file_size=0
  2114. ; Check the cache checksum each N requests.
  2115. ; The default value of "0" means that the checks are disabled.
  2116. ;opcache.consistency_checks=0
  2117. ; How long to wait (in seconds) for a scheduled restart to begin if the cache
  2118. ; is not being accessed.
  2119. ;opcache.force_restart_timeout=180
  2120. ; OPcache error_log file name. Empty string assumes "stderr".
  2121. ;opcache.error_log=
  2122. ; All OPcache errors go to the Web server log.
  2123. ; By default, only fatal errors (level 0) or errors (level 1) are logged.
  2124. ; You can also enable warnings (level 2), info messages (level 3) or
  2125. ; debug messages (level 4).
  2126. ;opcache.log_verbosity_level=1
  2127. ; Preferred Shared Memory back-end. Leave empty and let the system decide.
  2128. ;opcache.preferred_memory_model=
  2129. ; Protect the shared memory from unexpected writing during script execution.
  2130. ; Useful for internal debugging only.
  2131. ;opcache.protect_memory=0
  2132. ; Validate cached file permissions.
  2133. ; opcache.validate_permission=0
  2134. ; Prevent name collisions in chroot'ed environment.
  2135. ; opcache.validate_root=0
  2136. [curl]
  2137. ; A default value for the CURLOPT_CAINFO option. This is required to be an
  2138. ; absolute path.
  2139. ;curl.cainfo =
  2140. [openssl]
  2141. ; The location of a Certificate Authority (CA) file on the local filesystem
  2142. ; to use when verifying the identity of SSL/TLS peers. Most users should
  2143. ; not specify a value for this directive as PHP will attempt to use the
  2144. ; OS-managed cert stores in its absence. If specified, this value may still
  2145. ; be overridden on a per-stream basis via the "cafile" SSL stream context
  2146. ; option.
  2147. ;openssl.cafile=
  2148. ; If openssl.cafile is not specified or if the CA file is not found, the
  2149. ; directory pointed to by openssl.capath is searched for a suitable
  2150. ; certificate. This value must be a correctly hashed certificate directory.
  2151. ; Most users should not specify a value for this directive as PHP will
  2152. ; attempt to use the OS-managed cert stores in its absence. If specified,
  2153. ; this value may still be overridden on a per-stream basis via the "capath"
  2154. ; SSL stream context option.
  2155. ;openssl.capath=
  2156. ; Local Variables:
  2157. ; tab-width: 4
  2158. ; End:
  2159. EOF

范例:运行镜像

$ docker build -t centos-php:v1.0 -f Dockerfile .
# php:
# 1.使用镜像跑定时任务
# 2.nginx+php-fpm跑网站
$ docker images centos-php
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
centos-php   v1.0      6878df16217a   9 minutes ago   634MB

$ docker run -it -p 19000:9000 --name centos-php-node1 -d centos-php:v1.0
$ docker ps -l
CONTAINER ID   IMAGE             COMMAND     CREATED          STATUS          PORTS                                         NAMES
d173650742cb   centos-php:v1.0   "php-fpm"   16 seconds ago   Up 15 seconds   0.0.0.0:19000->9000/tcp, :::19000->9000/tcp   centos-php-node1

6.7 案例:容器化搭建个人博客系统

01 Docker 基础部分 - 图46

1、自定义网络

docker network create lnmp

2、创建Mysql容器

docker run -d \
      --name lnmp_mysql \
      --net lnmp \
      --mount src=mysql-vol,dst=/var/lib/mysql \
      -e MYSQL_ROOT_PASSWORD=123456 \
      -e MYSQL_DATABASE=wordpress \
      mysql:5.7 --character-set-server=utf8

3、创建PHP容器

docker run -d --name lnmp_php \
      --net lnmp \
      --mount src=wwwroot,dst=/wwwroot \
      centos-php:v1.0

4、创建Nginx容器

# docker run -d --name lnmp_nginx \
#         --net lnmp -p 10880:80 \
#         --mount src=wwwroot,dst=/wwwroot \
#         --mount type=bind,src=$PWD/php.conf,dst=/usr/local/nginx/conf/vhost/php.conf \
#         centos-nginx:v1.0

docker run -d --name lnmp_nginx \
        --net lnmp -p 10880:80 \
        --mount src=wwwroot,dst=/usr/local/nginx/html \
        --mount type=bind,src=$PWD/php.conf,dst=/usr/local/nginx/conf/vhost/php.conf \
        centos-nginx:v1.0

范例:php.conf 配置文件示例

server {
    listen 80;
    server_name example.kubesphere.com;
    index index.php index.html;

    access_log logs/www.kubesphere.com_access.log;
    error_log logs/www.kubesphere.com_error.log;

    location / {
        root /wwwroot;
    }
    location ~* \.php$ {
        root /wwwroot;
        fastcgi_pass lnmp _php:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

5、以wordpress博客为例

$ docker volume inspect wwwroot 
[
    {
        "CreatedAt": "2022-12-01T02:54:38Z",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/wwwroot/_data",
        "Name": "wwwroot",
        "Options": null,
        "Scope": "local"
    }
]
$ echo "<?php phpinfo();?>" > /var/lib/docker/volumes/wwwroot/_data/index.php
$ curl 127.0.0.1:10880/index.php
<?php phpinfo();?>

https://cn.wordpress.org/wordpress-4.9.4-zh_CN.tar.gz

Docker 容器需要用阻塞进程将容器一直运行中。

范例:start.sh 脚本示例

cat > start.sh <<-'EOF'
#!/bin/bash
service httpd start
service mysqld start
mysqladmin -uroot -p${MYSQL_ROOT_PASSWORD}
tail -f
EOF

范例:Dockerfile 示例

FROM centos:6
MAINTAINER <zhongzhiwei zhongzhiwei@kubesphere.io>

RUN curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-6.10.repo
RUN yum install -y httpd php php-gd php-mysql mysql mysql-server
ENV MYSQL_ROOT_PASSWORD 123456

RUN echo "<?php phpinfo();?>" > /var/www/html/index.php

# cat start.sh
# #!/bin/bash
# service httpd start
# service mysqld start
# mysqladmin -uroot -p${MYSQL_ROOT_PASSWORD}
# tail -f
ADD start.sh /start.sh
RUN chmod +x /start.sh

# wget https://cn.wordpress.org/wordpress-4.7.4-zh_CN.tar.gz 
ADD https://cn.wordpress.org/wordpress-4.7.4-zh_CN.tar.gz /var/www/html/
RUN cd /var/www/html/ && tar -zxvf wordpress-4.7.4-zh_CN.tar.gz 
COPY wp-config.php /var/www/html/wordpress

VOLUME [ "/var/lib/mysql" ]
CMD /start.sh

EXPOSE 80 3306

范例:wp-config.php 示例

<?php
/**
 * WordPress基础配置文件。
 *
 * 这个文件被安装程序用于自动生成wp-config.php配置文件,
 * 您可以不使用网站,您需要手动复制这个文件,
 * 并重命名为“wp-config.php”,然后填入相关信息。
 *
 * 本文件包含以下配置选项:
 *
 * * MySQL设置
 * * 密钥
 * * 数据库表名前缀
 * * ABSPATH
 *
 * @link https://codex.wordpress.org/zh-cn:%E7%BC%96%E8%BE%91_wp-config.php
 *
 * @package WordPress
 */

// ** MySQL 设置 - 具体信息来自您正在使用的主机 ** //
/** WordPress数据库的名称 */
define('DB_NAME', 'test');

/** MySQL数据库用户名 */
define('DB_USER', 'root');

/** MySQL数据库密码 */
define('DB_PASSWORD', '密码');

/** MySQL主机 */
define('DB_HOST', 'localhost');

/** 创建数据表时默认的文字编码 */
define('DB_CHARSET', 'utf8');

/** 数据库整理类型。如不确定请勿更改 */
define('DB_COLLATE', '');

/**#@+
 * 身份认证密钥与盐。
 *
 * 修改为任意独一无二的字串!
 * 或者直接访问{@link https://api.wordpress.org/secret-key/1.1/salt/
 * WordPress.org密钥生成服务}
 * 任何修改都会导致所有cookies失效,所有用户将必须重新登录。
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         '(Qc8jjvhi}r7w|N+fZ+5x;~:mTun!08=2f+vn#5m@<OH#q !0H_;PteVL/:a@1e_');
define('SECURE_AUTH_KEY',  '!{5p&%:CeG8Wi4q)FkjmEtYU8n3v*K/i01R-{~/7t7lKe?j=fs$!!K>lgw`8%|`E');
define('LOGGED_IN_KEY',    '779<wSUu<7Y#=:,,9>c@D{)p+i}0t=F/US}Be/=j)?2!l!Cd4_:cL)3&N,-ls?^X');
define('NONCE_KEY',        'FT{nC1?}qnP@)[JuENB3a%11w;vPp<@YxzbbFBfW5JPZN0wBVN|FVB`q!)f[H(/e');
define('AUTH_SALT',        '|Y]}.eZX$S~$#su_{hS0c24:dm@[a..jWav@:bSH)Y6PF)Qk@a;CP*4Cv=-Dpv3W');
define('SECURE_AUTH_SALT', '`!R:FNc{{kdkm;zQ1x2?{fIpbc-Am&UysZrYFHF?u~.N:;Rhy-?YZNnuOa(KE+0o');
define('LOGGED_IN_SALT',   '%h>+r06#a^6{Wk3/=8oH2`<p4ub0&d+N;tSeBY+iw(i.Ug9>X]A)rPRS/T.Rslg(');
define('NONCE_SALT',       '?Dvzn,,<r4;82^rIx5%+9/fNR?i3sG9^]pHR{+eV@pQP!L~CRFcrXz?&s^ZgWJJ2');

/**#@-*/

/**
 * WordPress数据表前缀。
 *
 * 如果您有在同一数据库内安装多个WordPress的需求,请为每个WordPress设置
 * 不同的数据表前缀。前缀名只能为数字、字母加下划线。
 */
$table_prefix  = 'wp_';

/**
 * 开发者专用:WordPress调试模式。
 *
 * 将这个值改为true,WordPress将显示所有用于开发的提示。
 * 强烈建议插件开发者在开发环境中启用WP_DEBUG。
 *
 * 要获取其他能用于调试的信息,请访问Codex。
 *
 * @link https://codex.wordpress.org/Debugging_in_WordPress
 */
define('WP_DEBUG', false);

/**
 * zh_CN本地化设置:启用ICP备案号显示
 *
 * 可在设置→常规中修改。
 * 如需禁用,请移除或注释掉本行。
 */
define('WP_ZH_CN_ICP_NUM', true);

/* 好了!请不要再继续编辑。请保存本文件。使用愉快! */

/** WordPress目录的绝对路径。 */
if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');

/** 设置WordPress变量和包含文件。 */
require_once(ABSPATH . 'wp-settings.php');

范例:构建 Docker 镜像

docker build -t php:v1.0 -f Dockerfile .

:::color1 Container 容器是最精简版的 Linux 操作系统。

:::

$ docker images 
REPOSITORY                TAG              IMAGE ID       CREATED          SIZE
php                       v1.0             14ebabe2d1c4   12 minutes ago   547MB
$ docker run -itd --name wordpress -p 88:80 php:v1.0
$ docker ps -l 
CONTAINER ID   IMAGE      COMMAND                  CREATED         STATUS         PORTS                                         NAMES
69dfab550ca6   php:v1.0   "/bin/sh -c /start.sh"   2 seconds ago   Up 2 seconds   3306/tcp, 0.0.0.0:88->80/tcp, :::88->80/tcp   wordpress

浏览器访问 http://<IP地址>:88

01 Docker 基础部分 - 图47

浏览器访问 http://<IP地址>:88/wordpress

01 Docker 基础部分 - 图48

$ docker exec -it wordpress /bin/bash
[root@1c8bab6f45bd /]# echo $MYSQL_ROOT_PASSWORD
123456
[root@404042e7bfc8 /]# vi /etc/my.cnf 
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
skip-grant-tables

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

01 Docker 基础部分 - 图49

安装 Wordpress 就可以实现了!

01 Docker 基础部分 - 图50

Wordpress 后台管理系统。

01 Docker 基础部分 - 图51

6.8 JAVA项目镜像构建:Tomcat

FROM centos:centos7.9.2009
LABEL maintainer www.kubesphere.io

ENV VERSION=8.5.84

RUN yum install java-1.8.0-openjdk wget curl unzip iproute net-tools -y && \
    yum clean all && \
    rm -rf /var/cache/yum/*
# wget https://dlcdn.apache.org/tomcat/tomcat-8/v8.5.84/bin/apache-tomcat-8.5.84.tar.gz
ADD apache-tomcat-${VERSION}.tar.gz /usr/local/
RUN mv /usr/local/apache-tomcat-${VERSION} /usr/local/tomcat && \
    sed -i '1a JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom"' /usr/local/tomcat/bin/catalina.sh && \
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

ENV PATH $PATH:/usr/local/tomcat/bin

WORKDIR /usr/local/tomcat

EXPOSE 8080

CMD ["catalina.sh", "run"]
$ docker build -t centos-tomcat:v1.0 -f Dockerfile .
$ docker images centos-tomcat
REPOSITORY      TAG       IMAGE ID       CREATED              SIZE
centos-tomcat   v1.0      d84e8bc7a8a4   About a minute ago   462MB

$ docker run -it -d -p 18080:8080 --name centos-tomcat centos-tomcat:v1.0
$ docker ps -l 
CONTAINER ID   IMAGE                COMMAND             CREATED         STATUS        PORTS                                         NAMES
2086996297dc   centos-tomcat:v1.0   "catalina.sh run"   2 seconds ago   Up 1 second   0.0.0.0:18080->8080/tcp, :::18080->8080/tcp   centos-tomcat
$ curl 127.0.0.1:18080

# 浏览器访问:http://<IP地址>:18080

01 Docker 基础部分 - 图52

6.9 JAVA微服务镜像构建:Jar

FROM java:8-jdk-alpine
LABEL maintainer www.kubesphere.com

ENV JAVA_OPTS="$JAVA_OPTS -Dfile.encoding=UTF8-Duser.timezone=GMT+08"

RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && \
    apk add -U tzdata && \
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

# 需要有一个hello.jar包文件
COPY hello.jar /
# 暴露端口
EXPOSE 8888

CMD ["/bin/sh", "-c", "java -jar $JAVA_OPTS /hello.jar"]
# 构建镜像
$ docker build -t alpine-jar:v1.0 -f Dockerfile .

范例:Apline-Openjdk-1.8

$ vim Dockerfile
FROM alpine

MAINTAINER zhongzhiwei <zhongzhiwei@kubesphere.io>
LABEL name="zhongzhiwei"
LABEL email="zhongzhiwei@kubesphere.io"

ENV MYPATH /usr/local/
WORKDIR ${MYPATH}

# 修改APT为清华源
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories

# 安装VIM编辑器
RUN apk add vim

# 安装ifconfig查看网络IP
RUN apk add net-tools

# 安装OpenJDK 和 bash
RUN apk add bash openjdk8

# 配置java环境变量
ENV JAVA_HOME=/usr/lib/jvm/java-1.8-openjdk
ENV PATH="$JAVA_HOME/bin:${PATH}"

EXPOSE 80
RUN echo "WORKDIR=${MYPATH}"
RUN java -version
RUN echo "Success-----------------OK"
CMD [ "/bin/bash" ]

范例:CentOS7-JDK1.8

FROM centos:centos7.9.2009

MAINTAINER zhongzhiwei <zhongzhiwei@kubesphere.io>
LABEL name="zhongzhiwei"
LABEL email="zhongzhiwei@kubesphere.io"

ENV MYPATH /usr/local
WORKDIR ${MYPATH}

# 安装VIM编辑器
RUN yum install -y vim

# 安装ifconfig查看网络IP
RUN yum install -y net-tools

# 安装java8以及lib库
RUN yum install -y glibc.i686

# ADD 是相对路径 jar,把jdk-8u301-linux-x64.tar.gz添加到容器中,安装包必须要和Dockerfile文件在同一位置
ADD jdk-8u301-linux-x64.tar.gz /usr/local/
RUN ln -s /usr/local/jdk1.8.0_301 /usr/local/java

# 配置java环境变量
ENV JAVA_HOME /usr/local/java
ENV JRE_HOME ${JAVA_HOME}/jre
ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib:$CLASSPATH
ENV PATH $JAVA_HOME/bin:$PATH

EXPOSE 80
RUN echo "WORKDIR=${MYPATH}"
RUN echo "Success-----------------OK"
CMD [ "/bin/bash" ]

范例:Ubuntu-JDK1.8

FROM ubuntu

MAINTAINER zhongzhiwei <935523993@qq.com>

ENV MY_PATH=/usr/local
WORKDIR ${MY_PATH}

# 更新APT源仓库
RUN apt update -y
# 安装 ifconfig 命令查看网络IP
RUN apt install -y net-tools
# 安装 ip addr
RUN apt install -y iproute2 
# 安装 ping
RUN apt install -y inetutils-ping
# 安装基本软件
RUN apt install -y wget bzip2 glibc-headers bison

# 安装 Java 8 以及 lib 库
# 1.安装 GNU MAKE-Version:4.2.1 软件路径:https://ftp.gnu.org/gnu/make/
RUN wget https://ftp.gnu.org/gnu/make/make-4.2.1.tar.gz && tar -xf make-4.2.1.tar.gz && cd make-4.2.1 && mkdir -p build && cd build
# 编译安装
RUN /usr/local/make-4.2.1/configure --prefix=/usr && sh build.sh && make install

# 2.安装 GCC-Version:8.2.0 软件路径:https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc 
RUN wget -c -P /opt/software/ https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-9.2.0/gcc-8.2.0.tar.gz && cd /opt/software/ && tar -zxvf gcc-8.2.0.tar.gz && /opt/software/gcc-8.2.0/contrib/download_prerequisites
RUN mkdir build && cd build && /opt/software/gcc-8.2.0/configure --enable-checking=release --enable-languages=c,c++ --disable-multilib
RUN make -j 4 && make install 

# 3.安装 Glibc-Version:2.28 软件路径:https://ftp.gnu.org/gnu/glibc/
RUN wget http://ftp.gnu.org/gnu/glibc/glibc-2.28.tar.gz && tar -xf glibc-2.28.tar.gz && cd glibc-2.28 && mkdir build && cd build
# 编译安装
RUN /usr/local/glibc-2.28/configure --prefix=/usr --disable-profile --enable-add-ons --with-headers=/usr/include --with-binutils=/usr/bin && make -j 4 && make install 

# ADD 是相对路径 jar,把jdk-8u301-linux-x64.tar.gz添加到容器中,安装包必须要和Dockerfile文件在同一位置
ADD jdk-8u301-linux-x64.tar.gz /usr/local/java

# 配置java环境变量
ENV JAVA_HOME=/usr/local/java/jdk1.8.0_301
ENV JRE_HOME=${JAVA_HOME}/jre
ENV CLASSPATH=${JAVA_HOME}/lib/dt.jar:${JAVA_HOME}/lib/tools.jar:${JRE_HOME}/lib:$CLASSPATH
ENV PATH=${JAVA_HOME}/bin:${PATH}

EXPOSE 80
CMD echo "${MY_PATH}"
CMD echo "Success-----------------OK"
CMD /bin/bash

6.10 编写Dockerfile最佳实践

  • 减少镜像层:一次RUN指令形成新的一层,尽量Shell命令都写在一行,减少镜像层。Docker 默认的限制镜像层为 127 层。
  • 优化镜像大小:一次RUN形成新的一层,如果没有在同一层删除,无论文件是否最后删除,都会带到下一层,所以要在每一层清理对应的残留数据,减小镜像大小。
  • 减少网络传输时间:例如软件包、mvn仓库等。
  • 多阶段构建:代码编译、部署在一个Dockerfile完成,只会保留部署阶段产生数据。

:::color1 编译构建 Dockerfile1 → 部署,打项目镜像 Dockerfile2

多阶段构建使用比较少,使用场景不多。

:::

  • 选择最小的基础镜像:例如( alpine & slim )。快速的拉取,拉取的部署等。
  • 学习更多Dockerfile的写法 Reference:https://github.com/docker-library/