skip to Main Content

I would like to run a shell script every time when a shell is started using docker exec or kubectl exec. I am looking for something similar to .bashrc/.bash_profile/.profile, but since this particular container is based on alpine linux, bash is not available.

How could I execute a shell script in the container?

I would like to achieve something like this:

> docker exec -it my_alpine_based_container sh
Hi! Welcome to the container. This message comes from a shell script.
/usr/src/app $

And similarly with kubectl:

> kubectl exec -it my_pod_running_the_container -- sh
Hi! Welcome to the container. This message comes from a shell script.
/usr/src/app $

2

Answers


  1. Chosen as BEST ANSWER

    When using the busybox ash variant, which is used by Alpine Linux as well, it is possible to set the ENV variable in the Dockerfile to point to a script that is executed on startup - even for not login shells.

    For details see the busybox ash source code: ash.c, line 14189.

    Dockerfile:

    FROM alpine:latest
    ENV ENV=/root/.ashrc
    RUN echo "echo 'Hello from .ashrc!'" >> /root/.ashrc
    CMD ["/bin/sh"]
    

    Test:

     $ docker exec -it c8688d3e9ce8 sh
    Hello from .ashrc!
    / #
    

  2. Alpine linux uses ash for /bin/sh. Ash does support .profile, but only when running as a login shell.

    Here is an example Dockerfile which prints a welcome message:

    FROM alpine:latest
    RUN echo 'echo foo' >> /root/.profile
    CMD ["/bin/sh", "-l"]
    

    Here’s it in action:

    $ docker run -it <image name>
    foo
    ccdae0bb9d59:/#
    

    Now, this doesn’t fit one of your requirements, because if you run:

    docker exec -it <container name> sh
    

    the message will not print, because it’s missing the -l option.

    but since this particular container is based on alpine linux, bash is not available.

    Bash is a pretty lightweight addition to the image. If you add Bash to your image like this, then it only adds 4.6 MB to the image.

    RUN apk add bash
    

    I would say that’s worth it if it makes your service easier to debug.

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