0

If I have an application with several containers in a docker-compose.yml, which I bring up with docker-compose up. These containers inherit from standard base images with some adjustments in their respective Dockerfiles - e.g., an elasticsearch image with some additional packages installed.

How do I adjust the Dockerfile or docker-compose.yml so that I can insert a command to be run first? E.g., something like echo ${NEW_ENV_VAR} or sleep 20.

I have looked at docker documentation/stack posts and tried things with CMD and ENTRYPOINT, but with no success. Usually the attempts have resulted in the command being run, but the expected subsequent container behavior not taking place (e.g., echo ${NEW_ENV_VAR} runs, but elasticsearch doesn't start).

hainabaraka
  • 595
  • 2
  • 5
  • 13
  • You might look at the pattern in [Reuse inherited image's CMD or ENTRYPOINT](https://stackoverflow.com/questions/42280792/reuse-inherited-images-cmd-or-entrypoint). As the accepted answer there notes, you do need to know how the existing image's startup sequence works in order to modify it. – David Maze Aug 02 '22 at 12:23

1 Answers1

0

The image you are using will have its own CMD defined - when you do docker run <image> (or use it in your compose file), this is what will be executed.

(in fact, you can modify the command in the compose file if you like using command: - syntax reference here)

A solution

When you create a new Dockerfile that is built FROM <image>, you don't inherit CMD. Therefore, if you want to run the original command, you need to find out what it was.

Sadly, this is always going to entail some searching. For example, these docs give you some information about the elasticsearch image:

Entrypoint: ["/bin/tini","--","/usr/local/bin/docker-entrypoint.sh"]

Command: ["eswrapper"]

To me, this seems to suggest the full startup sequence is /bin/tini -- /usr/local/bin/docker-entrypoint.sh eswrapper.

Perhaps the best solution is to create a small shell script that executes your custom command, followed by this startup command, and invoke that script via a new CMD?

(This is a bit less verbose than trying to cram the separate commands into CMD)

Alternative solution

Another suggestion is that in the example you give, the two commands seem to be decoupled from each other - i.e. there's actually no reason to run them in the same container, it's just that one has to run before the other.

If that's really the case (maybe it isn't in practice), you may want to run the off-the-shelf image via compose, but specify that it depends_on another container that will simply run the command.

This probably isn't suitable if the command is sleep (the dependency is on the container starting, not running to completion), but if it's echo than it might be okay.

Paddy Alton
  • 1,855
  • 1
  • 7
  • 11