- Create a directory for the project:
mkdir composetest
cd composetest
- Create a file called app.py in your project directory
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)
- Create another file called requirements.txt in your project directory
flask
redis
- In your project directory, create a file named 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"]
- Create a file called docker-compose.yml in your project directory
version: "3.9"
services:
web:
build: .
ports:
- "8000:5000"
redis:
image: "redis:alpine"
- From your project directory, start up your application by running docker compose up.
docker compose up
- Enter http://localhost:8000/ in a browser to see the application running
- Stop the application, by running docker compose down from within your project directory
docker compose down
- Edit docker-compose.yml in your project directory to add a bind mount for the web service
version: "3.9"
services:
web:
build: .
ports:
- "8000:5000"
volumes:
- .:/code
environment:
FLASK_DEBUG: True
redis:
image: "redis:alpine"
- Re-build and run the app with Compose
docker compose up
- 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)