Use Dockerfile commands inside of a shell script?

Viewed 20

Suppose that I have an entry-point to a shell script as I want to use some conditionals in a dockerfile. Is there a way to do something like this?

ENTRYPOINT ["./entry.sh", "lambda-name"]

Inside of entry.sh

#!/usr/bin/env bash

lambda_name=$1

echo "$lambda_name"

if [ "$lambda_name" = "a.handler" ]; then
    CMD [ "a.handler" ]
elif [ "$lambda_name" = "b.handler" ];then
    CMD [ "b.handler" ]
else
    echo "not found"
fi

2 Answers

first of all you don't need that complication.

why not like this?

#!/usr/bin/env bash

lambda_name=$1

echo "$lambda_name"

if [ "$lambda_name" = "a.handler" ]; then
    ./a.handler
elif [ "$lambda_name" = "b.handler" ];then
    ./b.handler
else
    echo "not found"
fi

also in your script you could use something like

exec "$@"

at the end of your script. this would run all your arguments.

The ENTRYPOINT is the main container process. It executes when you docker run the built image; it's too late to run any other Dockerfile directives at that point.

In particular, the ENTRYPOINT gets passed the image's CMD (or a Compose command: or an alternate command after the docker run image-name) as arguments, and it can do whatever it wants with that. So at this point you don't really need to "set the container's command", you can just execute whatever command it is you might have wanted to run.

#!/bin/sh

case "$1" in
  a.handler) a.handler ;;
  b.handler) b.handler ;;
  *)
    echo "$1 not found" >&2
    exit 1
    ;;
esac

With this setup, a fairly common Docker pattern is just to take whatever gets passed as arguments and to run that at the end of the entrypoint script.

#!/bin/sh

# ... do any startup-time setup required here ...

exec "$@"

That matches what you show in the question: if the first argument is a.handler then run that command, and so on.

Related