bashdockercontainersshdocker-entrypoint

Εxecute commands with args and override entrypoint on docker run


I am trying to override the entrypoint in a docker image with a script execution that accepts arguments, and it fails as follows

▶ docker run --entrypoint "/bin/sh -c 'my-script.sh arg1 arg2'" my-image:latest
docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/bin/sh -c 'myscript.sh arg1 arg2'": stat /bin/sh -c 'my-script.sh arg1 arg2': no such file or directory: unknown.

However when I exec to the container, the above command succeeds:

▶  docker run --entrypoint sh -it my-image:latest
~ $ /bin/sh -c 'my-script.sh arg1 arg2'
Success

Am I missing sth in the syntax?


Solution

  • Remember that arguments after the container image name are simply passed to the ENTRYPOINT script. So you can write:

    docker run --entrypoint my-script.sh my-image:latest arg1 arg2
    

    For example, if I have my-script.sh (mode 0755) containing:

    #!/bin/sh
    
    for arg in "$@"; do
        echo "Arg: $arg"
    done
    

    And a Dockerfile like this:

    FROM docker.io/alpine:latest
    
    COPY my-script.sh /usr/local/bin/
    ENTRYPOINT ["date"]
    

    Then I can run:

    docker run --rm --entrypoint my-script.sh my-image arg1 arg2
    

    And get as output:

    Arg: arg1
    Arg: arg2
    

    If you want to run an arbitrary sequence of shell commands, you can of course do this:

    docker run --rm --entrypoint sh my-image \
      -c 'ls -al && my-script.sh arg1 arg2'