Docker 运行 Windows 11 上的图像给出错误 /bin/sh: 1: [: python3: 意外的运算符

Docker run image on Windows 11 gives error /bin/sh: 1: [: python3: unexpected operator

我在我的 Windows 11 笔记本电脑上安装了以下软件:

在 Docker 桌面中我启用了 Kubernetes。

现在我在 Python 中创建了一个脚本,我称之为 Books,它是一个 API,它提供 json 和书籍:

main.py:

import flask
from flask import jsonify, request

app = flask.Flask(__name__) # Creates the Flask application object
app.config["DEBUG"] = True

# Create some test data for our catalog in the form of a list of dictionaries.
books = [
    {'id': 0,
     'title': 'A Fire Upon the Deep',
     'author': 'Vernor Vinge',
     'first_sentence': 'The coldsleep itself was dreamless.',
     'year_published': '1992'},
    {'id': 1,
     'title': 'The Ones Who Walk Away From Omelas',
     'author': 'Ursula K. Le Guin',
     'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
     'published': '1973'},
    {'id': 2,
     'title': 'Dhalgren',
     'author': 'Samuel R. Delany',
     'first_sentence': 'to wound the autumnal city.',
     'published': '1975'}
]


@app.route('/', methods=['GET'])
def home():
    return '''<h1>Distant Reading Archive</h1>
<p>A prototype API for distant reading of science fiction novels.</p>'''


@app.route('/api/v1/resources/books/all', methods=['GET'])
def api_all():
    return jsonify(books)


@app.route('/api/v1/resources/books', methods=['GET'])
def api_id():
    # Check if an ID was provided as part of the URL.
    # If ID is provided, assign it to a variable.
    # If no ID is provided, display an error in the browser.
    if 'id' in request.args:
        id = int(request.args['id'])
    else:
        return "Error: No id field provided. Please specify an id."

    # Create an empty list for our results
    results = []

    # Loop through the data and match results that fit the requested ID.
    # IDs are unique, but other fields might return many results
    for book in books:
        if book['id'] == id:
            results.append(book)

    # Use the jsonify function from Flask to convert our list of
    # Python dictionaries to the JSON format.
    return jsonify(results)

app.run()

当我 运行 来自 Pycharm 的脚本时一切正常。我可以在 http://127.0.0.1:5000/api/v1/resources/books/all

查看 API

现在我尝试构建一个 docker 图像。我创建了一个名为 dockerfile:

的文件

docker文件:

# Specifying Python
FROM ubuntu:latest
RUN apt-get update -y
RUN apt-get install python3 -y
RUN apt-get install python3-pip -y
RUN pip install --upgrade pip

# Add Python script
ADD main.py main.py

# Install dependencies
# RUN pip install -r requirements.txt
RUN pip install flask

# Run script
CMD [ "python3" "./main.py" ]

我使用以下命令构建 docker 图像,并且构建正常:

docker build --tag books .

当我现在打开 Powershell 到 运行 docker 图像时,它给我一个错误:

C:\Users\s>docker run books
/bin/sh: 1: [: python3: unexpected operator

您的 Dockerfile 中的命令之间需要一个逗号。即:

CMD ["python3", "./main.py"]

查看CMD格式here