上云——docker进阶篇

1 Docker Compose

定义管理多个容器,贴上官网地址https://docs.docker.com/compose/

官网的三个步骤

  1. Define your app’s environment with a so it can be reproduced anywhere.Dockerfile(必须要有dockerfile)
  2. Define the services that make up your app in so they can be run together in an isolated environment.docker-compose.yml(必须要有docker-compose.yml)
  3. Run and the Docker compose command starts and runs your entire app. You can alternatively run using the docker-compose binary.docker compose up``docker-compose up(启动项目)

知道dockerfile的可以明白,每个专属自己的服务,都需要一个dockerfile,然后再build,会显得特别麻烦,而Compose作为docker官方开源项目,就是为了解决这些问题,直接写一个文件批量编排服务

下载安装

# 命令行输入
[root@lv94 bin]# curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   423  100   423    0     0    179      0  0:00:02  0:00:02 --:--:--   179
100 16.7M  100 16.7M    0     0  1938k      0  0:00:08  0:00:08 --:--:-- 2821k
[root@lv94 bin]# sudo chmod +x /usr/local/bin/docker-compose
[root@lv94 bin]# docker-compose version
docker-compose version 1.25.5, build 8a1c60f6
docker-py version: 4.1.0
CPython version: 3.7.5
OpenSSL version: OpenSSL 1.1.0l  10 Sep 2019

官方实例

Get started with Docker Compose | Docker Documentation

官方案例步骤说明:
# 1、创建目录
mkdir composetest
cd composetest

# 2、app.py 服务详情
import time

import redis
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)

def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)

@app.route('/')
def hello():
    count = get_hit_count()
    return 'Hello World! I have been seen {} times.\n'.format(count)

# 3、创建requirements.txt,输入以下内容
flask
redis

# 4、创建Dockerfile文件 将应用打包为镜像
FROM python:3.7-alpine
WORKDIR
Learn more about the "WORKDIR" Dockerfile command.
 /code
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]

# 5、创建docker-compose.yaml 定义服务所需环境
version: "3.3"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"
    
# 6、docker compose up 启动项目
[root@lv94 composetest]# ls
app.py  docker-compose.yml  Dockerfile  requirements.txt
[root@lv94 composetest]# docker-compose build 
[root@lv94 composetest]# docker compose up

# 7、最终测试效果
[root@lv94 ~]# docker ps
CONTAINER ID   IMAGE             COMMAND                  CREATED         STATUS         PORTS                               NAMES
515d9c03102c   composetest_web   "flask run"              9 minutes ago   Up 5 minutes   0.0.0.0:5000->5000/tcp              composetest_web_1
dbfed961cf45   redis:alpine      "docker-entrypoint.s…"   9 minutes ago   Up 5 minutes   6379/tcp                            composetest_redis_1
[root@lv94 ~]# curl localhost:5000
Hello World! I have been seen 1 times.

# 8、停止
直接ctrl + C
或者新开连接窗口到当前目录 docker-compose down

yaml规则

Compose file version 3 reference | Docker Documentation

# docker-compose.yaml 分层法则

#第一层 版本
version: "3.3"

#第二层 各种服务
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"
  服务1:
    服务配置(镜像配置)

#第三层 其他配置,比如网络/卷、全局的规则
volumes:
network:
configs:

# depends_on举例,比如web服务依赖redis和db
version: "3.9"
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres
    
# deploy 相关配置,比如副本
version: "3.9"
services:
  redis:
    image: redis:alpine
    deploy:
      replicas: 6
      placement:
        max_replicas_per_node: 1
      update_config:
        parallelism: 2
        delay: 10s
      restart_policy:
        condition: on-failure

官网案例

https://docs.docker.com/samples/wordpress/

# docker-compose.yaml文件
version: "3.3"
    
services:
  db:
    image: mysql:5.7
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: somewordpress
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress
    
  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    volumes:
      - wordpress_data:/var/www/html
    ports:
      - "8000:80"
    restart: always
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
      WORDPRESS_DB_NAME: wordpress
volumes:
  db_data: {}
  wordpress_data: {}
  
# 后台启动
docker-compose up -d

# 项目存在问题已经构建过一次可以重新构建
docker-compose up --build

2 Docker Swarm(集群)

采用阿里云4台服务器测试

# centos7及以上版本服务器安装部署docker
# yum安装gcc环境
yum -y install gcc
yum -y install gcc-c++

# 卸载旧版本
sudo yum remove docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest-longrotate \
docker-logrotate \
docker-engine

# 安装需要的软件包
yum install -y yum-utils

# 设置镜像仓库
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

# 更新yum软件包索引
yum makecache fast

# 安装Docker CE
yum install -y docker-ce docker-ce-cli containerd.io

# 启动docker
systemctl start docker

# 测试命令
docker version

# 阿里云镜像加速器,这里镜像加速器在阿里云搜索容器镜像服务就有,暂不显示
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://xxxxx.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

工作模式

managers and workers.管理节点、工作节点

Swarm mode cluster

