Count
Development Mode
# 1. Start a redis container
docker run -d -p 6379:6379 redis
# 2. Create a Flask app
# app.py
import os
import time
import redis
from flask import Flask
def get_ip():
"""Receive hostname by an environment variable or using localhost
"""
return os.getenv('MYREDIS_HOST', 'localhost')
app = Flask(__name__)
cache = redis.Redis(host=get_ip(), 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 from Docker! I have been seen {} times.\n'.format(count)
if __name__ == '__main__':
app.run(debug=True, port=8080) # set up debug to be True to hot reload
# 3. Run the app
python app.py
Deployment Mode
# app.py
import os
import time
import redis
from flask import Flask
def get_ip():
return os.getenv('MYREDIS_HOST', 'localhost')
app = Flask(__name__)
cache = redis.Redis(host=get_ip(), 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 from Docker! I have been seen {} times.\n'.format(count)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
# 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 ["python", "app.py"]
# Developer Side
# 1. Create the dependent package list
pip freeze > requirements.txt
# 2. Create an image docker.io/library/lchenlangley/count
# lchenlangey is the account at Docker Hub
docker build -t lchenlangley/count .
# 3. Push the image to Docker Hub, each organizaiton may have their own private image registry
docker login
docker push lchenlangley/count
# Deployment on Host
# 1. Create a bridge network
docker network create asgard
# 2. Create a redis container named as redisserver
docker run -d --name redisserver --network asgard redis
# 3. Create a container for the app
# Pass redis container name to the app with an environment variable
docker run -d --network asgard -e MYREDIS_HOST=redisserver -p 8000:5000 lchenlangley/count
# User Side
http://localhost:8000/
Reference