Tutorial on deploying Python's flask Framework on Docker

Source: Internet
Author: User
Tags hosting docker hosting virtualenv docker run
Docker

In this article, I'll try to demonstrate a viable way to develop Python applications (primarily web apps) with Docker. While I am myself focused on Python's flask micro-framework, the purpose of this article is to demonstrate how to better develop and share applications through Docker (applications developed by any language and framework). By encapsulating dependencies, Docker significantly reduces the gap between the development environment and the formal product.

Most Python developers use virtualenv in development. It provides an easy-to-use mechanism for applications to consume their own dedicated dependencies that may conflict with other applications or operating systems (especially for different versions of Pyhton, as well as different library versions, and so on). Personally, I have not had much interest in virtualenv for the following reasons:

    1. I often forget to turn it on, or forget to switch it when switching projects, and it's confusing to see ambiguous error messages.
    2. It cannot provide "pure" isolation, only Python-level isolation (System libraries and non-Python dependencies will still be problematic).
    3. I usually don't want to run it in a formal product, which means inconsistencies in the development environment and the formal product.
    4. It's a bit of a "hacking" approach: it relies on modifying scripts and setting new paths to implement them.

(Check out this article in pythonrants to learn more why you might not want to use virtualenv)

So how does Docker get better? Docker essentially provides very lightweight VMS (which can be referred to as "containers"), and we can use them to create a high standard of isolation and to significantly reduce mismatches in development and product environments. (If you're not familiar with Docker and want to learn more, you can check out my talk about Docker at the Edinburgh Tech Symposium).

When we build a small visual Web APP, I myself and Mark Coleman Use this method (document here). This (inside) outlines a basic image to install Python 2.7, along with some flask management and PostgreSQL content. I will develop a Hello World Web application based on this image. I assume you are developing on Linux and you already have git, and the instructions for installing Docker,macos should be very similar. Start by cloning and creating a basic image:

$ git clone https://github.com/mrmrcoleman/python_webapp$ Docker build-t Python_webapp.

Now, we need to add some code to the container and specify it in detail. We're going to create a new project that just points to the Docker image to do the work, rather than modifying the previous project directly.

Create a new project with the following structure:

The code is as follows:


├──dockerfile
├──example_app
│├──app
││├──__init__.py
││└──views.py
│└──__init__.py
├──example_app.wsgi


Or a sample project that clones the address: Https://github.com/amouat/example_app.git

Write in example_app/app/_init_.py:

From flask import Flask app = Flask (__name__) from app import views

Makes the other _init_.py empty. Write in views.py:

From app Import App @app. Route ('/') @app. Route ('/index ') def index ():  return "Hello, world!"

These are the smallest flask versions of our Hello World app. I've also used similar code in this tutorial, so if you've just touched flask or python, you can use Docker instead of virtualenv to continue learning based on the tutorial mentioned above.

To make it run inside the Docker container, we still need to do something about it. In our instance of the Apache server, the Example_app.wsgi file contains instructions for connecting Python code and Web servers. The file should contain the following elements:

Import sitesite.addsitedir ('/opt/example_app/') from app import app as application

Finally, we need a dockerfile to build the container and run the container. In our case, it looks like this:

From Python_webapp maintainer amouat ADD example_app.wsgi/var/www/flaskapp/flaskapp.wsgicmd service apache2 Start & & Tail-f/var/log/apache2/error.log

Add that behavior starts WSGI injected with some code. The cmd line gets any possible error messages and sends them to STDOUT when launching the container, starting the Apache Web server.

If you do the following:

$ docker build-t Example_app. $ docker run-p 5000:5000-v $ (PWD)/example_app:/opt/example_app/-i-t Example_app

You should get the feedback: Open the address localhost:5000 through the browser and you'll see that your site is running. If you are running in a VM or vagrant, remember to open port 5000.

Now that we have a Web server running, we are very close to what we use in our products (I intentionally use Apache to do this rather than the Python Default Web server). We inject code into the container by mapping from the host to the container, or we can add the code to the Dockerfile command line with ADD, but then we need to rebuild the container every time we change our team code.

However, this is still not very good; in development we really want to use a Python Web server that is largely helpful to our debugging. The pleasure is that we don't have to make any changes to Dockerfile. Start by creating a run.py file in the Example_app file, following the content:

!flask/bin/pythonfrom app Import appapp.run (debug = True, host= ' 0.0.0.0 ')

This will start the Python Web server with debugging and listen for all connections, and we can also access it from outside the container. Now restart the container with the following command:

$ docker run-p 5000:5000-v $ (PWD)/example_app:/opt/example_app/-i-t Example_app python/opt/example_app/run.py

You can see the Web page running again. This time we explicitly provide the running command ("python/opt/example_app/ryn.py"), which overrides the CMD line setting in Dockerfile. Now if you edit the source program on the host, you can immediately see the changes on the page.

Let's take some time to see what we've learned:

    1. A Web application running in a quarantine container that completely encapsulates the app's Python dependencies and system dependencies.
    2. You can use an existing editor or IDE to develop code and see changes directly, just as you would in local editing.
    3. Closer to the operating environment of the formal product than before.
    4. No virtualenv is used.

If you want to know how to build a way to publish your program in this way, you can look at the article Mark Coleman wrote about the Visual Web app that was mentioned earlier.

Unfortunately, it's not perfect. The following questions are also available:

    1. You may still encounter situations where you need to use VIRTUALENV or its equivalent solution, such as a conflict between the operating system version of the library and the version required by your program.
    2. We haven't completely solved the problem of data hosting, and we still need to do some testing.
    3. I assume that the "product" is a docker container, but this is often not the case and Docker hosting itself is just starting out.

Still, I think it's a big step towards a better future for software development, which has greatly reduced the pain of deploying software and managing dependencies.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.