我想用 sagemath 构建一个服务器,它应该接收代码,执行它并发回结果。 SageMath 有一个 python 接口(interface),我认为这可以实现。我不太了解python,但我在这里找到了一个很好的起点https://ask.sagemath.org/question/23431/running-sage-from-other-languages-with-higher-performance/ .问题是我想在 docker 容器中运行它,只映射端口,但这似乎不起作用。
我更改了python文件以将其调整为较新的版本:
import socket
import sys
from io import StringIO
from sage.all import *
from sage.calculus.predefined import x
from sage.repl.preparse import preparse
SHUTDOWN = False
HOST = 'localhost'
PORT = 8888
MAX_MSG_LENGTH = 102400
# Create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print('Socket created')
# Bind socket to localhost and port
try:
s.bind((HOST, PORT))
except (socket.error , msg):
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print('Socket bind complete')
# Start listening on socket
s.listen(10)
print('Socket now listening')
# Loop listener for new connections
while not SHUTDOWN:
# Wait to accept a new client connection
conn, addr = s.accept()
print('Connected with ' + addr[0] + ':' + str(addr[1]))
# Receive message from client
msg = conn.recv(MAX_MSG_LENGTH)
if msg:
if msg == "stop":
SHUTDOWN = True
else:
parsed = preparse(msg)
if parsed.startswith('load') or parsed.startswith('attach'):
os.system('sage "' + os.path.join(os.getcwd(), parsed.split(None, 1)[1]) + '"')
else:
# Redirect stdout to my stdout to capture into a string
sys.stdout = mystdout = io.StringIO()
# Evalutate msg
try:
eval(compile(parsed,'<cmdline>','exec'))
result = mystdout.getvalue() # Get result from mystdout
except Exception as e:
result = "ERROR: " + str(type(e)) + " " + str(e)
# Restore stdout
sys.stdout = sys.__stdout__
# Send response to connected client
if result == "":
conn.sendall("Empty result, did you remember to print?")
else:
conn.sendall(result)
# Close client connection
conn.close()
# Close listener
s.close()
然后我创建了一个脚本来运行它#!/bin/bash
/usr/bin/sage -python /var/app/sage-server.py
之后我创建了 Dockerfile 来安装 SageMathFROM ubuntu:20.04
COPY src/ /var/app
RUN apt-get update \
&& DEBIAN_FRONTEND="noninteractive" TZ="Europe/London" apt-get -y install tzdata \
&& apt-get install sagemath -y
WORKDIR /var/app
RUN ["chmod", "+x", "/var/app/server.sh"]
CMD ["/var/app/server.sh"]
最后是一个 docker-compose 文件来自动化映射并将其包含到主项目中version: '3'
services:
sage-server:
build: .
volumes:
- ./src:/var/app
ports:
- "9999:8888"
所有部分都执行良好且没有任何错误(在 ubuntu 上)。我什至看到进入容器时使用了该端口,但主机系统中未使用端口 9999。你们有什么想法吗?
最佳答案
正如@David Maze 所建议的,您需要在 0.0.0.0 上公开才能在容器中访问。
HOST = '0.0.0.0'
然后你会遇到一些问题:preparse
期待 str
所以你需要解码收到的字节:msg = conn.recv(MAX_MSG_LENGTH).decode('utf-8')
StringIO
直接导入所以不需要前缀io.
:sys.stdout = mystdout = StringIO()
str
,所以你需要编码:conn.sendall(result.encode('utf-8'))
Dockerfile 可以改进(https://docs.docker.com/develop/develop-images/dockerfile_best-practices/):
FROM ubuntu:20.04
# First install dependencies so next builds will reuse docker build cache
# Use `--no-install-recommends` to minimize the installed packages
# Clean apt data
RUN apt-get update \
&& DEBIAN_FRONTEND="noninteractive" TZ="Europe/London" apt-get -y install tzdata \
&& apt-get install --no-install-recommends sagemath -y \
&& rm -rf /var/lib/apt/lists/*
# Copy changing data as late as possible to use docker build cache
COPY src/ /var/app
WORKDIR /var/app
# Explicit the listening ports
EXPOSE 8888
# No need for a wrapper script for simple command (and workaround chmod issue)
ENTRYPOINT ["/usr/bin/sage", "-python", "/var/app/sage-server.py"]
由于源代码的构建时副本在运行时被卷安装覆盖,因此权限必须在主机端正确(构建 RUN chmod +x
对运行时安装的文件没有影响)
关于python - docker中的端口映射不适用于python服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66611286/