Containerize Python applications in 3 minutes

Many developers use their own computers to develop and then deploy the program to the intranet. If the intranet cannot access the Internet, deployment is quite troublesome, and you need to transfer the packages that the application depends on to the intranet. If it is a Python application, you also need to use pip to install the dependency packages. For some packages that need to be compiled, an error may be reported during the installation process in the windows environment, and Linux may prompt that necessary header files are missing. Installing these dependency packages will cost more The time is actually not helpful to your own technical improvement, so you should avoid as much as possible.

Can it be deployed once and run everywhere? In fact, this question is a bit outdated. Don't ask, the question is docker. If you know docker, you know that publishing your applications in the form of containers has become very popular.

This article teaches you how to containerize a Python application. After containerization, your application can be easily migrated to other servers with Docker. Even if the Docker server is not connected to the Internet, you only need to copy a Docker image to the intranet. Complete the deployment, realize a deployment, run everywhere, and improve the efficiency of deploying applications.

If there is a Python web application index.py, here is Hello world written by falsk:

from flask import Flask
app =Flask(__name__)
@ app.route("/")
def hello():return"Hello World!"if __name__ =="__main__":
 app.run(host="0.0.0.0", port=int("5000"), debug=True)

After running python index.py, visit http://127.0.0.1:5000 on the browser, and you will see'Hello World!' displayed on the browser, indicating that there is no problem with the program. If we send this file to someone, he needs to do the following 3 steps to start the web application.

  1. Install the Python interpreter
  2. Install flask library
  3. Execute python index.py

In real situations, there may be many dependencies in step 2. Here we put all the dependent libraries in the requirements.txt file:

Flask==1.1.2

Then create a text file named Dockerfile in the root directory of the application (here is the directory where index.py is located), and paste the following code.

FROM python:alpine3.8
COPY ./app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 5000
CMD python ./index.py

Please note that the FROM instruction points to python:alpine3.7. This is telling the Docker container what base image to use and implicitly choosing the Python version to use, in this case 3.8. Docker Hub has base images for almost all Python versions. This example uses Python installed on Alpine Linux (a minimalist Linux distribution), which helps to make the Docker image smaller. Unless there is a good reason to use a basic image like Debian Jessie, it is better to choose Alpine.

Also note the RUN instruction, which calls pip to install dependencies from the requirements.txt file.

The remaining instructions in the Dockerfile are very simple. The CMD instruction tells the container to execute what to start the application. In this case, it tells Python to run index.py. The COPY command simply moves the application to the container image, WORKDIR sets the working directory, and EXPOSE binds the port used by Flask.

To build the image, in the Dockerfile directory, run the docker build command in the terminal.

docker build --tag somenzz-app ./

Wait for it to download the basic image and build it, you will get an image of somenzz-app:

$ docker images | grep somenzz
somenzz-app                                         latest              b7e2359056bb        3 hours ago         89.1MB
somenzz/my-kali                                     latest              975cbe3a4619        2 weeks ago         1.83GB

You can see that this image is only 89.1MB in size. Next, just like other images are already available:

$ docker run --name python-app -p 5000:5000 somenzz-app
 * Serving Flask app "index"(lazy loading)* Environment: production
 WARNING: This is a development server. Do not use it in a production deployment.
 Use a production WSGI server instead.* Debug mode: on
 * Running on http://0.0.0.0:5000/(Press CTRL+C to quit)* Restarting with stat
 * Debugger is active!* Debugger PIN:201-219-912172.17.0.1--[14/Oct/202022:32:05]"GET / HTTP/1.1"200-

At this point, the container has been successfully started, and the local 5000 port will be mapped to the 5000 port of the container. Therefore, accessing 127.0.0.0:5000 is equivalent to accessing the 5000 port of the container.

If you want to run the container in the background, you can add the -d parameter:

$ docker run -d  --name python-app -p 5000:5000 somenzz-app
259 d09fbbf77a6fd680cd7527600d055cb76fe3d6792063846103b47360210f9
$ docker container list | grep somenzz-app
259 d09fbbf77        somenzz-app                                         "/bin/sh -c 'python …"20 minutes ago      Up 20 minutes       0.0.0.0:5000->5000/tcp                           python-app

Combine the step 7 in the previous article Hand touch, take you to docker: Publish the image, you can publish the container to the network for others to use.

If you are not familiar with Dockerfile, there is an easier way to make and publish a docker image, which is to download an image, start it, log in to the container to modify it, install the dependencies, save it as a new image, and finally publish it. Of course, the efficiency is more. If you have time, it’s better to learn Dockerfile. The official tutorial is as follows:

https://docs.docker.com/engine/reference/builder/

Naturally, this article is just a simple HelloWorld web application. More complex scenarios will require more attention to detail, but the containerization process of most Python applications is the same, I hope this article will help you.

Python number seven, do a more satisfactory number seven, learn a Python trick every week, welcome to pay attention.

Recommended Posts

Containerize Python applications in 3 minutes
Functions in python
03. Operators in Python entry
Join function in Python
12. Network Programming in Python3
print statement in python
Concurrent requests in Python
Install python in Ubuntu
Context management in Python
Arithmetic operators in python
Write gui in python
MongoDB usage in Python
Str string in Python
Computational Geometry in Python
Concurrent requests in Python (part 2)
Subscripts of tuples in Python
Talking about inheritance in Python
What is introspection in python
What is object-oriented in python
Generators and iterators in Python
Talking about strings in Python
Use of Pandas in Python development
Use nohup command instructions in python
What is list comprehension in python
Is there function overloading in python
Getting started with Numpy in Python
Detailed sorting algorithm (implemented in Python)
How to wrap in python code
What does rc1 mean in python
Use of numpy in Python development
What does def in python do
How to omit parentheses in Python
Detailed usage of dictionary in Python
Usage of os package in python
Learn about garbage collection in Python
How to write classes in python
How to filter numbers in python
​What are the numbers in Python?
There are several keywords in Python
Everything in Python is an object
How to view errors in python
What does np do in python
How to write return in python
Talking about the modules in Python
How to understand variables in Python
How to clear variables in python
The usage of tuples in python
How to use SQLite in Python
Description of in parameterization in python mysql