# 初始化:将某一台服务器ip(内网)加入swarm
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker swarm init --advertise-addr 172.16.152.31
Swarm initialized: current node (x286x0qyru44hjcrux2zu0x7q) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-4kvdd3okhi6fr230o9r27fal7qsunr87au56f44ynvp04fz8ri-eccb9eki25ybbti6frclyd8fs 172.16.152.31:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

# docker swarm join 加入一个节点
# 注意这个命令行来自上面
[root@iZbp1ja9p6tw8bu7yaloq1Z /]# docker swarm join --token SWMTKN-1-4kvdd3okhi6fr230o9r27fal7qsunr87au56f44ynvp04fz8ri-eccb9eki25ybbti6frclyd8fs 172.16.152.31:2377
This node joined a swarm as a worker.

# 查看节点配置
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker node ls
ID                            HOSTNAME                  STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
vu6t8r4r4w1ksi3pnqbfiucm7     iZbp1ja9p6tw8bu7yaloq1Z   Ready     Active                          20.10.11
x286x0qyru44hjcrux2zu0x7q *   iZbp1ja9p6tw8bu7yaloq3Z   Ready     Active         Leader           20.10.11

# 获取令牌的方式
docker swarm join-token manager
docker swarm join-token worker
# 利用令牌生成命令
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker swarm join-token worker
To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-4kvdd3okhi6fr230o9r27fal7qsunr87au56f44ynvp04fz8ri-eccb9eki25ybbti6frclyd8fs 172.16.152.31:2377

# 最后结果是,两个服务器是worker,两个是manager
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker node ls
ID                            HOSTNAME                  STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
vu6t8r4r4w1ksi3pnqbfiucm7     iZbp1ja9p6tw8bu7yaloq1Z   Ready     Active                          20.10.11
x0y4ccc03e3835q18b49u81au     iZbp1ja9p6tw8bu7yaloq2Z   Ready     Active         Reachable        20.10.11
x286x0qyru44hjcrux2zu0x7q *   iZbp1ja9p6tw8bu7yaloq3Z   Ready     Active         Leader           20.10.11
nj7jr8kuvam995xb6rfk62ch0     iZbp1ja9p6tw8bu7yaloq4Z   Ready     Active                          20.10.11

总结上述,生成主节点(init),然后加入为worker或者manager

Raft协议

双主双从,假设任意一个节点挂,其他均可用

Raft协议:保证大多数节点存活才可以使用,只要>1,集群至少大于3台

四台服务器,二管理二工作,一个管理节点挂掉,整个swarm就挂了就有因为满足Raft协议,一个工作节点挂掉

# 节点离开集群
[root@iZbp1ja9p6tw8bu7yaloq4Z /]# docker swarm leave
Node left the swarm.

# 3台管理节点,挂掉一个集群还是可以正常使用的

相关命令

我们可以把集群的操作的docker service看成是docker run

# docker service:创建服务、动态扩展服务、动态更新服务
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker service --help

Usage:  docker service COMMAND

Manage services

Commands:
  create      Create a new service
  inspect     Display detailed information on one or more services
  logs        Fetch the logs of a service or task
  ls          List services
  ps          List the tasks of one or more services
  rm          Remove one or more services
  rollback    Revert changes to a service's configuration
  scale       Scale one or multiple replicated services
  update      Update a service

# 启动nginx
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker service create -p 8888:80 --name mynginx nginx
qb971f19reafd1i7uevnsui02
overall progress: 1 out of 1 tasks
1/1: running
verify: Service converged

# 查看服务
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker service ps mynginx
ID             NAME        IMAGE          NODE                      DESIRED STATE   CURRENT STATE                ERROR     PORTS
ydlveomxjyjz   mynginx.1   nginx:latest   iZbp1ja9p6tw8bu7yaloq3Z   Running         Running about a minute ago

# 列出所有的镜像信息,这里副本只有一个
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker service ls
ID             NAME      MODE         REPLICAS   IMAGE          PORTS
qb971f19reaf   mynginx   replicated   1/1        nginx:latest   *:8888->80/tcp

# 增加到3副本,负载量变大。启动完后可以观察其他节点有副本出现(负载均衡)
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker service update --replicas 3 mynginx
mynginx
overall progress: 3 out of 3 tasks
1/3: running
2/3: running
3/3: running
verify: Service converged

# 增加到5副本,动态扩缩容,同上面,不过更加方便
[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker service scale mynginx=5
mynginx scaled to 5
overall progress: 5 out of 5 tasks
1/5: running
2/5: running
3/5: running
4/5: running
5/5: running
verify: Service converged

3 Docker其他命令

stack

# 单机
docker-compose up -d xxx.yaml

# 集群
docker stack deploy xxx.yaml

secret

[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker secret --help

Usage:  docker secret COMMAND

Manage Docker secrets

Commands:
  create      Create a secret from a file or STDIN as content
  inspect     Display detailed information on one or more secrets
  ls          List secrets
  rm          Remove one or more secrets

config

[root@iZbp1ja9p6tw8bu7yaloq3Z /]# docker config --help

Usage:  docker config COMMAND

Manage Docker configs

Commands:
  create      Create a config from a file or STDIN
  inspect     Display detailed information on one or more configs
  ls          List configs
  rm          Remove one or more configs
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

友培

数据皆开源!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值