docker-compose学习随笔

Docker Compose

官方介绍

compose是一个定义、运行多个容器的工具

YAML file配置文件。

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the list of features.

所有的环境都可以是用compose

Compose works in all environments: production, staging, development, testing, as well as CI workflows. You can learn more about each case in Common Use Cases.

三步骤:

Using Compose is basically a three-step process:

  1. Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
    • dockerfile保证我们的项目在任何地方可以运行
  2. Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
    • services 什么服务
    • docker-compose.yml 这个文件怎么写
  3. Run docker compose up and the Docker compose command starts and runs your entire app. You can alternatively run docker-compose up using the docker-compose binary.
    • 启动项目

总结:批量容器编排工具

理解

compose是docker官方的开源项目,需要安装!

安装

根据官方文档操作即可,地址:

https://docs.docker.com/compose/install/#alternative-install-options

# 下载
[root@master ~]# sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   633  100   633    0     0    872      0 --:--:-- --:--:-- --:--:--   871
100 12.1M  100 12.1M    0     0  1212k      0  0:00:10  0:00:10 --:--:-- 1475k

# 赋权,需要可执行权限
[root@master ~]# sudo chmod +x /usr/local/bin/docker-compose

# 查看版本,测试安装
[root@master ~]# docker-compose version
docker-compose version 1.29.2, build 5becea4c
docker-py version: 5.0.0
CPython version: 3.7.10
OpenSSL version: OpenSSL 1.1.0l  10 Sep 2019

# 文件安装默认路径
[root@master ~]# ls -lh /usr/local/bin/

#卸载
[root@master ~]# sudo rm /usr/local/bin/docker-compose

开始入门

根据官网的介绍操作:构建一个在 Docker Compose 上运行的简单 Python Web 应用程序。

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

步骤

# 1、创建docker-compose项目目录
$ mkdir composetest
$ cd composetest

# 2、创建web 项目app.py
$ vim 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)

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

# 3、创建 Dockerfile 文件
[root@master composetest]# vim Dockerfile
# syntax=docker/dockerfile:1
FROM python:3.8
ADD . /code
WORKDIR /code
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
CMD ["python", "app.py"]


# 4、创建docker-compose.yml文件
[root@master composetest]# vim docker-compose.yml
version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
  redis:
    image: "redis:alpine"
# 启动日志
[root@master composetest]# docker-compose up
Building web
Sending build context to Docker daemon  5.632kB
Step 1/6 : FROM python:3.8
3.8: Pulling from library/python
955615a668ce: Pull complete 
2756ef5f69a5: Pull complete 
911ea9f2bd51: Pull complete 
27b0a22ee906: Pull complete 
8584d51a9262: Pull complete 
524774b7d363: Pull complete 
9460f6b75036: Pull complete 
9bc548096c18: Pull complete 
1d87379b86b8: Pull complete 
Digest: sha256:c2842aababbe377f9c76f172d9eb39487e23f306b2f29f020f3f6654cb0876e9
Status: Downloaded newer image for python:3.8
 ---> ff08f08727e5
Step 2/6 : ADD . /code
 ---> 4ad16799db72
Step 3/6 : WORKDIR /code
 ---> Running in 5de7275f16f8
Removing intermediate container 5de7275f16f8
 ---> 11bb5e96ab19
Step 4/6 : COPY requirements.txt requirements.txt
 ---> 531548b19fb6
Step 5/6 : RUN pip install -r requirements.txt
 ---> Running in 5a85cac02005
Collecting flask
  Downloading Flask-2.0.1-py3-none-any.whl (94 kB)
Collecting redis
  Downloading redis-3.5.3-py2.py3-none-any.whl (72 kB)
Collecting itsdangerous>=2.0
  Downloading itsdangerous-2.0.1-py3-none-any.whl (18 kB)
Collecting click>=7.1.2
  Downloading click-8.0.1-py3-none-any.whl (97 kB)
Collecting Jinja2>=3.0
  Downloading Jinja2-3.0.1-py3-none-any.whl (133 kB)
Collecting Werkzeug>=2.0
  Downloading Werkzeug-2.0.1-py3-none-any.whl (288 kB)
Collecting MarkupSafe>=2.0
  Downloading MarkupSafe-2.0.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (30 kB)
