Docker compose

单独的开源项目,需要安装

国内的镜像

curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.5/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

查看    cd /usr/local/bin/

授权    chmod +x /usr/local/bin/docker-compose

查看版本    docker-compose version

docker compose 高效批量编排多个容器 (写在docker-compose.yaml文件中)

重要概念:

服务service: 容器应用 (web ,redis ,mysql等)

项目project:一组有关联的容器 (比如运行一个博客:web+mysql+wp)

案例:搭建计时器应用

mkdir composetest
 
cd composetest    编写四个文件

app.py    requirements.txt    docker-compose.yml    Dockerfile

 1. vim  requirements.txt

flask
redis

2. 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)

3 vim  docker-compose.yml

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

4.  vim  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"]
启动服务 docker-compose up  -d    后台运行

验证: docker ps -a 查看是否运行两个容器

成功计数

[root@node1 ~]# curl localhost:5000

Hello World! I have been seen 1 times.

[root@node1 ~]# curl localhost:5000

Hello World! I have been seen 2 times.

 案例:搭建博客

mkdir my_wordpress
cd my_wordpress/


vim  docker-compose.yml
version: "3.3"
    
services:
  db:
    image: mysql:5.7
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: somewordpress
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress
    
  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    volumes:
      - wordpress_data:/var/www/html
    ports:
      - "8000:80"
    restart: always
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
      WORDPRESS_DB_NAME: wordpress
volumes:
  db_data: {}
  wordpress_data: {}

[root@node1 my_wordpress]# docker-compose up -d

查看容器是否运行成功    docker ps -a

网页验证   IP:8000

上一篇:【玩转 WordPress】基于 Serverless 搭建个人博客图文教程,学生党首选!


下一篇:原生Kubernetes容器云平台应用部署