I'm trying to write a simple python server that writes a message (from JSON) to a file. When I deploy my docker container, nothing happens. When I stop the container (keyboard interrupt) all console output is written at once an the container shuts down.
My python code:
import socketserver
import json
class PoCServer(socketserver.BaseRequestHandler):
def handle(self):
addr = self.client_address[0]
print("[{}] incoming connection...".format(addr))
buff = bytes()
while True:
rawdata = self.request.recv(256)
if not rawdata: break
buff = buff + rawdata
data = json.loads(buff.decode())
with open("data/" + data["name"] + ".txt", "w") as f:
f.write(data["msg"])
print("[{}] file ".format(addr) + data["name"] + ".txt written...")
server = socketserver.ThreadingTCPServer(("localhost", 10000), PoCServer)
print("[+] server listening...")
server.serve_forever()
My Dockerfile:
FROM python
WORKDIR /app
RUN mkdir /app/data
COPY server.py /app
EXPOSE 10000
CMD ["python", "server.py"]
Thank you!
Since the server listening message is visible after keyboard interrupt this means that code is working normally but the outputs are getting buffered. They are displayed once the program exits.
Running your code with -u flag should help solve this issue. According to python help page:
-u : unbuffered binary stdout and stderr;
which seems to be the problem. So in your docker file replace entry point with CMD ["python", "-u", "server.py"]
Now though, this will print the output without buffering but you should be careful in exposing the right ports and mapping them to ports on local system to actually send/receive response to server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With