I moved a small Flask service (a few hundred lines) into Docker this month. It runs on one Linux server, and I wanted the deploy to be clean and repeatable. Docker fits this case well, but some things were not clear from the tutorials.
Versions: Docker 1.3 came out in October 2014 and added docker exec. Docker 1.4 was released on 11 December
2014. Everything below works on 1.3 and later. On Ubuntu 14.04, install from Docker’s own apt repository. The
docker.io package in the Ubuntu archive is older.
I would not use Docker for one script run by cron; a virtualenv and a crontab line are simpler. I also would
not use it on a Raspberry Pi yet. Docker on ARM is not officially supported, and most images on Docker Hub
are x86-64 only. And for many containers across many hosts, plain docker run does not scale. Tools for that
exist (fig for one host, and several cluster tools), but they are young.
The service
A minimal Flask app, app.py:
import os
from flask import Flask
app = Flask(__name__)
DATA_DIR = os.environ.get('DATA_DIR', '/data')
@app.route('/health')
def health():
return 'ok\n'
@app.route('/count')
def count():
path = os.path.join(DATA_DIR, 'count.txt')
n = 0
if os.path.exists(path):
with open(path) as f:
n = int(f.read() or 0)
n += 1
with open(path, 'w') as f:
f.write(str(n))
return '%d\n' % n
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
And requirements.txt:
Flask==0.10.1
gunicorn==19.1.1
The Dockerfile
FROM python:3.4
WORKDIR /app
# Copy requirements first, so this layer is cached when only code changes.
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
COPY . /app
ENV DATA_DIR /data
VOLUME /data
EXPOSE 5000
CMD ["gunicorn", "-b", "0.0.0.0:5000", "-w", "2", "app:app"]
My first version copied all the code before pip install. Docker caches each step, so every code change
reinstalled all packages. Copy requirements.txt first.
Use the JSON array form for CMD. With the string form Docker starts /bin/sh -c, your process does not
get the stop signal, and docker stop waits 10 seconds and then kills it.
The Flask development server is single threaded and not made for production, so the image runs gunicorn.
Also add a .dockerignore with .git, *.pyc and local virtualenvs, or they end up in the build context.
Build and tag with a version, not only latest:
docker build -t counter:0.1 .
Running it
docker run -d --name counter \
--restart=always \
-p 127.0.0.1:5000:5000 \
-v /srv/counter/data:/data \
counter:0.1
--restart=always (since Docker 1.2) starts the container again after a crash and after a host reboot, as
long as the Docker daemon starts at boot. No init script needed for the container.
-p 127.0.0.1:5000:5000 binds only to localhost, and nginx in front does TLS and the public port. Be careful
here. With -p 5000:5000 the port is open on all interfaces, and because Docker changes iptables rules by
itself, your firewall rules may not block it. I did not expect that.
-v /srv/counter/data:/data keeps the data on the host. Anything written inside the container outside a
volume is gone when you remove the container.
Day-to-day commands
docker logs -f --tail=100 counter # stdout and stderr of the service
docker exec -it counter bash # shell inside the running container (Docker 1.3+)
docker ps # what is running
docker inspect counter | less # full config, volumes, IP
Before 1.3 people used nsenter or ran an SSH server inside the container. With docker exec you need
neither, so do not install SSH in your images.
Updating
docker build -t counter:0.2 .
docker stop counter && docker rm counter
docker run -d --name counter --restart=always \
-p 127.0.0.1:5000:5000 -v /srv/counter/data:/data counter:0.2
This gives a few seconds of downtime, which is fine for a small internal service. Keep the old image so you
can go back with one command. I put the docker run line in a small shell script in the repository, so the
run options are in Git and not only in my shell history.
Things that bit me or will bite later
Old images and stopped containers stay on disk until you remove them:
docker ps -a | grep 'Exited' | awk '{print $1}' | xargs -r docker rm
docker rmi $(docker images -q -f dangling=true)
Docker 1.3 and 1.4 write container logs to a JSON file with no rotation. I use logrotate on
/var/lib/docker/containers/*/*.log with copytruncate.
The container uses UTC by default. For a server that is what I want anyway.
The process runs as root by default. For a simple service, add a user in the Dockerfile and use USER app,
and make sure the volume directory on the host is writable by that user ID. I have not done this for the
counter yet.
Security fixes (like the bash fix this autumn) come in new base images. Run docker pull python:3.4 and
rebuild from time to time.
Short checklist
- Requirements copied first, exec form
CMD, gunicorn. - Versioned image tags.
- Data in a host volume.
- Port bound to 127.0.0.1, nginx in front.
--restart=always.- The run command in a script in Git.
- Cleanup and log rotation.