How to set bash aliases for docker containers in Dockerfile?

旧时模样 提交于 2019-12-03 03:27:34

问题


I am new to docker. I found that we can set environment variables using ENV instruction in the Dockerfile. But how does one set bash aliases for long commands in Dockerfile?


回答1:


Basically like you always do, by adding it to the user's .bashrc:

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



回答2:


To create an alias of an existing command, might also use ln -s:

ln -s $(which <existing_command>) /usr/bin/<my_command>




回答3:


If you want to use aliases just in Dockerfile, but not inside container then the shortest way is 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 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 on building stage and do not go inside containers, so first example is quicker, clearer and simpler for every day use.




回答4:


  1. edit this file ~/.bash_aliases vi ~/.bash_aliases
  2. source this file ~/.bash_aliases source ~/.bash_aliases
  3. done.



回答5:


You can use entrypoint, but it will not work for alias, in your Dockerfile:

ADD dev/entrypoint.sh /opt/entrypoint.sh
ENTRYPOINT ["/opt/entrypoint.sh"]

Your entrypoint.sh

#!/bin/bash
set -e

function dev_run()
{

}

export -f dev_run

exec "$@"

(Quick copy/paste, sorry)




回答6:


I just added this to my app.dockerfile

# setup aliases
ADD ./bashrc_alias.sh /usr/sbin/bashrc_alias.sh
ADD ./initbash_profile.sh /usr/sbin/initbash_profile
RUN chmod +x /usr/sbin/initbash_profile
RUN /bin/bash -C "/usr/sbin/initbash_profile"

and inside the initbash_profile.sh which just appends my custom aliases and no need to source the .bashrc file.

# add the bash aliases
cat /usr/sbin/bashrc_alias.sh >> ~/.bashrc

worked a treat!

Another option is to just use the "docker exec -it command" from outside the container and just use your own .bashrc or the .bash_profile (what ever you prefer)

eg. docker exec -it docker_app_1 bash



来源:https://stackoverflow.com/questions/36388465/how-to-set-bash-aliases-for-docker-containers-in-dockerfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!