Simple construction and operation of Python Flask service of Docker


Run a simple flash project in the form of Docker container


I Write py code

1. Write a simple flash project in python. Here I use PyChram to write the project

Create an app Py files are as follows: (it is worth noting that Flask needs a wave of packet inversion. Move the mouse to Flask and press Alt + Enter to complete the packet inversion)

#!/user/bin/env python3
# -*- coding: utf-8 -*-
# @Email  :

from flask import Flask

app = Flask(__name__)

def index():
    return '<h1>Hello World!</h1>'

def getUserName():
    return '<h1>Tommy </h1>'

if __name__ == '__main__':'', port=7777, debug=True)

2. After the code is written, first run a wave of code in PyCharm to test the effect. Right click in the blank and select Run 'app' code to run normally:

3. Open the browser and enter http://localhost:7777 Enter and Hello World appears! It means that you have no problem with Flask to create a docker image

II Build the flash service into a docker image

1. Create two files Dockerflie and requirements Txt (Note: Dockerfile has no extension name)

1.1) Dockerfile is the basis for docker to build an image file. Docker will build an image according to the command of Dockerfile. The code of Dockerfile is as follows:

FROM python:3.8


ADD . /app

RUN pip install -r requirements.txt -i


CMD ["python", ""]

General meaning:

Using python3.8 edition

set up docker Working directory of the container /app

Copy all contents in the current directory to the container /app Under the directory( Dockerfile requirements.txt)

Pour in Required package (here is the package) Flask After the package is the image source. If the package you want to introduce needs to learn to surf the Internet, it will be difficult to do. Therefore, a domestic image source is set to ensure that it is safe

Exposed port number of container: 7777

implement python code

1.2)requirement.txt is the dependency Library of python


2. Start building the image

2.1) cd directory to your python directory, i.e. Dockerfile file directory

Right click Ubuntu to open the terminal

2.2) execute build image code

It should be noted that I run docker directly below. Under normal circumstances, sudo is required to run. Why can I do this?

By default, only root Or yes sudo Users with permissions can execute Docker Command.
Want to blame root User execution Docker Command, you need to add your users to Docker User group in Docker CE The package is created during installation. To do this, enter:

$ sudo usermod -aG docker $USER

$USER Is an environment variable that represents the current user name.
Log out and log in again to refresh the user group member information.
docker build -f Dockerfile -t Flask:tommy .

#According to the Dockerfile file, create a docker image with the image name flag and the tag name tommy

Execution error prompt 1:

tommy@tommy-Vostro-3900:~/PycharmProjects/pythonProject$ docker build -f Dockerfile -t Flask:tommy
invalid argument "Flask:tommy" for "-t, --tag" flag: invalid reference format: repository name must be lowercase
See 'docker build --help'.

The name must be in lowercase letters, and flask is modified to flask:

docker build -f Dockerfile -t flask:tommy .

Execution error 2:

tommy@tommy-Vostro-3900:~/PycharmProjects/pythonProject$ docker build -f Dockerfile -t flask:tommy
"docker build" requires exactly 1 argument.
See 'docker build --help'.

Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Please button your eyes, there is a point at the end, and add a space ~!!!

docker build -f Dockerfile -t flask:tommy . < --- here's a point

2.3) view the image by executing the code after the construction is completed

docker images

You can see that the image named flash and marked tommy has been created successfully.

3. Run the mirror

docker run -p 7777:7777 flask:tommy

Error message:

tommy@tommy-Vostro-3900:~/PycharmProjects/pythonProject$ docker run -p 7777:7777 7790f1ba6894
docker: Error response from daemon: driver failed programming external connectivity on endpoint romantic_nash (25d453a1f5e5bb4c19cebe2c0922349cc6e4f4cff2abe3a9a142c5fd9849560f): Error starting userland proxy: listen tcp4 bind: address already in use.
ERRO[0000] error waiting for container: context canceled 

It shows that you are testing on your own machine. You just ran the test code in PyCharm in the first step. Your TM has not been closed until now, resulting in the occupation of port 7777

Click on the Red Square and close it.

Execute another wave of operation code:

docker run -p 7777:7777 flask:tommy

OK, run up. At this time, the browser inputs a wave: http://localhost:7777/user

It can be accessed normally, and the deployment of the flash image to this docker is complete.

4. When finishing work, Ctrl + C finds that the service will stop, that is, the service will disappear as soon as the command window is closed. What should I do?

# -d run in the background, so that the service can run in the background all the time
docker run -d -p 7777:7777 flask:tommy

# View running images
docker ps

# Stop a running image (this ID is the ID queried by ps)
docker kill CONTAINER ID 

# View all current mirrors
docker images

# Delete a mirror
docker rmi  [name:tag] [image id]
docker rmi flask:tommy
docker rmi 7790f1ba6894

4.1) stop mirroring

tommy@tommy-Vostro-3900:~/PycharmProjects/pythonProject$ docker ps
CONTAINER ID   IMAGE             COMMAND                  CREATED              STATUS              PORTS                    NAMES
f01bd3055ea9   flask:tommy       "python"          About a minute ago   Up About a minute>7777/tcp   confident_borg
b2dd9fb7f01c   sonatype/nexus3   "sh -c ${SONATYPE_DI..."   2 days ago           Up 5 hours>8081/tcp   nexus

Flash: the id of Tommy image is f01bd3055ea9

docker kill f01bd3055ea9

4.2) delete image

tommy@tommy-Vostro-3900:~/PycharmProjects/pythonProject$ docker images
REPOSITORY            TAG       IMAGE ID       CREATED          SIZE
flask                 tommy     7790f1ba6894   32 minutes ago   907MB
tommy/tt              t1        b7e4080a6925   6 days ago       907MB
mysql                 5.7       a70d36bc331a   6 weeks ago      449MB
python                3.8       b0358f6298cd   7 weeks ago      882MB
sonatype/nexus3       latest    8716903d1912   7 weeks ago      629MB
portainer/portainer   latest    62771b0b9b09   7 months ago     79.1MB
java                  latest    d23bdf5b1b1b   4 years ago      643MB
training/webapp       latest    6fae60ef3446   5 years ago      349MB

View the existing image. Flash: Tommy image id: 7790f1ba6894

# Delete by id
docker rmi 7790f1ba6894

# Mark deletion by name
docker rmi flask:tommy

Execution error prompt:

tommy@tommy-Vostro-3900:~/PycharmProjects/pythonProject$ docker rmi flask:tommy
Error response from daemon: conflict: unable to remove repository reference "flask:tommy" (must force) - container fed9c379b0b6 is using its referenced image 7790f1ba6894

The prompt cannot be deleted. If you want to delete it, you must force it to be deleted

# Delete by id
docker rmi -f 7790f1ba6894

# Mark deletion by name
docker rmi -f flask:tommy

After deletion, run docker images to see if it has been deleted.


Finally: if the article is helpful to you, please click the < reward > button below to learn about it ~

Tags: Python Linux Operation & Maintenance Docker Ubuntu

Posted by y2yang on Mon, 11 Apr 2022 15:05:37 +0300