tornado icon indicating copy to clipboard operation
tornado copied to clipboard

Docker + tornado.ioloop.IOLoop.current().start()

Open gogasca opened this issue 2 years ago • 2 comments

I'm trying to start a Docker container using a systemctl service:

Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/docker run docker run --name=agent \
      --detach \
      --net host \
      my-project/agent:local \
    python3 /agent.py

If I remove --detach my container service gets stuck in initializing.

In agent:

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

    def make_app():
        return tornado.web.Application([ (r"/", MainHandler), ])  # URL Mapping

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)    # Port Number
    tornado.ioloop.IOLoop.current().start()
    print("Ready")

I tried adding print line and I see that tornado.ioloop blocks execution and systemctl service is stuck in initialize, is there a way to execute tornado.ioloop.IOLoop.current().start() in background?

# Create a new thread and start the Tornado server in that thread
server_thread = threading.Thread(target=start_server)
server_thread.start()
print("Hello")

Seems to work fine, is ok/recommended, I will run `tornado.ioloop.IOLoop.current().stop() at exit.

Thanks

gogasca avatar Jul 07 '23 21:07 gogasca

Why do you think it's "stuck in initializing"? IOLoop.start is supposed to run forever; that's the main event loop of the application. Your print("Ready") is in the wrong place; it should be just before the call to start. I'm not a systemd expert but I think in general you should use Type=exec (or simple) instead of Type=oneshot for Tornado services.

bdarnell avatar Jul 08 '23 00:07 bdarnell

One of the reasons why I tried "oneshot" is because Python logic may execute or not. I will update the results of my tests and will answer "Why do you think it's "stuck in initializing"?"

gogasca avatar Jul 10 '23 22:07 gogasca