MiamiBeach
MiamiBeach

Reputation: 3487

Calling Python scripts from Java. Should I use Docker?

We have a Java application in our project and what we want is to call some Python script and return results from it. What is the best way to do this?

We want to isolate Python execution to avoid affecting Java application at all. Probably, Dockerizing Python is the best solution. I don't know any other way.

Then, a question is how to call it from Java.

As far as I understand there are several ways:

  1. start some web-server inside Docker which accepts REST calls from Java App and runs Python scripts and returns results to Java via REST too.

  2. handle request and response via Docker CLI somehow.

  3. use Java Docker API to send REST request to Docker which then converted by Docker to Stdin/Stdout of Python script inside Docker.

What is the most effective and correct way to connect Java App with Python, running inside Docker?

Upvotes: 0

Views: 1204

Answers (2)

Timir
Timir

Reputation: 1425

You don’t need docker for this. There are a couple of options, you should choose depending on what your Java application is doing.

  1. If the Java application is a client - based on swing, weblaunch, or providing UI directly - you will want to turn the python functionality to be wrapped in REST/HTTP calls.

  2. If the Java application is a server/webapp - executing within Tomcat, JBoss or other application container - you should simply wrap the python scrip inside a exec call. See the Java Runtime and ProcessBuilder API for this purpose.

Upvotes: 2

Simone Zabberoni
Simone Zabberoni

Reputation: 2113

You can try OpenFaas to dockerize your python scripts with a webserver on top.

You can use the full OpenFaas stack to create single API functions mapped to single containers or you can use only the OpenFaas web component.

A simple Dockerfile could be something like:

FROM python:3.4-alpine

ADD . /workdir
WORKDIR /workdir

ADD https://github.com/openfaas/faas/releases/download/0.7.9/fwatchdog /usr/bin
RUN chmod +x /usr/bin/fwatchdog

ENV fprocess="python yourPythonScript.py"
CMD ["fwatchdog"]

Build it and run it:

$ docker build . -t dockerized-python-script
[....]
$ docker run -p 8080:8080 dockerized-python-script

And you are ready to "talk" to your script via http with plaintext parameters:

$ curl yourserver:8080 -d "param1 param2 param3"
Some output from your script

If you want to talk JSON, you'll need to modify yourPythonScript.py accordingly to manage input and output.

Upvotes: 1

Related Questions