Skip to content
Advertisement

Is there a way to get the error raised from a Python program outside Docker container and handle it?

I have a container that runs a Python program and it can run in two ways, using docker exec in the localhost terminal or by making an API Rest request (that is outside the container) which executes the same command as it would be done by using the first method. What I am trying to do is whenever my Python program inside the container raises an error the API notice it.

The error handling that is being done in the Python program is using logging.exception to print an error message and the traceback in terminal and in the API I am using the subprocess methos to make the docker exec (I know it would be better to use a Docker Compose and services but I can’t now)

The try/catch inside Docker container progam:

...
try:
    ... something ...
except IOError as e:
    self._log.exception("Error in my programn{}".format(e))

The API function:

...
try:
    CMD = "docker exec <continer_id> <params>"
    subprocess.check_output(CMD, shell=True)
    return{ 'response' : 'Done'}, 200
except Exception as e:
    return{ 'response' : 'Error {}'.format(e)}, 500

I would like the API function to catch the exception raised inside Docker container. Or if it is no possible other way to do something like this.

Advertisement

Answer

As pointed out in comments, you should not Docker commands directly on network requests (it’s error prone, not flexible nor maintainable and open to attacks)

What you can do:

  • Instead of calling your subprocess directly via Docker, wrap-it around another API which you can run in a container parallely to your first service and make an HTTP call or similar from one service to the other. You’ll be able to process errors much more efficiently (such as HTTP error codes and payload) and you won’t be subject to bash-injections attacks
  • If you keep using a sub-command call, you can have your sub-pogram return and error code depending on the error and log exception in stderr. In caller program, you can easily process the error code and stderr output to log it and perform special actions
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement