I have python application which uses Flask for accepting REST requests (on port 5000) and Tornado for accepting websocket connections (on port 8888). I want to run the application on Windows machine.
The application runs fine when I run it using python -m flask run
Now, I want to dockerize the application.
My Dockerfile is:
FROM python:3.8.3
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
RUN pip install -r requirements.txt
COPY . /app
CMD ["python","app.py"]
My requirements.txt is:
autobahn==20.6.2
cryptography==2.9.2
ecdsa==0.15
Flask==1.1.2
PyJWT==1.7.1
requests==2.24.0
tornado==6.0.4
Twisted==20.3.0
urllib3==1.25.9
websocket-client==0.57.0
websockets==8.1
app.py:
from flask import Flask, request, Response, make_response
app = Flask(__name__)
init_ws_server_thread()
@app.route("/")
def home():
return "Hello, Flask!"
def init_ws_server_thread():
print('init server thread')
try:
t = Thread(target=initialize_websocket_server, args=())
t.start()
except Exception as e:
print('init_ws_server_thread Exception:', e)
def initialize_websocket_server():
print('initialize_websocket_server')
asyncio.set_event_loop(asyncio.new_event_loop())
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
class MainHandler(tornado.websocket.WebSocketHandler):
def open(self):
global g_ws
print("New client connected", self.request.remote_ip)
g_ws = self
self.write_message("You are connected")
def on_message(self, message):
self.write_message(u"You said: " + message)
def on_close(self):
print("Client disconnected")
def check_origin(self, origin):
return True
if __name__ == '__main__':
app.run(debug = True, host = '0.0.0.0')
Docker commands:
docker build -t my-app:0.0.0.1 .
docker run -d -p 5000:5000 my-app:0.0.0.1
When the docker image is run, the REST requests are being served by Flask (http://localhost:5000) But I get the following exception for websocket:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/app/websocket_server.py", line 57, in initialize_websocket_server
app.listen(8888)
File "/usr/local/lib/python3.8/site-packages/tornado/web.py", line 2116, in listen
server.listen(port, address)
File "/usr/local/lib/python3.8/site-packages/tornado/tcpserver.py", line 151, in listen
sockets = bind_sockets(port, address=address)
File "/usr/local/lib/python3.8/site-packages/tornado/netutil.py", line 174, in bind_sockets
sock.bind(sockaddr)
OSError: [Errno 98] Address already in use
I tried to expose port 8888 using EXPOSE 8888 or by doing docker run -d -p 5000:5000 -p 8888:8888 my-app:0.0.0.1, but not working
What could be going wrong?