您当前的位置:首页 > 电脑百科 > 程序开发 > 容器

Docker从入门到精通之Docker Compose

时间:2022-05-16 13:15:40  来源:  作者:上海滩1y4C

Compose是一个用于定义和运行多容器Docker应用程序的工具。使用Compose,您可以使用YAML文件来配置应用程序的服务。然后,只需一个命令,就可以从配置中创建并启动所有服务。

Install Docker Compose

  1. 下载docker compose
$  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
  1. 给docker compose设置可执行权限
$ sudo chmod +x /usr/local/bin/docker-compose
  1. 验证
$ docker-compose --version

Uninstallation

$ sudo rm /usr/local/bin/docker-compose

Getting Started

Python构建一个简易网页统计网页点击量,docker-compose进行发布

Step1:创建项目

  1. 创建项目目录
  2. $ mkdir test_web
    $ cd test_web
  3. 在项目目录中创建App.py文件,并把下面代码复制进去
  4. 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)
  5. 创建requirements.txt文件,以下内容复制进去
flask
redis

Step2:创建Dockerfile文件

FROM python:3.7-alpine
WORKDIR /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"]

Step3:在docker-compose.yml中定义services

version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

Step4:用Docker compose构建和运行app

  1. 进入项目目录,运行docker-compose up
  2. $ docker-compose up
  3. 在浏览器访问http://localhost:5000/ ,刷新页面看变化
  4. 查看使用compose构建的镜像
  5. $ docker images

Step5:绑定一个数据卷

version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
    environment:
      FLASK_ENV: development
  redis:
    image: "redis:alpine"

将当前目录与容器的/code目录绑定,这样可以动态修改代码

Step6:重新构建和运行app

先docker-compose down停止服务,在构建

$ docker-compose down
$ docker-compose up

Compose file

用YAML文件定义服务,默认文件是docker-compose.yml,包含4个顶级key,version、services、networks、volumes

参考compose-spec/spec.md at master · compose-spec/compose-spec · GitHub

version

指定本 yml 依从的 compose版本

services

定义多个应用服务,包含环境配置、镜像构建等

build

指定构建镜像的路径

version: "3.9"
services:
  webapp:
    build: ./app

blkio_config

定义服务的block IO配置,参考compose-spec/spec.md at master · compose-spec/compose-spec · GitHub

container_name

指定自定义容器名称

depends_on

定义服务间启动或关闭的依赖关系

services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

command

覆盖容器启动的默认命令

command: [ "bundle", "exec", "thin", "-p", "3000" ]

domainname

domainname declares a custom domain name to use for the service container.

entrypoint

覆盖容器默认的entrypoint

env_file

从文件中添加环境变量到容器,可以是一个或多个文件

env_file: .env
env_file:
  - ./a.env
  - ./b.env

文件格式:

# Set Rails/Rack environment
RACK_ENV=development
VAR="quoted"

environment

添加环境变量

environment:
  RACK_ENV: development
  SHOW: "true"
  USER_INPUT:

expose

暴露端口,但不映射到宿主机,只被连接的服务访问,仅可以指定内部端口

expose:
  - "3000"
  - "8000"

healthcheck

用于检测 docker 服务是否健康运行。

healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost"] # 设置检测程序
  interval: 1m30s  # 设置检测间隔
  timeout: 10s # 设置检测超时时间
  retries: 3 # 设置重试次数
  start_period: 40s # 启动后,多少秒开始启动检测程序

image

指定容器运行的镜像

image: redis:5

labels

设置容器标签

labels:
  com.example.description: "Accounting webapp"
  com.example.department: "Finance"
labels:
  - "com.example.description=Accounting webapp"
  - "com.example.department=Finance"

links

连接到另一个容器的网络,简单将就是让容器相互连通

web:
  links:
    - db
    - db:database
    - redis

logging

服务的日志记录配置,driver:指定服务容器的日志记录驱动程序,默认值为json-file。有以下三个选项

driver: "json-file"
driver: "syslog"
driver: "none"

仅在 json-file 驱动程序下,可以使用以下参数,限制日志得数量和大小。

logging:
  driver: json-file
  options:
    max-size: "200k" # 单个文件大小为200k
    max-file: "10" # 最多10个文件

syslog 驱动程序下,可以使用 syslog-address 指定日志接收地址。

logging:
  driver: syslog
  options:
    syslog-address: "tcp://192.168.0.42:123"

network_mode

设置网络模式,格式如下:

network_mode: "bridge" #桥接模式
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"

networks

配置容器连接的网络

services:
  some-service:
    networks:
      - some-network
      - other-network
