docker-compose 部署python项目

通过docker-compose.yml创建redis容器

docker-compose.yml

version: '3.8'
services:
    redis:
      image: redis:latest
      container_name: myredis
      command: redis-server
      ports:
        - "16379:6379"
      volumes:
        - ./data:/data

启动容器

docker-compose up -d   #后台启动

创建python flask项目

项目文件夹:demo01 的结构

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

app.py文件内容如下:

import time
import redis
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host='192.168.10.121', port=16379)

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)

requirements.txt文件内容如下:

flask
redis

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
EXPOSE 5000
COPY . .
CMD ["flask", "run"]

Dockerfile还可以这样写:

FROM python:3.7-alpine

WORKDIR /code

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD [ "python", "./app.py" ]

和上一种写法稍稍有一点区别

docker-compose.yml

version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"

启动

 docker-compose up -d

验证结果

打开链接:http://localhost:5000

docker-compose 部署python项目_第1张图片
image

你可能感兴趣的:(docker-compose 部署python项目)