Search code examples
dockerdaemonpython-daemon

How to start a daemon in background during Docker container startup?


I am trying to run a custom Python-based server (queue server) daemon in a Docker container, which communicates via sockets and operates similarly to standard Linux daemons.

The server works when started manually inside the container:

docker exec -it my_container /bin/bash
/usr/queue/qserver --port=1234 &

However, I want the daemon to run, right after calling docker run. I've tried these approaches in my Dockerfile:

  1. Using CMD with background process:
CMD /usr/queue/qserver --port=1234 & sleep infinity
  1. Using an entrypoint script:
#!/bin/bash
/usr/queue/qserver --port=1234 &
sleep infinity

But when check the qserver daemon is not running.

How can I ensure the qserver starts and remains running when the container launches?


Solution

  • Docker containers differ fundamentally from traditional Linux systems in process management. While Linux systems have a complete init system (PID 1) managing all processes, Docker containers run with a single main process that must handle all process management duties.

    Direct Background Process:

    CMD ["./daemon", "&"]

    Init System:

    CMD ["tini", "--", "./daemon"]

    Process Supervisor:

    CMD ["supervisor", "./daemon"]

    • Choose appropriate process management strategy
    • Implement proper signal handling (SIGTERM, SIGINT)
    • Enable logging and monitoring
    • Handle startup dependencies Design for proper container shutdown

    in short:

    Simple daemons → lightweight init system

    Complex daemons → process supervisor

    Critical services → full monitoring and health checks