Skip to content

Commit

Permalink
add simple python webapp example
Browse files Browse the repository at this point in the history
  • Loading branch information
tbrettschneider committed Jul 23, 2018
0 parents commit ddc3d44
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 0 deletions.
20 changes: 20 additions & 0 deletions python/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Use an official Python runtime as a parent image
FROM python:2.7-slim

# Set working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]
24 changes: 24 additions & 0 deletions python/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from flask import Flask
from redis import Redis, RedisError
import os
import socket

# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)

app = Flask(__name__)

@app.route("/")
def hello():
try:
visits = redis.incr("counter")
except RedisError:
visits = "<i>cannot connect to Redis, counter disabled</i>"

html = "<h3>Hello {name}!</h3>" \
"<b>Hostname:</b> {hostname}<br/>" \
"<b>Visits:</b> {visits}"
return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)

if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
19 changes: 19 additions & 0 deletions python/readme.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# create docker image and tag it using -t
docker build -t friendlyhello .

# new docker image should show up in local Docker image registry
docker image ls

# run app in container and map local machine's port 4000 to container's published port 80 using -p
docker run -p 4000:80 friendlyhello

# open http://localhost:4000 in local machine's browser

# quit app with CTRL+C

# explictly stop container (on Windows only)
docker container ls
docker container stop <container_name or container_id>

# run app in background, in detached mode using -d
docker run -d -p 4000:80 friendlyhello
2 changes: 2 additions & 0 deletions python/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Flask
Redis

0 comments on commit ddc3d44

Please sign in to comment.