Docker-compose教程

来自linux中国网wiki
跳到导航 跳到搜索


可以 Dockerfile 创建容器,docker-compse实现部署 或者直接用官方的img 利用docker-compse实现部署

introduce

Compose项目来源于之前的fig项目,使用python语言编写,与docker/swarm配合度很高。

工程、服务、容器

    Docker Compose 将所管理的容器分为三层,分别是工程(project)、服务(service)、容器(container)
    Docker Compose 运行目录下的所有文件(docker-compose.yml)组成一个工程,一个工程包含多个服务,每个服务中定义了容器运行的镜像、参数、依赖,一个服务可包括多个容器实例





Compose 是 Docker 容器进行编排的工具,定义和运行多容器的应用,可以一条命令启动多个容器,使用Docker Compose不再需要使用shell脚本来启动容器。 

Compose 通过一个配置文件来管理多个Docker容器,在配置文件中,所有的容器通过services来定义,然后使用docker-compose脚本来启动,停止和重启应用,和应用中的服务以及所有依赖服务的容器,非常适合组合使用多个容器进行开发的场景。

docker-compose默认的模板文件是 docker-compose.yml,其中定义的每个服务都必须通过 image 指令指定镜像或 build 指令(需要 Dockerfile)来自动构建。

其它大部分指令都跟 docker run 中的类似。
如果使用 build 指令,在 Dockerfile 中设置的选项(例如:CMD, EXPOSE, VOLUME, ENV 等) 将会自动被获取,无需在 docker-compose.yml 中再次设置。

使用Compose 基本上分为三步:
1.Dockerfile 定义应用的运行环境
2.docker-compose.yml 定义组成应用的各服务
3.docker-compose up 启动整个应用
--------------------- 

Compose 项目是 Docker 官方的开源项目,负责实现对 Docker 容器集群的快速编排。

在日常工作中,经常会碰到需要多个容器相互配合来完成某项任务的情况。例如要实现一个 Web 项目,除了 Web服务容器本身,往往还需要再加上后端的数据库服务容器,甚至还包括负载均衡容器等。

Compose 恰好满足了这样的需求。它允许用户通过一个单独的 docker-compose.yml 模板文件(YAML 格式)来定义一组相关联的应用容器为一个项目。

Compose 中有两个重要的概念:

    服务 (service):一个应用的容器,实际上可以包括若干运行相同镜像的容器实例。

    项目 (project):由一组关联的应用容器组成的一个完整业务单元,在 docker-compose.yml 文件中定义。

Docker-compose常用命令


#日志过滤
docker logs xx -f 2>&1| grep --line-buffered xxx
docker-compose --help

docker-compose up -d nginx                     构建建启动nignx容器 # #这个是写在yml里面的server名  查看 文件, 不是容器名

docker-compose exec nginx bash            登录到nginx容器中

docker-compose down                              删除所有nginx容器,镜像

docker-compose ps                                   显示所有容器

docker-compose restart nginx                   重新启动nginx容器 #这个是写在yml里面的server名  不是容器名

docker-compose run --no-deps --rm php-fpm php -v  在php-fpm中不启动关联容器,并容器执行php -v 执行完成后删除容器

docker-compose build nginx                     构建镜像 。        

docker-compose build --no-cache nginx   不带缓存的构建。

docker-compose logs  nginx                     查看nginx的日志 

docker-compose logs -f nginx                   查看nginx的实时日志
 

docker-compose config  -q                        验证(docker-compose.yml)文件配置,当配置正确时,不输出任何内容,当文件配置错误,输出错误信息。 

docker-compose events --json nginx       以json的形式输出nginx的docker日志

docker-compose pause nginx                 暂停nignx容器

docker-compose unpause nginx             恢复ningx容器

docker-compose rm nginx                       删除容器(删除前必须关闭容器)

docker-compose stop nginx                    停止nignx容器

docker-compose start nginx                    启动nignx容器

docker-compose exec nginx nginx -t
docker-compose exec nginx nginx -s reload


note:
docker-compose   知道补充

docker-compose  ps 
          Name                        Command               State                        Ports                      
--------------------------------------------------------------------------------------------------------------------
docker4jenkins_jenkins_1   /sbin/tini -- /usr/local/b ...   Up      0.0.0.0:50000->50000/tcp, 0.0.0.0:7099->8080/tcp

 docker-compose  stop  jenkins #后面是加server名  服务名称
 
 docker-compose.yml 
 
 services:
  jenkins:
    image: jenkins/jenkins:lts

所以 
docker-compose  start   jenkins

install

#方法1 如果是国内网络太慢 可以把变量换成对应的值 然后先在desktop 下载回来 
sudo curl -L "https://github.com/docker/compose/releases/download/1.24.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

#方法 2  有时axel最快了
#https://github.com/docker/compose/releases/download/1.24.0/docker-compose-linux-x86_64   -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
$  docker-compose --version
docker-compose version 1.24.0, build 0aa59064

Get started with Docker Compose

Step 1: Setup

1.Create a directory for the project:

 mkdir composetest &&  cd composetest

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

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(host="0.0.0.0", debug=True)  

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

flask
redis

Step 2: Create a Dockerfile

FROM python:3.4-alpine
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD ["python", "app.py"]

Step 3: Define services in a Compose file

Create a file called docker-compose.yml

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

Step 4: Build and run your app with Compose

docker-compose up -d# (后台运行这些containers) 还是这个好 
#马上访问就行了 哈哈 不用一直等
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

Enter http://0.0.0.0:5000/ in a browser to see the application running.

Step 5: Edit the Compose file to add a bind mount

Edit docker-compose.yml in your project directory to add a bind mount for the web service:

version: '3'
services:
  web:
    build: .
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  redis:
    image: "redis:alpine"