networks:
  some-network:
    # Use a custom driver
    driver: custom-driver-1
  other-network:
    # Use a custom driver which takes special options
    driver: custom-driver-2
services:
  frontend:
    image: awesome/webapp
    networks:
      - front-tier
      - back-tier

  monitoring:
    image: awesome/monitoring
    networks:
      - admin

  backend:
    image: awesome/backend
    networks:
      back-tier:
        aliases:
          - database
      admin:
        aliases:
          - MySQL

networks:
  front-tier:
  back-tier:
  admin:

ipv4_address, ipv6_address

指定ip地址

services:
  frontend:
    image: awesome/webapp
    networks:
      front-tier:
        ipv4_address: 172.16.238.10
        ipv6_address: 2001:3984:3989::10

networks:
  front-tier:
    ipam:
      driver: default
      config:
        - subnet: "172.16.238.0/24"
        - subnet: "2001:3984:3989::/64"

ports

端口映射,映射主机与容器端口,格式:Host:ontainer

ports:
     - "5000:5000"

restart

容器重启策略

restart: "no"
restart: always
restart: on-failure
restart: unless-stopped

secrets

存储敏感数据,比如密码

services:
  frontend:
    image: awesome/webapp
    secrets:
      - server-certificate
secrets:
  server-certificate:
    file: ./server.cert

volumes

将主机数据卷挂载到容器

services:
  db:
    image: postgres:latest
    volumes:
      - "/localhost/postgres.sock:/var/run/postgres/postgres.sock"
      - "/localhost/data:/var/lib/postgresql/data"

working_dir

覆盖容器工作目录

Volumes 顶级目录

services:
  backend:
    image: awesome/database
    volumes:
      - db-data:/etc/data

  backup:
    image: backup-service
    volumes:
      - db-data:/var/lib/backup/data

volumes:
  db-data:

Networks 顶级目录

services:
  frontend:
    image: awesome/webapp
    networks:
      - front-tier
      - back-tier

networks:
  front-tier:
  back-tier:
    driver: bridge

docker-compose 命令

$ docker-compose --help
Define and run multi-container applications with Docker.

Usage:
  docker-compose [-f <arg>...] [--profile <name>...] [options] [COMMAND] [ARGS...]
  docker-compose -h|--help

Options:
  -f, --file FILE             Specify an alternate compose file
                              (default: docker-compose.yml)
  -p, --project-name NAME     Specify an alternate project name
                              (default: directory name)
  --profile NAME              Specify a profile to enable
  --verbose                   Show more output
  --log-level LEVEL           Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  --no-ansi                   Do not print ANSI control characters
  -v, --version               Print version and exit
  -H, --host HOST             Daemon socket to connect to

  --tls                       Use TLS; implied by --tlsverify
  --tlscacert CA_PATH         Trust certs signed only by this CA
  --tlscert CLIENT_CERT_PATH  Path to TLS certificate file
  --tlskey TLS_KEY_PATH       Path to TLS key file
  --tlsverify                 Use TLS and verify the remote
  --skip-hostname-check       Don't check the daemon's hostname against the
                              name specified in the client certificate
  --project-directory PATH    Specify an alternate working directory
                              (default: the path of the Compose file)
  --compatibility             If set, Compose will attempt to convert deploy
                              keys in v3 files to their non-Swarm equivalent

Commands:
  build              Build or rebuild services
  bundle             Generate a Docker bundle from the Compose file
  config             Validate and view the Compose file
  create             Create services
  down               Stop and remove containers, networks, images, and volumes
  events             Receive real time events from containers
  exec               Execute a command in a running container
  help               Get help on a command
  images             List images
  kill               Kill containers
  logs               View output from containers
  pause              Pause services
  port               Print the public port for a port binding
  ps                 List containers
  pull               Pull service images
  push               Push service images
  restart            Restart services
  rm                 Remove stopped containers
  run                Run a one-off command
  scale              Set number of containers for a service
  start              Start services
  stop               Stop services
  top                Display the running processes
  unpause            Unpause services
  up                 Create and start containers
  version            Show the Docker-Compose version information

Swarm集群



