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
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:
Test:
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:
Here’s it in action:
Now, this doesn’t fit one of your requirements, because if you run:
the message will not print, because it’s missing the
-l
option.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.
I would say that’s worth it if it makes your service easier to debug.