0

I have a service (python in that example) that prints something on SIGINT/SIGTERM.

printer.py:

import signal
import sys
import threading

def runner(stop_event):
    while not stop_event.wait(1):
        print('Hi.', flush=True)

stop_event = threading.Event()

def signal_handler(*_):
    stop_event.set()
    print('Bye.', flush=True)
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

runner_thread = threading.Thread(target=runner, args=(stop_event,))
runner_thread.start()
runner_thread.join()

When running normally in the terminal and pressing CTRL+C, it works fine, i.e., the Bye. message is printed:

$ python3 printer.py 
Hi.
Hi.
^CBye.

However when running with Docker compose and CTRL+C-ing it, Bye. is never shown.

Dockerfile:

FROM python:3.7
ADD printer.py .
CMD [ "python", "printer.py" ]

docker-compose.yml:

version: '2.4'

services:
  printer:
    build:
      context: .
      dockerfile: Dockerfile

Terminal interaction:

$ docker-compose up
Creating network "compose_print_term_default" with the default driver
Creating compose_print_term_printer_1 ... done
Attaching to compose_print_term_printer_1
printer_1  | Hi.
printer_1  | Hi.
^CGracefully stopping... (press Ctrl+C again to force)
Stopping compose_print_term_printer_1 ... done

What can be done to make the Bye. visible?

Tobias Hermann
  • 9,936
  • 6
  • 61
  • 134
  • Take a look to this Question: https://stackoverflow.com/questions/41451159/how-to-execute-a-script-when-i-terminate-a-docker-container – Wie Apr 25 '19 at 12:34
  • @Wie Thanks. But printing `Bye.` is just an example. In reality the service calculates some statistics of its working and prints a summary from it. So it can not simply be done in a wrapping shell script as explained in the answer to the question you linked to. – Tobias Hermann Apr 25 '19 at 13:12

1 Answers1

1

Seems to be an issue with docker compose, already known for a few years: https://github.com/docker/compose/issues/592

Tobias Hermann
  • 9,936
  • 6
  • 61
  • 134