Skip to content

f3d3r1c01/composetest

Repository files navigation

logo

Requirements

  1. Create a directory for the project:
mkdir composetest
cd composetest
  1. 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)
  1. Create another file called requirements.txt in your project directory
flask
redis

Dockerfile

  1. 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"]

Docker Compose

  1. Create a file called docker-compose.yml in your project directory
version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:5000"
  redis:
    image: "redis:alpine"
  1. From your project directory, start up your application by running docker compose up.
docker compose up
  1. Enter http://localhost:8000/ in a browser to see the application running
  2. Stop the application, by running docker compose down from within your project directory
docker compose down

Bind Mount

  1. 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"
  1. Re-build and run the app with Compose
docker compose up
  1. 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)

About

Web App to Count Refresh

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published