Search code examples
javadockerkubernetesdockerfilekubernetes-pod

How to use docker ENTRYPOINT to exec java and then exec touch once java process completes


I am trying to run a pod with 2 containers. Main container executes a docker java image which runs the cron job and the other sidecar(logstash) container reads the log and ship it to the Kibana server. As main container completes once the cron job is finished but sidecar container keeps running as it doesn't gracefully shutdown. I tried https://github.com/karlkfi/kubexit and preStop container lifecycle hook but didn't work. Now, I want to try to stop sidecar container using dockerfile. Docker ENTRYPOINT exec java image jar and once java process is finished then I wanted to create / touch a file inside the main container which my other sidecar container looks for that touched file.

This is my current dockerfile

FROM mcr.microsoft.com/java/jre:11-zulu-alpine
ARG projectVersion
WORKDIR /opt/example/apps/sync
COPY /target/sync-app-${projectVersion}.jar app.jar
ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar app.jar

I wanted to add following once the java process execution completes

echo "Going to kill sync-app container..."
trap 'touch /opt/example/apps/sync/container/done' EXIT

I really wanted to know if it's possible execute the above command once ENTRYPOINT execution is finished? (may be adding these commands together in a script and pass that script to the ENTRYPOINT). But, I am not sure what is required to add those command to execute it properly.

The code I have for the logstash container which would look for the file (which is created by the first container)

- args:
  - |
    dockerd-entrypoint.sh &
    while ! test -f /opt/example/apps/sync/container/done; do
      echo "Waiting for sync-app to finish..."
      sleep 5
    done
    echo "sync-app finished, exiting"
    exit 0
  command:
  - /bin/sh
  - -c

Please let me know if any more information is required. Thanks for all the help in advance!


Solution

  • You can wait for the process to finish by the process PID. The bash interpreter has a build in command called wait where if called with a child PID as argument, it will wait until the child had finished.

    So you can create the following entrypoint.sh and add it to your java container.

    entrypoint.sh

    #!/bin/bash
    
    echo "Cleaning the file signal and running the entrypoint"
    rm -rf /opt/example/apps/sync/container/done
    
    exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar app.jar &
    child_pid=$!
    echo "Process started, waiting for the exit"
    wait $child_pid
    
    echo "Entrypoint exited, signaling the file"
    touch /opt/example/apps/sync/container/done