This post is about working with containers and python web applications. But first, a little bit on containers and their use in a development ecosystem. Docker is a technology that provides abstraction and automation at an operating system level offering reusability, automation control, version control, per review, and testing capabilities.
This virtualization of bare-bones operating systems into containers enables a micro-services model where all the units of work are divided into separate units of work, facilitating scalability, relability and testing. In essence, docker containers allows developers to be accountable for programming features without having to worry about machine dependencies.
The following code blocks gives a walk-through on building a dockerized web app, the hello world of docker.
First create a new directory called “hello_docker” to contain our webserver. Then inside the hello_docker directory create a another directory creatively named “app.” Inside the app directory, create a file called hellodocker.py with the following contents.
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!\n' if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
This web server will run off a docker container so lets create a dockerfile that will be used to create our docker image. In the hello_docker directory create a file called Dockerfile with the following contents.
FROM python:3.4 RUN pip install Flask==0.10.1 WORKDIR /app COPY app /app CMD ["python", "hellodocker.py"]
Dockerfiles contain a set of instructions for docker to create an image to specifications. The first line pulls the python 3 image as a base installation and installs flask, the next lines copy the code from our directory to the image on build and runs the server.
Next to build the sample app run in the terminal,
cd hello_docker docker build -t hello_docker . docker run -d -p 5000:5000 hello_docker
Docker run with flags -d -p run the app in the background and forward port 5000 in the container to port 5000 on the host. The command should output a hash confirming a successful execution.
Our docker image is now built and running! To test the application run the following command verifying the message “Hello Docker!”:
curl $(docker-machine ip default):5000 Hello Docker!
This walkthrough barely scratched the surface of some of dockers capabilities so if you are interested in experimenting with docker I’ve listed a few links to get started with.
Here are a few more helpful cmds.
#To see your all docker containers docker ps -a #to see your running docker containers docker ps #to see your docker images docker images
If you like these blog posts or want to comment and or share something do so below and follow py-guy!