Issue
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 $
Solution
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.
Answered By - Nick ODell Answer Checked By - Gilberto Lyons (WPSolving Admin)