Docker Swarm - 配置管理

► 前言介绍

Docker 17.06 引入了 Swarm 服务配置,它允许你在服务的镜像或者运行的容器外部存储非敏感信息,比如配置文件。这样保证了镜像的通用性,而无需将配置文件绑定到容器或使用环境变量来配置。

  • Configs 是安装在容器的文件系统中,而不是使用 RAM 磁盘。
  • Configs 可以随时添加或删除,服务可以共享一个配置。
  • Configs 可以与 Environments 或 Labels 结合使用,以获得最大的灵活性。

提醒:Docker Configs 仅对 Swarm 服务有效,对独立的容器是无用的。如需使用,可以启动 1 个副本的服务来使用 Docker Config。

► Docker Config 基本操作

友情提示:“ 需 Swarm Manager 权限才能操作 !”

1、创建配置

用法

docker config create [参数] CONFIG file|-

参数

简写 参数 默认值 描述
-l --label 配置标签

2、配置列表

用法

docker config ls [参数]

参数

简写 参数 默认值 描述
-f --filter 按条件过滤输出
--format GO 模板转化
-q --quiet 仅展示 ID

3、配置详情

用法

docker config inspect [参数] CONFIG [CONFIG...]

参数

简写 参数 默认值 描述
-f --format GO 模板转化
--pretty 以人性化的格式打印信息

4、配置删除

用法

docker config rm CONFIG [CONFIG...]

5、Docker Compose file 示例

version: "3.3"
services:
  redis:
    image: redis:latest
    deploy:
      replicas: 1
    configs:
      - my_config
      - my_other_config
configs:
  my_config:
    file: ./my_config.txt
  my_other_config:
    external: true

提醒:仅 version 3.3 + 可用
详细:https://docs.docker.com/compose/compose-file/#configs

► Swarm 对 Config 的管理

在 Swarm 中添加一个 Config 时,Docker 通过 TLS 连接把 Config 发送给 Swarm Manager。这个 Config 经过加密后,存储在 Raft 日志中,而且整个 Raft 日志会被复制到其他 Manager 中,确保 Config 的高可用性。

在新创建的或正在运行的服务添加 Config 时,Config 将作为文件安装到容器中,文件路径默认为 linux 容器中的 /

可以在任何时候通过更新服务的方式授权其他的 Config 或移除已有的
Config 访问权。

如果节点是 Swarm Manager,或者正在运行服务任务已被授权访问这个 Config,那么这个节点才能访问这个配置。当容器任务停止运行时,共享给它的 Config 将从该容器的内存文件系统中卸载,并从节点的内存刷新。

如果一个节点运行了一个带 Config 的任务容器,在它失去与 Swarm 的连接后,这个任务容器仍然可以访问其 Config,但只有在节点重新连接到 Swarm 时才能接收更新。

正在运行的服务正在使用的 Config 不能删除。想要在不中断正在运行的服务的情况下删除配置可以参考 《Rotate a config》。

为了更容易地更新或回退 Config,可以考虑在 Config Name 中添加版本号或日期。

如需更新 Stack ,可以更改 Compose file,然后重新运行 docker stack deploy -c 。如果 Compose file 使用新的 Config ,那么 services 将开始使用这些配置。

注意:配置是不可变的,所以无法更改现有服务的文件,可以创建一个新的 Config 来使用不同的文件。

► 示例一:在服务中添加 Config

1、创建配置

echo "This is a config" | docker config create my-config -

2、创建 redis 服务,使用 my-config 配置

docker service create --name redis --config my-config redis

3、查看容器所在的节点

docker service ps redis


4、查看配置内容

docker exec $(docker ps --filter name=redis -q) cat /my-config

► 示例二:配置 Nginx 首页

1、新建一个 HTML 页面 index.html


  Hello Docker
  
    

Hello Docker! This is a docker config page.

2、创建配置 homepage

docker config create homepage index.html

3、创建 Nginx 配置文件 site.conf

server {
    listen 80;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

4、创建配置 nginx_config

docker config create nginx_config site.conf

5、创建 Nginx 服务

docker service create \
     --name nginx \
     --config source=nginx_config,target=/etc/nginx/conf.d/site.conf \
     --config source=homepage,target=/usr/share/nginx/html/index.html \
     --publish published=3000,target=80 \
     nginx

6、验证 Nginx 服务配置

你可能感兴趣的:(Docker Swarm - 配置管理)