docker-compose入门及使用

一、docker-compose简介

docker-compose 是官方开源容器创建、多容器编排的工具。

我们知道一个完整的应用系统往往包含多个容器,相辅相成提供服务。如一个web应用需要包含web服务、数据库等,此时通过使用docker-compose来轻松实现对多容器的控制和管理。

开源地址:https://github.com/docker/compose


三、docker-compose安装

docker-compose由python编写,可以通过pip包管理安装

pip install docker-compose

#或yum方式安装
wget https://repo.huaweicloud.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo
yum install docker-compose

#或二进制安装
clone GitHubrelease

二、docker-compose的三个关键

Docker Compose 将所管理的容器分为三层,分别是工程(project)、服务(service)、容器(container)

docker-compose.yml文件所在目录为docker-compose工程,一个工程包含多个服务,每个服务中定义了容器运行的镜像、容器名、端口、网络等参数。即一个服务可包含多个容器实例。

如下的一个docker-compose.yml文件

version: '2.3'  
services:
  log:
    image: goharbor/harbor-log:v2.1.5
    container_name: harbor-log
    restart: always
    dns_search: .
    cap_drop:
      - ALL
    cap_add:
      - CHOWN
      - DAC_OVERRIDE
      - SETGID
      - SETUID
    volumes:
      - /var/log/harbor/:/var/log/docker/:z
      - type: bind
        source: ./common/config/log/logrotate.conf
        target: /etc/logrotate.d/logrotate.conf
      - type: bind
        source: ./common/config/log/rsyslog_docker.conf
        target: /etc/rsyslog.d/rsyslog_docker.conf
    ports:
      - 127.0.0.1:1514:10514
    networks:
      - harbor
  registry:
    image: goharbor/registry-photon:v2.1.5
    container_name: registry
    restart: always
    ...

三、docker-compose 常用命令

  • ps:列出所有运行容器
docker-compose ps
  • logs:查看服务日志输出
docker-compose logs
  • build:构建或者重新构建服务
docker-compose build
  • start:启动指定服务已存在的容器
docker-compose start nginx
  • stop:停止已运行的服务的容器
docker-compose stop nginx
  • rm:删除指定服务的容器
docker-compose rm nginx
  • up:构建、启动容器
docker-compose up
  • kill:通过发送 SIGKILL 信号来停止指定服务的容器
docker-compose kill nginx
  • pull:下载服务镜像
version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db
      
$ docker-compose pull db
Pulling db (postgres:latest)...
latest: Pulling from library/postgres
cd0a524342ef: Pull complete
9c784d04dcb0: Pull complete
d99dddf7e662: Pull complete
e5bff71e3ce6: Pull complete
cb3e0a865488: Pull complete
31295d654cd5: Pull complete
fc930a4e09f5: Pull complete
8650cce8ef01: Pull complete
61949acd8e52: Pull complete
527a203588c0: Pull complete
26dec14ac775: Pull complete
0efc0ed5a9e5: Pull complete
40cd26695b38: Pull complete
Digest: sha256:fd6c0e2a9d053bebb294bb13765b3e01be7817bf77b01d58c2377ff27a4a46dc
Status: Downloaded newer image for postgres:latest
  • scale:设置指定服务运气容器的个数.
docker-compose scale nginx=3 redis=3
  • run:在一个服务上执行一个命令
docker-compose run web bash

详细命令和介绍参考官方文档https://docs.docker.com/compose/reference/


四、docker-compose实践

使用docker-compose部署一个python web应用。

1.创建一个工程目录
 mkdir mycompose
 cd mycompose
2. 创建flask应用 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)
3.创建requirements.txt
flask
redis
4.创建Dockerfile文件
# syntax=docker/dockerfile:1
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"]
5.创建你的docker-compose.yml 包含两个容器 web和redis
version: "3.0"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"
6.构建和运行docker-compose工程
#此时你的工程目录如下:

[root@VM-0-5-centos mycompose]# ls
app.py  docker-compose.yml  Dockerfile  requirements.txt

docker-compose up

开始构建容器

image-20210510185543915

docker ps可查看到两个容器已经起来了

image-20210510231945597

验证安装 http://ip ,如下安装已完成。

更新docker-compose.yml 添加挂载

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

编辑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 ' I have been seen {} times.\n'.format(count)     #去除hello world

重新构建web容器

[root@VM-0-5-centos mycompose]# docker-compose up -d
Starting mycompose_web_1 ... 
Starting mycompose_web_1 ... done

此时访问web页面如下:

image-20210510233912883

docker-compose基础使用完毕啦,深入学习可参考官方文档https://docs.docker.com/compose/reference/


文章有不足的地方欢迎在评论区指出。

欢迎收藏、点赞、提问。关注顶级饮水机管理员,除了管烧热水,有时还做点别的。

posted @ 2021-05-11 09:37  justtest1  阅读(567)  评论(0编辑  收藏  举报