Skip to content

Instantly share code, notes, and snippets.

@pdonorio
Created July 10, 2017 13:51
Show Gist options
  • Save pdonorio/348a3b263c6c2841d8a021100bd33905 to your computer and use it in GitHub Desktop.
Save pdonorio/348a3b263c6c2841d8a021100bd33905 to your computer and use it in GitHub Desktop.
dockerized python app

Dockerized simple python app

An example app for having python code dockerized connected to one service. In this proof of concept we connect to postgresql database, using the dataset library.

getting the code up

You just have to bring the containers up with compose:

docker-compose up

debugging

If you want to check tables after launch you can access a postgresql shell like explained in testing.sh

Accessing a python shell instead would require you to:

docker-compose exec app ash

$ ipython

notes

  1. You can force the python container to do nothing by changing the command option inside the docker-compose.yml file.
  2. You can play with dataset by using the previous step and opening ipython.

clean everything after testing

docker-compose down -v
version: "3"
networks:
dbnet:
services:
app:
build: pyalpine
##################
# DIRECTLY EXECUTE THE CODE
command: myapp
# # DEBUGGING
# command: sleep 1234567890
##################
volumes:
- ./testing.py:/usr/bin/myapp
depends_on:
- db
networks:
- dbnet
db:
image: postgres:9.6
hostname: db
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydatabase
networks:
- dbnet
FROM alpine:3.6
RUN apk update && apk add \
gcc \
# there is a 'limit.h' missing in alpine when compiling psycopg2:
# https://stackoverflow.com/a/30873179
# linux-headers \
musl-dev \
# other dev packages necessary are:
postgresql-dev python3-dev
RUN pip3 install --upgrade \
pip \
ipython psycopg2 dataset
ENV SLEEP_TIME 1234567890
CMD ['sleep', '$SLEEP_TIME']
#! /usr/bin/env python3
# Access container:
# $ docker-compose exec app ash
# / # ipython
import time
import dataset
connected = False
while not connected:
try:
db = dataset.connect('postgresql://user:pass@db/mydatabase')
except BaseException:
print("Waiting for connection...")
time.sleep(3)
else:
connected = True
tablename = 'testingconnection'
table = db[tablename]
table
table.insert(dict(name='John Doe', age=46, country='China'))
# db.commit()
users = db[tablename].all()
print(users) # <-- iterator
list(users) # <-- unpacked table content
print("Completed! Now sleeping...")
time.sleep(987654321)
docker-compose exec db bash
root@db:/# psql -U user -d mydatabase
mydatabase=# \d
--------+--------------------------+----------+-------
public | testingconnection | table | user
public | testingconnection_id_seq | sequence | user
mydatabase=# SELECT * FROM testingconnection;
id | name | age | country
----+----------+-----+---------
1 | John Doe | 46 | China
(1 row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment