Docker Workshop


Full Example (python)

Cool, now lets try a full example. Lets say we have a flask webapp and rq as a background worker.

Python + flask setup

Lets put this Dockerfile into a new folder:

FROM sherzberg/python-all-dev

RUN apt-get update -qq && apt-get install -y python-pip

RUN pip install flask rq

WORKDIR /app

EXPOSE 5000
VOLUME ["/app"]

This Dockerfile will install the base dependencies for a Flask app. The base image sherzberg/python-all-dev already has the development versions of python installed.

You also need to create a file called app.py in that folder:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(host='0.0.0.0')

And lets see if it works:

$ docker build -t workshop/python-full .
...
$ docker run -i -p 5000:5000 -v $(pwd):/app -t workshop/python-full python app.py

If you don't get any errors, navigate to http://your-ip:5000

rq setup

First, we need redis:

$ docker run --name redis -d redis

Now create tasks.py for the rq worker code.

import os

from redis import Redis
from rq import Queue, Worker, Connection

redis = Redis(os.environ['REDIS_PORT_6379_TCP_ADDR'], os.environ['REDIS_PORT_6379_TCP_PORT'])
q = Queue('default', connection=redis)

def calculate(a, b):
    result = a + b
    print("{} + {} = {}".format(a, b, result))
    return result

if __name__ == '__main__':
    with Connection(redis):
        worker = Worker(map(Queue, ['default']))
        worker.work()

Run the rq worker:

$ sudo docker run -i -p 5000:5000 --link redis:redis -v $(pwd):/app -t workshop/python-full python tasks.py

Try it out:

$ sudo docker run -i --link redis:redis -v $(pwd):/app -t workshop/python-full python
>>> from tasks import q, calculate
>>> q.enqueue(calculate, 1, 3)

Look at the console output of the worker.

Exercises