zoukankan      html  css  js  c++  java
  • dockercompose 简介

    一句话
    docker-compose 是用来做docker 的多容器控制

    docker-compose 是什么

    docker-compose 是一个用来把 docker 自动化的东西。
    有了 docker-compose 你可以把所有繁复的 docker 操作全都一条命令,自动化的完成。

    为什么要用 docker-compose,他解决了什么

    用通俗的语言来说,我们平时操作 docker 还是很原始的一系列动作,你手动使用 docker 的动作可以拆分成

    1. 找到一个系统镜像 // docker search
    2. 安装好 vm 或者 virtual box // apt-get install docker
    3. 在 vm 中安装镜像 // docker run -d -it 你的镜像
    4. 略..

    这是最小的动作, 如果你要映射硬盘,设置nat网络或者桥接网络,等等…你就要做更多的 docker 操作, 这显然是非常没有效率的。

    但是我们写在 docker-compose.file 里面就很好了。 你只需要写好后 只运行一句
    docker-compose up -d
    一切都是那么的简单

    那么哪里可以买到呢?

    你要你能上网,到处都可以得到他。
    我自己的机器上有 python&pip 的环境,所以我的安装非常简单


    先确定你是不是安装了 docker

    CentOS7下安装Docker-Compose

    Docker-Compose是一个部署多个容器的简单但是非常必要的工具.

    安装Docker-Compose之前,请先安装 python-pip

    安装 python-pip

    1、首先检查linux有没有安装python-pip包,终端执行 pip -V

    [root@localhost templates]# pip -V
    -bash: pip: 未找到命令

    2、没有python-pip包就执行命令 yum -y install epel-release

    [root@localhost templates]# yum -y install epel-release
    已加载插件:fastestmirror
    Loading mirror speeds from cached hostfile
    ...

    3、执行成功之后,再次执行yum -y install python-pip

    [root@localhost templates]# yum -y install python-pip
    已加载插件:fastestmirror
    Loading mirror speeds from cached hostfile
    ...

    4、对安装好的pip进行升级 pip install --upgrade pip

    [root@localhost templates]# pip install --upgrade pip
    Collecting pip
    ...

    至此,pip安装好了,执行pip -V 再次检查pip环境。

    [root@localhost templates]# pip -V
    pip 19.0.3 from /usr/lib/python2.7/site-packages/pip (python 2.7)
    [root@localhost templates]#

    安装Docker-Compose

    终端执行:pip install docker-compose

    [root@localhost templates]# pip install docker-compose
    DEPRECATION: Python 2.7 will reach the end of its li

    检查docker-compose 安装:docker-compose -version

    [root@localhost templates]# docker-compose -version
    docker-compose version 1.23.2, build 1110ad0
    [root@localhost templates]# 

    ubuntu

    我的环境是
    linux-ubuntu:python2:pip
    所以我的安装
    pip install docker-compose
    如此简单

    从一个小例开始

    root@ubuntu:~/test# cat docker-compose.yml 
    version: '2'
    services:
      mariadb:
        image: 'bitnami/mariadb:latest'
        environment:
          - ALLOW_EMPTY_PASSWORD=yes
        volumes:
          - /path/to/mariadb-persistence:/bitnami/mariadb
    
    root@ubuntu:~/test# docker-compose up
    Creating network "test_default" with the default driver
    Creating test_mariadb_1
    Attaching to test_mariadb_1
    mariadb_1  | 
    mariadb_1  | Welcome to the Bitnami mariadb container
    mariadb_1  | Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-mariadb
    mariadb_1  | Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-mariadb/issues
    mariadb_1  | Send us your feedback at containers@bitnami.com
    mariadb_1  | 
    mariadb_1  | nami    INFO  Initializing mariadb
    mariadb_1  | mariadb INFO  ==> Creating 'root' user with unrestricted access...
    mariadb_1  | mariadb INFO  ==> Flushing privileges...
    mariadb_1  | mariadb INFO  ==> Enabling remote connections...
    mariadb_1  | mariadb INFO 
    mariadb_1  | mariadb INFO  ########################################################################
    mariadb_1  | mariadb INFO   Installation parameters for mariadb:
    mariadb_1  | mariadb INFO     Root Password: Not set during installation
    mariadb_1  | mariadb INFO   (Passwords are not shown for security reasons)
    mariadb_1  | mariadb INFO  ########################################################################
    mariadb_1  | mariadb INFO 
    mariadb_1  | nami    INFO  mariadb successfully initialized
    mariadb_1  | INFO  ==> Starting mariadb...
    mariadb_1  | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB: Highest supported file format is Barracuda.
    mariadb_1  | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB: 128 rollback segment(s) are active.
    mariadb_1  | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB: Waiting for purge to start
    mariadb_1  | 2017-03-05 15:01:27 139903487235968 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.34-79.1 started; log sequence number 1616829
    mariadb_1  | 2017-03-05 15:01:27 139902956046080 [Note] InnoDB: Dumping buffer pool(s) not yet started
    

    先安装吧

    如果你和我的环境相同,请直接看我的 docker-compose 安装

    如果是别的话,别担心,这里有
    安装指南

    helloworld

    root@ubuntu:~/test# cat docker-compose.yml 
    version: '2'
    services:
      mariadb:
        image: 'bitnami/mariadb:latest'
        environment:
          - ALLOW_EMPTY_PASSWORD=yes
        volumes:
          - /path/to/mariadb-persistence:/bitnami/mariadb
        command: echo "hello world"
    root@ubuntu:~/test# 
    root@ubuntu:~/test# 
    root@ubuntu:~/test# docker-compose up      
    Starting test_mariadb_1
    Attaching to test_mariadb_1
    mariadb_1  | 
    mariadb_1  | Welcome to the Bitnami mariadb container
    mariadb_1  | Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-mariadb
    mariadb_1  | Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-mariadb/issues
    mariadb_1  | Send us your feedback at containers@bitnami.com
    mariadb_1  | 
    mariadb_1  | hello world
    test_mariadb_1 exited with code 0
    

    服务更新

    软升级

    $ docker-compose stop wordpress
    停止容器运行
    
    $ docker-compose rm wordpress
    删除老旧的容器
    更新你的 image
    
    $ docker-compose start wordpress
    启动新容器
    

    还比如

    你的 nginx 更新了配置文件之后

    docker-compose restart nginx

    硬升级

    docker-compose stop

    升级你的程序

    你要重新
    docker-compose up

    从日志得到需要的信息

    直接使用 logs

    docker-compose logs nginx
    欧 shit 直接给我屏幕刷爆了

    使用类似linux tail 命令

    我们的 tial 命令一般是什么样的呢
    tail -f xx.file

    我们的docker-compose log 却是这样

    root@ubuntu:~# docker-compose logs -f --tail 10 nginx
    Attaching to root_nginx_1
    nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:18 +0000] "GET /wp-admin/ HTTP/1.1" 302 0 "http://www.yunlan.name/wp-admin/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"
    nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:18 +0000] "GET /wp-login.php?action=lostpassword HTTP/1.1" 200 1201 "http://www.yunlan.name/wp-login.php?action=lostpassword" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"
    nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:18 +0000] "GET /wp-login.php?action=lostpassword HTTP/1.1" 200 1201 "-" "Mozilla"
    nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:18 +0000] "GET /wp-login.php?redirect_to=http%3A%2F%2Fwww.yunlan.name%2Fwp-admin%2F&reauth=1 HTTP/1.1" 200 1265 "http://www.yunlan.name/wp-admin/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"
    nginx_1 | 64.79.100.22 - - [05/Mar/2017:16:57:19 +0000] "GET /wp-login.php?redirect_to=http%3A%2F%2Fwww.yunlan.name%2Fwp-admin%2F&reauth=1 HTTP/1.1" 200 1265 "-" "Mozilla"
    nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:57:52 +0000] "GET /robots.txt HTTP/1.1" 200 134 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
    nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:58:03 +0000] "GET / HTTP/1.1" 499 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
    nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:58:03 +0000] "GET / HTTP/1.1" 200 3844 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
    nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:58:03 +0000] "GET /wp-content/plugins/code-prettify/prettify/run_prettify.js?ver=1.3.4 HTTP/1.1" 200 7600 "http://www.yunlan.name/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
    nginx_1 | 117.150.55.119 - - [05/Mar/2017:16:58:04 +0000] "GET /wp-content/plugins/code-prettify/prettify/prettify.css HTTP/1.1" 200 722 "http://www.yunlan.name/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"

    最近的10条开始

    docker-compose 常用命令

    
    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
      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
    

    解释一下

    build 构建或重建服务
    help 命令帮助
    kill 杀掉容器
    logs 显示容器的输出内容
    port 打印绑定的开放端口
    ps 显示容器
    pull 拉取服务镜像
    restart 重启服务
    rm 删除停止的容器
    run 运行一个一次性命令
    scale 设置服务的容器数目
    start 开启服务
    stop 停止服务
    up 创建并启动容器
    

    docker-compose 如何配置

    先看看我自己写的一个 docker-compose.yml

    version: '2'
    services:
        nginx:
                image: bitnami/nginx:latest
                ports:
                    - '80:80'
                    - '1443:443'
                volumes:
                    - /root/wp_yunlan/nginx/:/bitnami/nginx/
        mariadb:
                image: bitnami/mariadb:latest
                volumes:
                    - /root/wp_yunlan/mariadb:/bitnami/mariadb
        wordpress:
                image: bitnami/wordpress:latest
                depends_on:
                    - mariadb
                    - nginx
                environment:
                    - WORDPRESS_USERNAME=neptunemoon    #这个账户你是自己设定的
                    - WORDPRESS_PASSWORD=123123         #这个密码是你自己设定的
                ports:
                    - '8080:80'
                    - '8081:443'
                volumes:
                    - /root/wp_yunlan/wordpress:/bitnami/wordpress
                    - /root/wp_yunlan/apache:/bitnami/apache
                    - /root/wp_yunlan/php:/bitnami/php
    

    nginx 和 mariadb,wordpress 是要启动的三个服务

    顺序不是重要的,我们看见wordpress中有个 depends_on: 的属性

    depends_on: 依赖

    代表wordpress 依赖于

    - mariadb
    - nginx
    

    两个服务, 所以他们两个会先启动

    image: 镜像

    就是你的 docker 镜像
    我们用
    docker search mariadb
    找到我们需要的镜像

    root@ubuntu:~/test# docker search mariadb
    NAME                         DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
    mariadb                      MariaDB is a community-developed fork of M...   1192      [OK]       
    paintedfox/mariadb           A docker image for running MariaDB 5.5, a ...   29                   [OK]
    bitnami/mariadb              Bitnami MariaDB Docker Image                    29                   [OK]
    million12/mariadb            MariaDB 10 on CentOS-7 with UTF8 defaults       12                   [OK]
    toughiq/mariadb-cluster      Dockerized Automated MariaDB Galera Cluste...   9                    [OK]
    webhippie/mariadb            Docker images for mariadb                       6                    [OK]
    panubo/mariadb-galera        MariaDB Galera Cluster                          6                    [OK]
    kakilangit/mariadb           Docker for MariaDB with OQGraph & TokuDB E...   5                    [OK]
    maxexcloo/mariadb            Service container with MariaDB installed a...   4                    [OK]
    tcaxias/mariadb              MariaDB containers                              1                    [OK]
    desertbit/mariadb            This is an extended docker image of the of...   1                    [OK]
    russmckendrick/mariadb       A MariaDB image                                 1                    [OK]
    drupaldocker/mariadb         MariaDB for Drupal                              1                    [OK]
    jpco/mariadb                 Mariadb, so I can have it on my raspberry       1                    [OK]
    clearlinux/mariadb           MariaDB Server                                  1                    [OK]
    danielsreichenbach/mariadb   Minimal MariaDB container to be used as co...   0                    [OK]
    lucidfrontier45/mariadb      Mariadb with some customizable properties       0                    [OK]
    codete/mariadb               MariaDB docker image used at Codete.            0                    [OK]
    dogstudio/mariadb            MariaDB Container for Dogs                      0                    [OK]
    babim/mariadb                Mariadb Server on Alpine or Debian. Check ...   0                    [OK]
    objectstyle/mariadb          ObjectStyle MariaDB Docker Image                0                    [OK]
    oriaks/mariadb               MariaDB                                         0                    [OK]
    yannickvh/mariadb            Custom build of MariaDB based on the offic...   0                    [OK]
    gymnae/mariadb               Alpine based simple mariadb                     0                    [OK]
    nimmis/mariadb               MariaDB multiple versions based on nimmis/...   0                    [OK]
    root@ubuntu:~/test# 
    

    好了,就是bitnami/mariadb

    如果你看见有的么有 images ,而是一个 build, 那个说明这个不是用镜像的,而是使用 dockerfile 去构建容器。
    如果要说 dockerfile 又要花很久了

    想了解 dockerfile 可以看这里
    编写Dockerfile

    environment 环境变量

    这个是在好理解不过的了。
    不过这和我们程序语言设计层面的还是不一样的,这个是容器层面的环境变量。
    如果我们写程序做一些逻辑判断的时候,肯定会使用
    比如我们判断现在的编译器,我们会使用
    #if __GNUC__ 或者 #if _MSC_VER
    相应的,我们的容器里面肯定也有这样的逻辑,我们经常使用环境变量来传值,或者定义一个行为。写过程序的人都懂。

    ports 端口映射

    映射本机还有镜像的端口。这个没有什么好说的。

    volumes 文件映射

    有两种格式,
    可以对应 docker 操作中的 -v my/path/:/docker/path
    还可以使用单方面的 -v /path
    这样的话 就相当于 一个匿名映射, 其实还是在本机有对应目录的。

    使用docker inspect -f {{.Volumes}} /path 可以看到详细信息

    相对这个了解更多的 深入理解Docker Volume

    docker-compose 需要注意的

    我根据我自己的体验,给出几点需要注意的

    1. 不要把 docker 当做数据容器来使用,数据一定要用 volumes 放在容器外面
    2. 不要把 docker-compose 文件暴露给别人, 因为上面有你的服务器信息
    3. 多用 docker-compose 的命令去操作, 不要用 docker 手动命令&docker-compose 去同时操作
    4. 写一个脚本类的东西,自动备份docker 映射出来的数据。
    5. 不要把所有服务都放在一个 docker 容器里面

    针对需求开始部署了

    设定一个需求

    我假定现在我们的需求是做一个博客系统

    我们的第一印象肯定是 wordpress, 没有比这个更专业的了, 当然还有很多,我们使用 django 吧

    用过 django 的肯定会知道, django 一开始是要构造工程的。
    还有数据之类的

    我们拟订一个过程

    1. python 环境搭建
    2. django 环境搭建
    3. docker-compose.yml 写作
    4. django 构建工程
    5. django 数据库设定
    6. 开始运行
    7. 数据库同步

    简单的单机部署

    python 环境搭建

    Dockerfile

    ENV PYTHONUNBUFFERED 1
    RUN mkdir /root/testdjango/code    #都写上绝对路径, 注意不要跟我一样。
    WORKDIR /root/testdjango/code
    ADD requirements.txt /root/testdjango/code/
    RUN pip install -r requirements.txt
    ADD . /root/testdjango/code/
    

    python 的pip 有一个requirements.txt 文件来专门放依赖环境的

    django 环境搭建

    requirements.txt

    Django
    psycopg2
    

    docker-compose.yml 写作

    db:
      image: postgres
    web:
      build: .
      command: python manage.py runserver 0.0.0.0:8000
      volumes:
        - .:/code
      ports:
        - "8000:8000"
      links:
        - db
    

    django 构建工程

    docker-compose run web django-admin.py startproject docker_composeexample .

    django 数据库设定

    我们做了 volumes, django 的东西在本地有映射。
    做过 django 的人都知道 ,我们的设定都在 settings.py

    root@ubuntu:~/testdjango/docker_composeexample# cat settings.py 
    """
    Django settings for docker_composeexample project.
    
    Generated by 'django-admin startproject' using Django 1.10.6.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/1.10/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.10/ref/settings/
    """
    
    import os
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '3*@nbl2pu$hdmpe-hy&iko_cr_-$%9g=nu2=3x_^g(vy2463d6'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ROOT_URLCONF = 'docker_composeexample.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'docker_composeexample.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/1.10/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/1.10/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.10/howto/static-files/
    
    STATIC_URL = '/static/'
    root@ubuntu:~/testdjango/docker_composeexample# 
    

    我们只设置 数据库

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'postgres',
            'USER': 'postgres',
            'HOST': 'db',
            'PORT': 5432,
        }
    }
    

    开始运行

    docker-compose up

    数据库同步

    docker-compose run web python manage.py syncdb

    转自:https://www.cnblogs.com/neptunemoon/p/6512121.html

  • 相关阅读:
    linux命令3
    sersync和rsync数据实时同步配置
    java web框架
    处理 json数据,base64合成图片
    day032进程池(重点)进程池的同步、异步方法,回调函数;管道、数据共享
    day031同步锁、信号量、事件、队列、生成者消费者模型、Jionablequeue
    day030进程的两种创建方法,验证进程的空间隔离,join等待子进程
    day029socketserver模块实现并发,线程、 ftp上传或下载,打印进度条
    day028两种粘包现象,两种解决粘包的方法,subprocess, struck模块
    day027OSI七层协议;tcp三次握手,四次挥手;tcp与udp的区别及两者的撰写方式
  • 原文地址:https://www.cnblogs.com/duanxz/p/2980155.html
Copyright © 2011-2022 走看看