Automatically detach from a container after command is executed

  docker, gradle, gradle-daemon, java

I need to execute a docker run inside a console application in Java. I build the Dockerfile with base image gradle:6.8.3-jdk15 before the application starts. This is the expected flow:

  1. On host: I create a new Process that runs my docker run command.
  2. Inside container: the entrypoint is gradle --daemon, after the daemon is started and running the container must run in detached mode (with -d -it for instance).
  3. On host: I am sure the daemon is running and I can access my container with docker exec.


How can I automatically detach a docker container after a command (inside the container) is executed?

Most of the solutions I found deal with the problem at the application level: it is feasible for me too because I can run my container in detached mode from the beginning and keep polling it from code. Working but not very performant, I feel like Docker already let you do this.

I thought that maybe an HEALTHCHECK could come in handy, if it would be able to return to the caller after the container gets labeled as healthy, but I do not think it is possible.

I have not written any code because what I am looking for is a solution/workaround based on docker only. If it cannot be done, is polling the container with docker exec my only option?

Source: Docker Questions