Installing collected packages: MarkupSafe, Werkzeug, Jinja2, itsdangerous, click, redis, flask
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Successfully installed Jinja2-3.0.1 MarkupSafe-2.0.1 Werkzeug-2.0.1 click-8.0.1 flask-2.0.1 itsdangerous-2.0.1 redis-3.5.3
Removing intermediate container 5a85cac02005
 ---> f3d69f1cc53d
Step 6/6 : CMD ["python", "app.py"]
 ---> Running in bf7b1696a7ae
Removing intermediate container bf7b1696a7ae
 ---> 94080556a0e3
Successfully built 94080556a0e3
Successfully tagged composetest_web:latest
WARNING: Image for service web was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Pulling redis (redis:alpine)...
alpine: Pulling from library/redis
a0d0a0d46f8b: Pull complete
a04b0375051e: Pull complete
cdc2bb0f9590: Pull complete
8f19735ec10c: Pull complete
ac5156a4c6ca: Pull complete
7b7e1b3fdb00: Pull complete
Digest: sha256:fa785f9bd167b94a6b30210ae32422469f4b0f805f4df12733c2f177f500d1ba
Status: Downloaded newer image for redis:alpine
Creating composetest_web_1   ... done
Creating composetest_redis_1 ... done
Attaching to composetest_web_1, composetest_redis_1
##############################################Redis服务启动成功#############################################
redis_1  | 1:C 10 Sep 2021 06:50:32.618 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 10 Sep 2021 06:50:32.618 # Redis version=6.2.5, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:C 10 Sep 2021 06:50:32.618 # 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 10 Sep 2021 06:50:32.619 * monotonic clock: POSIX clock_gettime
redis_1  | 1:M 10 Sep 2021 06:50:32.619 * Running mode=standalone, port=6379.
redis_1  | 1:M 10 Sep 2021 06:50:32.619 # 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 10 Sep 2021 06:50:32.619 # Server initialized
redis_1  | 1:M 10 Sep 2021 06:50:32.619 # 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 10 Sep 2021 06:50:32.619 * Ready to accept connections
##############################################web服务启动成功###############################################
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 all addresses.
web_1    |    WARNING: This is a development server. Do not use it in a production deployment.
web_1    |  * Running on http://172.18.0.2:5000/ (Press CTRL+C to quit)
web_1    |  * Restarting with stat
web_1    |  * Debugger is active!
web_1    |  * Debugger PIN: 707-546-904

默认规则

  • 服务启动成功

    # 容器运行正常
    [root@master composetest]# docker ps -a
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
    5077a755b065        redis:alpine        "docker-entrypoint.s…"   About an hour ago   Up About an hour    6379/tcp                 composetest_redis_1
    41639789d6b0        composetest_web     "python app.py"          About an hour ago   Up About an hour    0.0.0.0:5000->5000/tcp   composetest_web_1
    
    # 应用访问正常
    [root@master composetest]# curl localhost:5000
    Hello World! I have been seen 1 times.
    
    
  • 自动构建镜像

    # 查看镜像,发现构建了composetest_web镜像,以及应用需要的依赖镜像python和redis
    [root@master composetest]# docker images
    REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
    composetest_web     latest              94080556a0e3        About an hour ago   920MB
    python              3.8                 ff08f08727e5        2 days ago          909MB
    redis               alpine              f6f2296798e9        13 days ago         32.3MB
    
    
  • 默认的服务名 文件名_服务名 _ num

    _num 代表副本数量

  • 网络规则

    1、通过compose启动,会生产一个自己的网络

    假设一个项目中有10个服务,那么项目中的内容都在同一个网络下面。在同一个网络下面就可以通过域名访问

    image-20210910162754973

    image-20210910163152342

  • 停止服务

    [root@master composetest]# docker-compose down
    Stopping composetest_redis_1 ... done
    Stopping composetest_web_1   ... done
    Removing composetest_redis_1 ... done
    Removing composetest_web_1   ... done
    Removing network composetest_default
    

yaml 规则

官网介绍:https://docs.docker.com/compose/compose-file/

# 三层
version: ''  #版本
services: ''  #服务
	服务1: web
		# 服务配置
		images
		build
		network
		...
	服务2: Redis
		...
	服务3: redis
# 其他配置 网络/卷、全局规则
volumes:
networks:
configs:

作者:likaifei

出处:https://www.cnblogs.com/likaifei/p/16707403.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   adai_kfl  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示