docker compose官网示例改进

关键字: 官网示例的改进

一、docker compose的安装

提示:需要利用pip进行安装,否则卡成狗

  1. pip安装(pip2)
apt-get install python-pip

补充:如果是ubuntu 20可以直接使用pip3进行安装,此步骤可以省略

  1. 安装docker compose
pip install --upgrade pip
pip install docker-compose 
docker-compose version

补充:ubuntu 20,可以如下操作:

pip3 install docker-compose
docker-compose version

二、创建项目

  1. 创建项目目录:
$ mkdir composetest
$ cd composetest
  1. 创建使用flask和redis的python项目
    ./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)
  1. 项目下创建requirements.txt文件,并加入内容:
    ./requirements.txt
flask
redis
  1. 建立Dockerfile文件
    ./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
COPY . .
CMD ["flask", "run"]
  1. 建立Docker Compose的配置文件:
    ./docker-compose.yml
version: '3'
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

注: 5000是flesk的默认监听端口

  1. 构建和启动:
docker compose up

你可能感兴趣的:(docker compose官网示例改进)