skip to Main Content

I create the image "FOO" from a Dockerfile that contains an ENTRYPOINT.
Is it possible to run this image in order that the entry point is executed (no override), and then the extra commands from the command line ?

Let’s be more clear :
Here is my dockerfile

FROM ubuntu
RUN  blah blah
ENTRYPOINT ["myscript.sh"]

Then, I create an image with docker build -t FOO .
Now, if I run docker run --rm -it FOO it works well: myscript.sh is well launched.
But, if I run docker run --rm -it FOO bash it says "Extra argument bash.".

On the other hand, if I create the image without the ENTRYPOINT in the dockerfile, then the second command (with bash) actually launches bash (but of course not myscript.sh).

Is it possible to get the best of the both ?
Execute the ENTRY POINT and then, if any, what is at the end of the docker run command line ?

Thanx!

2

Answers


  1. Not in the way you’ve said it. A container runs exactly one command, and then it exits.

    However: the ENTRYPOINT is passed the CMD or an overridden value as its command-line arguments. A common pattern is to use ENTRYPOINT to do some first-time setup, and then exec its arguments to switch to the CMD as the "real" main container process. You’ll often see this as a shell script

    #!/bin/sh
    
    # ... do whatever first-time setup ...
    ./myscript.sh || exit 1
    
    # then switch to the main container CMD
    exec "$@"
    

    In the Dockerfile, name this script as the ENTRYPOINT; it must use JSON-array syntax. You will generally provide a default CMD as well, though if you really want the container to just exit in the default case then this could be a no-op command like /bin/true.

    ENTRYPOINT ["./entrypoint.sh"]
    CMD ["/bin/echo", "hello world"]
    
    $ docker run --rm your-image
    hello world
    $ docker run --rm -it your-image bash
    0123456789abcdef:/#
    

    A very typical use for this setup is to run database migrations in the entrypoint script, or to set environment variables based on runtime-only information, or to initialize a data store that’s mounted at runtime. The CMD will by default run the main server process but this can be overridden.

    Login or Signup to reply.
  2. You can also detect whether it was started with a tty at the top of your entrypoint

    #! /bin/bash
    
    if [[ -t 0 ]]; then
      # interactive
      exec bash
    fi
    
    # rest of your script
    printf 'hello worldn'
      
    

    then, if you run

    docker run --rm FOO
    

    you get

    hello workd
    

    but if you run

    docker run --rm -it FOO
    

    you get the bash prompt.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search