Search This Blog

Tuesday, 9 October 2018

Creating a very basic python flask app in a docker container

Instructions for creating a very basic "hello flasky" Python Flask application in a docker container.  These instructions are for hand building the app on a single host and have no niceties (at the moment) for things like WSGI, NGINX, CI/CD, etc.  I put them together when I was learning the very basics of how to create a container.

Step 1 - create a host.

Create a host VM to run docker on.  As it happens, I have an old Windows8 PC that I run as a HyperV server, but any server would do.  I assigned my VM a single core and 1.5Gb of RAM which has been more than adequate for this project.

  • Install Ubuntu18.04 server - select "Docker" option during install
  • Set a static IP (or use DNS if you have some locally)


Step 2 - create a container.

I created a Flask app that simply returns "HELLO FLASKY" when queried by a web browser.  I adapted the instructions from here

SSH into your VM (I used putty on a Windows PC, but use whatever floats your boat)

Run the following bash commands from console:
 mkdir ~/helloflasky  
 cd ~/helloflasky  
 sudo nano helloFlasky.py  

Enter python code into nano:
 from flask import Flask  
 app = Flask(__name__)  
 @app.route("/")  
 def greeting():  
   return "<h1 style='color:green'>Hello Flasky!</h1>"  
 if __name__ == "__main__":  
   app.run(host='0.0.0.0')  
...save and exit nano

If python tools are installed locally (python3, python3-dev, python3-pip, flask), test the app on http://localhost:5000

Create a Dockerfile using nano:
 sudo nano Dockerfile  

Enter dockerfile into nano:
 FROM python  
 LABEL maintainer="Nik"  
 RUN apt-get update  
 RUN apt-get install -y python3 python3-dev python3-pip nginx  
 RUN pip3 install uwsgi  
 RUN pip3 install flask  
 COPY ./ ./app  
 WORKDIR ./app  
 CMD python3 helloFlasky.py  
...save and exit nano

Build container image
 sudo docker build -t hello-flasky .  

Create a container bound to TCP:5000
 sudo docker run -p 5000:5000 -d hello-flasky  

Check it using a web browser on http://host_ip:5000


NEXT STEPS :

  • Run the app using uwsgi or gunicorn.  
  • Wrapper with NGINX.
  • Create a data container (probably Mongo)
  • Have helloFlasky get data from second container
  • CI/CD




Further container thoughts

MONGO

Create a folder ~/data

Created a Mongo container
docker run -d -p 27017:27017 -v /home/nik/data:/data/db mongo

Tested with Robo 3T client (Windows)

No comments:

Post a Comment