docker / compose 的安装 和 体验

文档

官网文档

视频

视频

简介

课程内容

1.Docker Compose 容器编排
2.Docker Swarm #集群 热扩容 需要在阿里上买服务器,至少冲100+以上的人民币
文档:

集群方式的部署,买4台阿里云服务器,建议买2核4g 用的时候付费,不用的时候销毁.一天也就几元钱

3.Docker Stack #部署 和 Compose比较像
4.Docker Secret #权限认证
5.Docker Config #配置
6.k8s
容器单独没有什么意义,容器编排才有意义.

docker-compose使用的三个步骤

docker-compose.yml示例:

version: '2.0'
services:
  web:
    build: .
    ports:
    - "5000:5000"
    volumes:
    - .:/code
    - logvolume01:/var/log
    links:
    - redis
  redis:
    image: redis
volumes:
  logvolume01: {}

通过编写docker-compose.yml文件,哪怕有100个服务,
也可以用docker-compose up 一键启动

Compose : 重要的概念

  • 服务sevices,容器.应用 (web,redis,mysql....),很多单容器
  • 把很多单容器编排在一起,就是一个项目project.一组关联的容器.博客,web,mysql

安装docker-compose


# 1. 国内下载地址:(推荐)
执行:curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

# 1. 官网的地址地址(不推荐,下载慢)

[root@localhost ~]# 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    313      0  0:00:01  0:00:01 --:--:--   313
100 16.7M  100 16.7M    0     0  6907k      0  0:00:02  0:00:02 --:--:-- 19.3M


# 2.赋权:
[root@localhost ~]# chmod +x /usr/local/bin/docker-compose


# 3.看版本: 就是一个二进制文件.用它去运行命令
[root@localhost ~]# docker-compose version
Docker Compose version v2.17.2

[root@localhost /usr/local/bin]# docker -v
Docker version 23.0.4, build f480fb1

# 4.卸载:
[root@localhost bin]# rm /usr/local/bin/docker-compose
rm:是否删除普通文件 "/usr/local/bin/docker-compose"?y
[root@localhost bin]# docker-compose version
-bash: /usr/local/bin/docker-compose: 没有那个文件或目录

更多docker-compose版本见下面链接
https://github.com/docker/compose/releases

image

体验部署python应用

用docker-compose布置一个python应用

地址:https://docs.docker.com/compose/gettingstarted/

python应用.计数器.reids!

  1. 应用app.py
  2. Dockerfile 应用打包为镜像
  3. Docker-compose yaml文件(定义整个服务需要的环境变量web redis),完整的线上服务.
  4. 启动compose项目(docker-compase up)

实操

1.Create a directory for the project:

$ cd /home
$ mkdir composertest
$ cd composertest

2.Create a file called app.py in your project directory and paste this in:

$ vim app.py

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)

if __name__ == "__main__":
    app.run(host ="0.0.0.0",debug=True)

3.Create another file called requirements.txt in your project directory and paste this in:

vim requirements.txt

flask
redis

4.Create a Dockerfile

$ vim Dockerfile

FROM python:3.7-alpine
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt #安装txt里的python依赖项(flask redis)
CMD ["python", "app.py"] #将容器的默认命令设置为python app.py

5.在项目中创建docker-compose.yml文件

version: '3.8'
services:
  web:
    build: . #使用Dockerfile当前目录中构建镜像
    ports:
      - "5000:5000"
    volumes:
      - .:/code
  redis:
    image: "redis:alpine" #从docker hub中下载运行
[root@localhost compasetest]# tree
.
├── app.py
├── docker-compose.yml
├── Dockerfile
└── requirements.txt

6.启动

$ docker-compose up` #窗口运行
$ docker-compose up -d #后台运行

启动效果:

[root@localhost composertest]# docker-compose up
Creating network "composertest_default" with the default driver
Creating composertest_web_1   ... done
Creating composertest_redis_1 ... done
Attaching to composertest_web_1, composertest_redis_1
redis_1  | 1:C 20 Aug 2020 23:34:26.784 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 20 Aug 2020 23:34:26.784 # Redis version=6.0.6, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 20 Aug 2020 23:34:26.784 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1  | 1:M 20 Aug 2020 23:34:26.792 * Running mode=standalone, port=6379.
redis_1  | 1:M 20 Aug 2020 23:34:26.792 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1  | 1:M 20 Aug 2020 23:34:26.792 # Server initialized
redis_1  | 1:M 20 Aug 2020 23:34:26.793 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1  | 1:M 20 Aug 2020 23:34:26.793 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
redis_1  | 1:M 20 Aug 2020 23:34:26.797 * Ready to accept connections
web_1    |  * Serving Flask app "app" (lazy loading)
web_1    |  * Environment: production
web_1    |    WARNING: This is a development server. Do not use it in a production deployment.
web_1    |    Use a production WSGI server instead.
web_1    |  * Debug mode: on
web_1    |  * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
web_1    |  * Restarting with stat
web_1    |  * Debugger is active!
web_1    |  * Debugger PIN: 318-153-711

7.看新的窗口,查看启动的容器

[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
e1012c89675b        redis:alpine        "docker-entrypoint.s…"   43 seconds ago      Up 38 seconds       6379/tcp                 composertest_redis_1
5111b3adadaf        composertest_web    "python app.py"          43 seconds ago      Up 38 seconds       0.0.0.0:5000->5000/tcp   composertest_web_1

8.访问一下

[root@localhost composertest]# curl localhost:5000
Hello World! I have been seen 1 times.
[root@localhost composertest]# curl localhost:5000
Hello World! I have been seen 5 times.
[root@localhost composertest]# curl localhost:5000
Hello World! I have been seen 6 times.
[root@localhost composertest]# curl localhost:5000
Hello World! I have been seen 7 times.
[root@localhost ~]# docker service ls #它不是一个集群,所以不能这样查看
Error response from daemon: This node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again.

浏览器访问:

http://122.114.30.38:5000/

Hello World! I have been seen 4 times.

9.停止服务

$ docker-compose down

或者

ctrl+c

小结:

网络规则

[root@localhost ~]# docker network ls
NETWORK ID          NAME                   DRIVER              SCOPE
55246ac3d411        bridge                 bridge              local
8bf32609e619        composertest_default   bridge              local
868b78ed9d45        host                   host                local
f81eb59f871d        none                   null                local

查看容器的网络

[root@localhost ~]# docker network -h
Flag shorthand -h has been deprecated, please use --help

Usage:	docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  prune       Remove all unused networks
  rm          Remove one or more networks

Run 'docker network COMMAND --help' for more information on a command.
[root@localhost ~]# docker network inspect 8bf32609e619
[
    {
        "Name": "composertest_default",
        "Id": "8bf32609e619553398f22ef75ae557eda7292647d17d4b864487559754428655",
        "Created": "2020-08-21T07:34:22.293824382+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.20.0.0/16",
                    "Gateway": "172.20.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": true,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "5111b3adadafa06462ec653b0cf34750c483db1ff17d00c0b261f265b46b88c7": {
                "Name": "composertest_web_1",
                "EndpointID": "43857e6a28f7a6061dab21fa3e66a103158182b42ffebfbfd5d8083cd953b574",
                "MacAddress": "02:42:ac:14:00:02",
                "IPv4Address": "172.20.0.2/16",
                "IPv6Address": ""
            },
            "e1012c89675bca1e7040af20176839427089e98a2aafe930ab1fa0eb4258ac65": {
                "Name": "composertest_redis_1",
                "EndpointID": "e3805e9343649e7ba830a705c26df97eb9f64c5407a7d43e87acd45fb4c581f1",
                "MacAddress": "02:42:ac:14:00:03",
                "IPv4Address": "172.20.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "default",
            "com.docker.compose.project": "composertest",
            "com.docker.compose.version": "1.25.5"
        }
    }
]


可以看到在同一个网络下,可以通过服务名redis ping相互通网络

下面我们来测试一下:

[root@localhost ~]# docker ps 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
e1012c89675b        redis:alpine        "docker-entrypoint.s…"   39 minutes ago      Up 38 minutes       6379/tcp                 composertest_redis_1
5111b3adadaf        composertest_web    "python app.py"          39 minutes ago      Up 38 minutes       0.0.0.0:5000->5000/tcp   composertest_web_1
[root@localhost ~]# docker exec -it 5111 /bin/sh 
/code # ping redis   # web里ping  redis  可以ping通 
PING redis (172.20.0.3): 56 data bytes
64 bytes from 172.20.0.3: seq=0 ttl=64 time=0.076 ms
64 bytes from 172.20.0.3: seq=1 ttl=64 time=0.107 ms
64 bytes from 172.20.0.3: seq=2 ttl=64 time=0.128 ms
64 bytes from 172.20.0.3: seq=3 ttl=64 time=0.115 ms
^C
--- redis ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 0.076/0.106/0.128 ms
/code # exit
[root@localhost ~]# docker exec -it e101 /bin/sh
/data # ping web   # redis 里ping web 可以ping通 
PING web (172.20.0.2): 56 data bytes
64 bytes from 172.20.0.2: seq=0 ttl=64 time=0.109 ms
64 bytes from 172.20.0.2: seq=1 ttl=64 time=0.111 ms
64 bytes from 172.20.0.2: seq=2 ttl=64 time=0.113 ms
^C
--- web ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max = 0.109/0.111/0.113 ms
/data # 

posted @ 2020-08-17 07:59  HaimaBlog  阅读(530)  评论(0编辑  收藏  举报