#胶布的端口是机器的5000 后面的端口是容器的5000  volumes 也是这样顺序

The new volumes key mounts the project directory (current directory) on the host to /code inside the container, allowing you to modify the code on the fly, without having to rebuild the image 把当前目录mounts 到容器的/code

  volumes:
    - ~/test/composetest:/code  #   将主机的当前目录映射为容器内部的 /code数据卷           把当前目录 ~/test/composetest mounts 到容器的/code


eg:

#容器
evan@latop:~/test/composetest$ docker exec -it b4f882c81522 /bin/sh 
/code # pwd
/code
/code # ls 
Dockerfile           app.py               app.py~              docker-compose.yml   docker-compose.yml~  requirements.txt

#母机
evan@latop:~/test/composetest$ ls 
app.py  app.py~  docker-compose.yml  docker-compose.yml~  Dockerfile  requirements.txt


Step 6: Re-build and run the app with Compose

From your project directory, type docker-compose up to build the app with the updated Compose file, and run it.

Step 7: Update the application

Because the application code is now mounted into the container using a volume, you can make changes to its code and see the changes instantly, without having to rebuild the image. 可见 有mount 后 只改变母机的不用rebuild 了

Change the greeting in app.py and save it. For example, change the Hello World! message to Hello from Docker!:

return 'Hello from Docker! I have been seen {} times.\n'.format(count)

Refresh the app in your browser. The greeting should be updated, and the counter should still be incrementing.

常用参数

ports

HOST:CONTAINER格式或者只是指定容器的端口,宿主机会随机映射端口。
基本遵循规则是从宿主机映射到容器,默认是tcp,如果使用udp,比如5600,要记得在运行时或者yaml文件端口处比如写:5000/udp

docker和docker-compose 端口映射

links/external_links参数

-link  同一个物理机之前  


external_links
Docker平台的组合功能提供了一个叫“外部链接”(“external_links”)的设置选项,能用来接连那些在不同组合文件中定义的容器:

eg 
    hostname: rabbitmq02
    extra_hosts:
      - "rabbitmq01:10.3.10.141" #前面是hostname 后面是ip 


Docker使用Link在容器之间建立连接

Docker的组合功能:如何用external_links选项连接组合文件外部定义的容器

如何使不同主机上的docker容器互相通信

docker compose 中难缠的网络问题

privileged

run on command 

docker run \
--detach \
-p 8095:8080 \
--privileged \
-m 4096M \
--name jira \
evan886/jira:latest

on yml file 

web:
  image: an_image-image:1.0
  container_name: my-container
  privileged: true
  entrypoint: ["/usr/sbin/init"]
  ports:
    - "8280:8280"

how to bring up a docker-compose container as privileged

restart

. 

默认值为 no ,即在任何情况下都不会重新启动容器;当值为 always 时,容器总是重新启动;当值为 on-failure 时, on-failure 如果退出代码指示的故障错误政策,重启容器。

restart: "no"

restart: always

restart: on-failure

restart: unless-stopped

注意:使用(版本3)Compose文件在群集模式下部署堆栈时,将忽略此选项,改用restart_policy

trouble

509


docker x509: certificate has expired or is not yet valid

1.如果是系统时间问题好办,直接更新一下就行了:

ntpdate cn.pool.ntp.or


解决docker x509: certificate has expired or is not yet valid

Question

docker-compose up

ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running?
If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable. 


solve

Use the command  sudo systemctl edit docker.service  to open an override file for docker.service in a text editor.

Add or modify the following lines, substituting your own values.

[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock
Save the file.

Reload the systemctl configuration.

 $ sudo systemctl daemon-reload
Restart Docker:

 $ sudo systemctl restart docker.service
Check to see whether the change was honored by reviewing the output of netstat to confirm dockerd is listening on the configured port.

$ sudo netstat -lntp | grep dockerd
tcp        0      0 127.0.0.1:2375          0.0.0.0:*               LISTEN      3758/dockerd

vim ~/.bashrc
export DOCKER_HOST=tcp://localhost:2375

https://stackoverflow.com/questions/27763340/docker-opts-do-not-work-in-config-file-etc-default-docker

https://stackoverflow.com/questions/44678725/cannot-connect-to-the-docker-daemon-at-unix-var-run-docker-sock-is-the-docker

其它办法 没过过 正确的是将当前用户加入docker组 jing@ubuntu:/tmp/docker$ sudo gpasswd -a ${USER} docker

see also

使用文档 Docker:Docker Compose 详解

Docker Compose 配置文件详解

https://www.runoob.com/docker/docker-compose.html

docker-compose文件语法解析(v3.x)


安装文档吧 官方文档永远是最帅的

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

docker-compose命令参数及使用(3)

Docker-compose.yml文件参数详解

Docker 容器编排利器 Docker Compose

Docker:Docker Compose 详解

Docker-compose常用命令

Docker-compose命令详解

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

Docker三剑客之Docker Compose

https://blog.csdn.net/zhugeaming2018/article/details/81518327

docker-compose常用命令

Docker:Docker Compose 详解


使用 docker-compose 替代 docker run

Docker系列之(五):使用Docker Compose编排容器


Docker(四)----Docker-Compose 详解

安装docker-compose并统一拉取镜像

『中级篇』Docker Compose的安装和基本使用(39)

Docker学习(6)Docker Compose介绍和编配

Docker-Docker Compose

小白学Docker之Compose

docker-compose教程安装,使用, 快速入门

docker-compose是个好东西,越用越香


一步步学会用docker部署应用(nodejs版)

理解Docker(8):Docker 存储之卷(Volume)

深入理解Docker Volume(一)

深入理解Docker Volume(一)

Docker-compose搭建nginx+php+mysql