How can I set Bash aliases for docker containers in Dockerfile?
Solution 1:
Basically like you always do, by adding it to the user's .bashrc
file:
FROM foo
RUN echo 'alias hi="echo hello"' >> ~/.bashrc
As usual this will only work for interactive shells:
docker build -t test .
docker run -it --rm --entrypoint /bin/bash test hi
/bin/bash: hi: No such file or directory
docker run -it --rm test bash
$ hi
hello
For non-interactive shells you should create a small script and put it in your path, i.e.:
RUN echo -e '#!/bin/bash\necho hello' > /usr/bin/hi && \
chmod +x /usr/bin/hi
If your alias uses parameters (ie. hi Jim
-> hello Jim
), just add "$@"
:
RUN echo -e '#!/bin/bash\necho hello "$@"' > /usr/bin/hi && \
chmod +x /usr/bin/hi
Solution 2:
To create an alias of an existing command, might also use ln -s
:
ln -s $(which <existing_command>) /usr/bin/<my_command>
Solution 3:
If you want to use aliases just in Dockerfile, but not inside a container then the shortest way is the ENV
declaration:
ENV update='apt-get update -qq'
ENV install='apt-get install -qq'
RUN $update && $install apt-utils \
curl \
gnupg \
python3.6
And for use in a container the way like already described:
RUN printf '#!/bin/bash \n $(which apt-get) install -qq $@' > /usr/bin/install
RUN chmod +x /usr/bin/install
Most of the time I use aliases just in the building stage and do not go inside containers, so the first example is quicker, clearer and simpler for every day use.