How to create a Docker image in flask? How to create a Docker image in flask? In this Docker image the crawler is implemented to run in docker.

System Environment CentOS 7.9.2009(Py3.7.9)

0x01 Create flask project

Create the project folder and python virtual environment, and activate the virtual environment

$ mkdir flask_api
$ cd flask_api
$ python3 -m venv venv
$ . venv/bin/activate
Copy the code

Create the Web API file app.py

$ touch app.py
$ vim app.py
Copy the code

0x02 Implementation logic

The management method is achieved through the Docker SDK for Python library through Python to manage the Docker container, the local Docker environment used in this article, the command is as follows

import docker

The default configuration is to connect to the local docker
client = docker.from_env()
Copy the code

The difficulty is to get the name of the container

Get the current active container, equivalent to docker ps
client.containers.list(a)Get all containers, equivalent to Docker ps-A
client.containers.list(all)

To get the name of the container, we need a for loop
for container in client.containers.list(all) :print(container.id)
	print(container.name)
Copy the code

Gets the specified container, either by its ID or name

container = client.containers.get('container')
Copy the code

The add, delete, and query functions of specified containers are described in detail in the code line below. The most important thing is to check whether the container name exists before operation.

Check whether the container exists
def exist_container(name) :
    for container in client.containers.list(all) :if(container.name==name):
            # container exists
            return True
    The container does not exist
    return False
Copy the code

0x03 code implementation

Edit app.py to achieve docker management function, where args is the parameter

from flask import Flask,request,jsonify
import docker

app = Flask(__name__)
Initialize the Docker connection
client = docker.from_env()


Check whether the container exists
def exist_container(name) :
    for container in client.containers.list(all) :if(container.name==name):
            # container exists
            return True
    The container does not exist
    return False

# add container
@app.route("/add", methods=['POST'])
def add() :
    args = request.form.get('args')
    if(exist_container(args)==False):
        client.containers.run('mosoteach',[args],name=args,detach=True)
        return jsonify(code=200,msg=args+', task created successfully ')
    else:
        return jsonify(code=204,msg=args+'task already exists')

# delete container
@app.route('/delete', methods=['POST'])
def delete() :
    args = request.form.get('args')
    if(exist_container(args)==True):
        container = client.containers.get(args)
        container.stop()
        container.remove()
        return jsonify(code=200,msg=args+', task deleted successfully ')
    return jsonify(code=204,msg=args+'Task does not exist')
    
Delete all containers
@app.route('/delete_all', methods=['POST'])
def delete_all() :
    security_code = request.form.get('security_code')
    if(security_code=='NstevKwt2nMbtdkC') :for container in client.containers.list(all):
            container.stop()
            container.remove()
        return jsonify(code=200,msg=args+', all tasks deleted successfully ')
    return jsonify(code=204,msg='Security code is incorrect')
    
Get all containers that are running
@app.route('/get_list')
def get_list() :
    containers_list = []
    for container in client.containers.list():
        containers_list.append(container.name)
    return jsonify(containers_list=containers_list)

Get a container log
@app.route('/get_logs', methods=['POST'])
def get_logs() :
    args = request.form.get('args')
    if(exist_container(args)==True):
        container = client.containers.get(args)
        return container.logs()
    else:
        return jsonify(code=204,msg=args+'Task does not exist')

if __name__ == '__main__':
    app.run()
Copy the code

0 x04 Dockerfile

The crawler needs to start from docker, write Dockerfile file and make docker image.

New Dockerfile

$ touch Dockerfile
$ vim Dockerfile
Copy the code
FROM python:slim-buster

Create project directory /app
RUN mkdir /app

Copy files from the scapy folder in the current directory to /app in the docker image
copy scapy/ /app

Set the working folder to /app
WORKDIR /app

# install dependencies
RUN ["pip"."install"."-r"."requirements.txt"."-i"."https://pypi.tuna.tsinghua.edu.cn/simple"]

# fixed parameter
ENTRYPOINT ["python"."main.py"]
# variable parameter
CMD ["0"."0"] 
Copy the code

Make the image, notice there’s one at the end.

$docker build-t [image name]Copy the code

Boot image

$docker run -d --name=[docker name] [docker name] [docker name]Copy the code

Viewing container Logs

$docker logs [container name/id]Copy the code

Once you’re sure, you can call the command creation in Python

client.containers.run('mosoteach', startup parameter,name= container name,detach=True)
Copy the code