Home » Categories » Multiple Categories |
Docker Explained: How To Containerize Python Web Applications |
Article Number: 260 | Rating: Unrated | Last Updated: Mon, Jan 6, 2014 at 12:47 AM
|
Docker in BriefThe docker project offers higher-level tools, working together, which are built on top of some Linux kernel features. The goal is to help developers and system administrators port applications - with all of their dependencies conjointly - and get them running across systems and machines -headache free. Docker achieves this by creating safe, LXC (i.e. Linux Containers) based environments for applications called docker containers. These containers are created using docker images, which can be built either by executing commands manually or automatically through Dockerfiles. Installing Docker on Ubuntu (Latest)With its most recent release (0.7.1. dating 5 Dec.), docker can be deployed on various Linux operating systems including Ubuntu / Debian and CentOS / RHEL. We will quickly go over the installation process for Ubuntu (Latest). Installation Instructions for UbuntuUpdate:
Make sure aufs support is available:
Add docker repository key to apt-key for package verification:
Add the docker repository to aptitude sources:
Update the repository with the new addition:
Finally, download and install docker:
Ubuntu's default firewall (UFW: Uncomplicated Firewall) denies all forwarding traffic by default, which is needed by docker. Enable forwarding with UFW: Edit UFW configuration using the nano text editor.
Scroll down and find the line beginning with DEFAULT_FORWARD_POLICY. Replace:
With:
Press CTRL+X and approve with Y to save and close. Finally, reload the UFW:
Basic Docker CommandsRunning the docker daemon and CLI Usage Upon installation, the docker daemon should be running in the background, ready to accept commands sent by the docker CLI. For certain situation where it might be necessary to manually run docker, use the following. Running the docker daemon:
docker CLI Usage:
Note: docker needs sudo privileges in order to work. Docker CommandsHere is a summary of currently available (version 0.7.1) docker commands: attachAttach to a running container buildBuild a container from a Dockerfile commitCreate a new image from a container's changes cpCopy files/folders from the containers filesystem to the host path diffInspect changes on a container's filesystem eventsGet real time events from the server exportStream the contents of a container as a tar archive historyShow the history of an image imagesList images importCreate a new filesystem image from the contents of a tarball infoDisplay system-wide information insertInsert a file in an image inspectReturn low-level information on a container killKill a running container loadLoad an image from a tar archive loginRegister or Login to the docker registry server logsFetch the logs of a container portLookup the public-facing port which is NAT-ed to PRIVATE_PORT psList containers pullPull an image or a repository from the docker registry server pushPush an image or a repository to the docker registry server restartRestart a running container rmRemove one or more containers rmiRemove one or more images runRun a command in a new container saveSave an image to a tar archive searchSearch for an image in the docker index startStart a stopped container stopStop a running container tagTag an image into a repository topLookup the running processes of a container versionShow the docker version information Building a Docker Container To Sandbox Python WSGI AppsAfter having installed docker on our server and having quickly gone over its commands, we are ready to start with the actual work to create our docker container running a Python WSGI Application. Note: The following section will enable you to have a dockerized (containerized) Python WSGI web application. However, it is definitely not the recommended method due to its complexity and impracticability. It is here to offer you a chance to learn how to work with a live container and get familiar with the commands we will need to define later in the next section to automate the process. Let's begin!Creating a Base Docker Container From UbuntuUsing docker's RUN command, we will begin with creating a new container based on the Ubuntu image. We are going to attach a terminal to it using the -t flag and will have bash as the running process. We are going to expose port 80 so that our application will be accessible from the outside. In future, you might want to load-balance multiple instances and "link" containers to each other to access them using a reverse-proxy running container, for example.
Note: After executing this command, docker might need to pull the Ubuntu image before creating a new container for you. Remember: You will be attached to the container you create. In order to detach yourself and go back to your main terminal access point, run the escape sequence: CTRL+P followed by CTRL+Q. Being attached to a docker container is like being connected to a new server instance from inside another. To attach yourself back to this container:
Important: Please do not forget that since we are in a container, all the following commands will be executed there, without affecting the host it resides. Preparing the Base Container for the InstallationIn order to deploy Python WSGI web applications inside a container - and the tools we need for the process - the relevant application repositories must be available for the downloads. Unfortunately (and intentionally to keep things simple) this is not the case with the default Ubuntu image that comes with docker. Let's append Ubuntu's universe repository to the default list of application sources list of the base image.
Update the list with the newly added source.
Before we proceed with setting up Python WSGI applications, there are some tools we should have such as nano, tar, curl, etc. -just in case. Let's download some useful tools inside our container.
Installing Common Python Tools for DeploymentFor our tutorial (as an example), we are going to create a very basic Flask application. After following this article, you can use and deploy your favorite framework instead, the same way you would deploy it on a virtual server. Remember: All the commands and instructions below still take place inside a container, which acts almost as if it is a brand new server instance of its own. Let's begin our deployment process with installing Python and pip the Python package manager:
Installing The Web Application and Its DependenciesBefore we begin with creating a sample application, we better make sure that everything - i.e. all the dependencies - are there. First and foremost, you are likely to have your Web Application Framework (WAF) as your application's dependency (i.e. Flask). As we have pip installed and ready to work, we can use it to pull all the dependencies and have them set up inside our container:
After installing pip, let's create a basic, sample Flask application inside a "my_application" folder which is to contain everything.
Note: If you are interested in deploying your application instead of this simple-sample example, see the "**Quick Tip**" mid-section below. Let's create a single, one page flask "Hello World!" application using nano.
And copy-and-paste the contents below for this small application we have just mentioned:
Press CTRL+X and approve with Y to save and close. Alternatively, you can use a "requirements.txt" to contain your application's dependencies such as Flask. To create a requirements.txt using nano text editor:
And enter the following inside, alongside all your dependencies:
Press CTRL+X and approve with Y to save and close. Our final application folder structure:
Note:Please see the following section regarding the "server.py" -Configuring your Python WSGI Application. Remember: This application folder will be created inside the container. When you are automatically building images (see the following section on Dockerfiles), you will need to make sure to have this structure on the host, alongside the Dockerfile.
How to get your application repository and its requirements inside a containerIn the above example, we created the application directory inside the container. However, you will not be doing that to deploy your application. You are rather likely to pull its source from a repository. There are several ways to copy your repository inside a container. Below explained are two of them:
Configuring your Python WSGI ApplicationTo serve this application, you will need a web server. The web server, which powers the WSGI app, needs to be installed in the same container as the application's other resources. In fact, it will be the process that docker runs. Note: In this example, we will use CherryPy's built-in production ready HTTP web server due to its simplicity. You can use Gunicorn, CherryPy or even uWSGI (and set them up behind Nginx) by following our tutorials on the subject. Download and install CherryPy with pip:
Create a "server.py" to serve the web application from "app.py":
Copy and paste the contents from below for the server to import your application and start serving it:
And that's it! Now you can have a "dockerized" Python web application securely kept in its sandbox, ready to serve thousands and thousands of client requests by simply running:
This will run the server on the foreground. If you would like to stop it, press CTRL+C. To run the server in the background, run the following:
To test that everything is running smoothly, which they should given that all the port allocations are already taken care of, you can visit http://[your IP] with your browser to see the "**Hello World!**" message. Creating the Dockerfile to Automatically Build the ImageAs we have mentioned in the previous step, it is certainly not the recommended way to create containers this way for a scalable production deployment. The right way to do can be considered as using Dockerfiles to automate the build process in a structured way. After having gone through the necessary commands for downloading and installing inside a container, we can use the same knowledge to compose a Dockerfile that docker can use to build an image from, which then can be used to run a Python WSGI application container easily. Before we start working on the Dockerfile, let's quickly go over the basics. Dockerfile BasicsDockerfiles are scripts containing commands declared successively, which are to be executed in that order by docker to automatically create a new docker image. They help greatly with deployments. These files always begin with defining an base image using the FROM command. From there on, thebuild processstarts and each following action taken forms the final image which will be committed on the host. Usage:
Dockerfile Commands OverviewAddCopy a file from the host into the container CMDSet default commands to be executed, or passed to the ENTRYPOINT ENTRYPOINTSet the default entrypoint application inside the container ENVSet environment variable (e.g. "key = value") EXPOSEExpose a port to outside FROMSet the base image to use MAINTAINERSet the author / owner data of the Dockerfile RUNRun a command and commit the ending result (container) image USERSet the user to run the containers from the image VOLUMEMount a directory from the host to the container WORKDIRSet the directory for the directives of CMD to be executed Creating the DockerfileTo create a Dockerfile at the current location using the nano text editor, execute the following command:
Note:Append all the following lines one after the other to form the Dockerfile. Defining the FundamentalsLet's begin our Dockerfile by defining the basics (fundamentals) such as the FROM image (i.e. Ubuntu) and the MAINTAINER. Append the following:
Updating the Default Application Repository for InstallationsRun the following to update the Append the following:
Installing the Basic ToolsAfter updating the default application repository sources list, we can begin our deployment process by getting the basic applications we will need. Append the following:
Note: Although you are unlikely to ever need some of the tools above, we are getting them nonetheless -just-in-case. Base Installation Instructions for Python and Basic Python ToolsFor deploying Python WSGI applications, you are extremely likely to need some of the tools which we worked with before (e.g.pip). Let's install them now before proceeding with setting up the framework (i.e. your WAF) and the your web application server (WAS) of choice. Append the following:
Application DeploymentGiven that we are building docker images to deploy Python web applications, we can very all take advantage of docker's ADD command to copy the application repository, preferably with a REQUIREMENTS file to quickly get running in one single step. Note: To package everything together in a single file and not to repeat ourselves, an application folder, structured similarly to the one below might be a good way to go.
Note: To see about creating this structure, please roll back up and refer to the section Installing The Web Application and Its Dependencies. Append the following:
Note: If you want to deploy from an online host git repository, you can use the following command to clone:
Please do not forget to replace the URL placeholder with your actual one. Bootstrapping EverythingAfter adding the instructions for copying the application, let's finish off with final configurations such as pulling the dependencies from the requirements.txt.
Final DockerfileIn the end, this is what the Dockerfile should look like:
Again save and exit the file by pressing CTRL+X and confirming with Y. Using the Dockerfile to Automatically Build ContainersAs we first went over in the "basics" section, Dockerfiles' usage consists of calling them with docker build command. Since we are instructing docker to copy an application folder (i.e. /my_application) from the current directory, we need to make sure to have it alongside this Dockerfile before starting the build process. This docker image will allow us to quickly create containers running Python WSGI applications with a single command. To start using it, build a new container image with the following:
And using that image - which we tagged my_application_img - we can run a new container running the application with:
Now you can visit the IP address of your server instance, and your application will be running via a docker container. Example:
Sample Response:
|
Attachments
There are no attachments for this article.
|
How To Create a SSL Certificate on Apache for Ubuntu 12.04
Viewed 3305 times since Mon, Dec 23, 2013
How To Install Apache Tomcat on Ubuntu 12.04
Viewed 3758 times since Mon, Dec 23, 2013
How To Set Up Python 2.7.6 and 3.3.3 on CentOS 6.4
Viewed 7437 times since Sat, Jan 4, 2014
How To Set Up vsftpd on Ubuntu 12.04
Viewed 2236 times since Thu, Dec 26, 2013
How To Set Up an NFS Mount on Ubuntu 12.04
Viewed 10300 times since Tue, Dec 24, 2013
How To Install and Use Memcache on Ubuntu 12.04
Viewed 3528 times since Tue, Dec 24, 2013
How To Launch Your Site on a New Ubuntu 12.04 Server with LAMP, SFTP, and DNS
Viewed 2561 times since Thu, Dec 26, 2013
How To Set Up Apache Virtual Hosts on Ubuntu 12.04 LTS
Viewed 3512 times since Mon, Dec 23, 2013
Common Python Tools: Using virtualenv, Installing with Pip, and Managing
Viewed 2140 times since Sat, Jan 4, 2014
Initial Server Setup with Ubuntu 12.04
Viewed 2444 times since Mon, Dec 23, 2013
|