Tags:Docker Compose   点击:()  评论:()
声明:本站部分内容及图片来自互联网,转载是出于传递更多信息之目的,内容观点仅代表作者本人,如有任何标注错误或版权侵犯请与我们联系(Email:2595517585@qq.com),我们将及时更正、删除,谢谢。
▌相关推荐
Compose是一个用于定义和运行多容器Docker应用程序的工具。使用Compose,您可以使用YAML文件来配置应用程序的服务。然后,只需一个命令,就可以从配置中创建并启动所有服务。Inst...【详细内容】
2022-05-16  Tags: Docker Compose  点击:(19)  评论:(0)  加入收藏
Compose 简介    通过前面几篇文章的学习,我们可以通过 Dockerfile 文件让用户很方便的定义一个单独的应用容器。然而,在日常工作中,经常会碰到需要多个容器相互配合来完成...【详细内容】
2020-09-08  Tags: Docker Compose  点击:(122)  评论:(0)  加入收藏
基本概念默认情况下,Compose会为我们的应用创建一个网络,服务的每个容器都会加入该网络中。这样,容器就可被该网络中的其他容器访问,不仅如此,该容器还能以服务名称作为hostname...【详细内容】
2019-10-24  Tags: Docker Compose  点击:(170)  评论:(0)  加入收藏
▌简易百科推荐
标题比较晦涩难懂,简单解释下:假如一个服务器有五个ip,我们部署了某一个服务,我们可以在配置文件里面修改IP为五个IP,但是服务器始终只有一个出口,最后落地出口还是一个IP,所以我们...【详细内容】
2022-05-19  运维幼儿    Tags:docker   点击:(9)  评论:(0)  加入收藏
Compose是一个用于定义和运行多容器Docker应用程序的工具。使用Compose,您可以使用YAML文件来配置应用程序的服务。然后,只需一个命令,就可以从配置中创建并启动所有服务。Inst...【详细内容】
2022-05-16  上海滩1y4C    Tags:Docker Compose   点击:(19)  评论:(0)  加入收藏
一:简介Mailu.io是一款免费开源且性能强大、功能丰富的域名邮箱系统。它基于Docker, 具有部署简单,可移植性高,备份方便等多种优势。主要的功能: 基本的邮件服务器 IMAP IMAP+...【详细内容】
2022-05-11  运维笔记ywbj    Tags:mailu邮件   点击:(41)  评论:(0)  加入收藏
前言Rainbond 是一个云原生应用管理平台,使用简单,不需要懂容器、Kubernetes和底层复杂技术,支持管理多个Kubernetes集群,和管理企业应用全生命周期。但是随着云原生时代的一点...【详细内容】
2022-05-11  Rainbond开源    Tags:容器   点击:(11)  评论:(0)  加入收藏
1.Docker 迁移存储目录默认情况系统会将 Docker 容器存放在 /var/lib/docker 目录下 [问题起因] 今天通过监控系统,发现公司其中一台服务器的磁盘快慢,随即上去看了下,发现 /va...【详细内容】
2022-05-09  奇妙的Linux世界  微信公众号  Tags:Docker   点击:(19)  评论:(0)  加入收藏
1. 介绍1.1 介绍大家已经跟着福哥学习了Docker私有仓库的搭建和基本使用方法了,现在有一个问题:如果仓库里面的镜像老了,想更新一下,怎么办呢?Registry服务器的镜像是不支持更新...【详细内容】
2022-05-06  同福编程    Tags:Docker   点击:(19)  评论:(0)  加入收藏
背景 普通消息队列,消息一旦入队就会被消费者立刻消费,而延迟队列则需要指定固定时间后被延迟消费.docker安装rabbitMq延迟队列插件版本学习的话可以去官网下载rabbitmq并通...【详细内容】
2022-04-29  没情调的程序男    Tags:docker   点击:(33)  评论:(0)  加入收藏
一:备份查看docker mysql 方法一:一步一步来,常规备份,进入容器中,用mysqldump备份。sudo docker exec -it mysql /bin/bash#进入mysql容器mysqldump -uroot -p123456 --all-data...【详细内容】
2022-04-24  运维笔记ywbj    Tags:docker   点击:(49)  评论:(0)  加入收藏
无论选择是什么,Spring 都能容纳这两种风格,甚至可以将它们混合在一起。值得指出的是,通过它的 Java 配置选项,Spring 允许注解以一种非入侵的方式使用,不触碰目标组件源码和那些...【详细内容】
2022-04-18  辗转难眠    Tags:Spring   点击:(30)  评论:(0)  加入收藏
1.原生安装mysql步骤多,系统环境污染重,卸载麻烦,耗时耗力2.Docker安装Mysql,提前准备,一行命令安装,卸载无残留,再次安装数据不丢失3.需要提前安装Docker环境,主页有相关文...【详细内容】
2022-04-14  用程序提高效率    Tags:Docker   点击:(45)  评论:(0)  加入收藏
相关文章
    无相关信息
站内最新
站内热门
站内头条