Setting alias in Dockerfile not working: command not found

Viewed 3324

I have the following in my Dockerfile:

...
USER $user

# Set default python version to 3
RUN alias python=python3
RUN alias pip=pip3

WORKDIR /app

# Install local dependencies
RUN pip install --requirement requirements.txt --user

When building the image, I get the following:

 Step 13/22 : RUN alias pip=pip3
 ---> Running in dc48c9c84c88
Removing intermediate container dc48c9c84c88
 ---> 6c7757ea2724
Step 14/22 : RUN pip install --requirement requirements.txt --user
 ---> Running in b829d6875998
/bin/sh: pip: command not found

Why is pip not recognized if I set an alias right on top of it?

Ps: I do not want to use .bashrc for loading aliases.

2 Answers

The problem is that the alias only exists for that intermediate layer in the image. Try the following:

FROM ubuntu

RUN apt-get update && apt-get install python3-pip -y

RUN alias python=python3

Testing here:

❰mm92400❙~/sample❱✔≻ docker build . -t testimage
...
Successfully tagged testimage:latest

❰mm92400❙~/sample❱✔≻ docker run -it testimage bash
root@78e4f3400ef4:/# python
bash: python: command not found
root@78e4f3400ef4:/#

This is because a new bash session is started for each layer, so the alias will be lost in the following layers.

To keep a stable alias, you can use a symlink as python does in their official image:

FROM ubuntu

RUN apt-get update && apt-get install python3-pip -y 

# as a quick note, for a proper install of python, you would
# use a python base image or follow a more official install of python,
# changing this to RUN cd /usr/local/bin 
# this just replicates your issue quickly 
RUN cd "$(dirname $(which python3))" \
    && ln -s idle3 idle \
    && ln -s pydoc3 pydoc \
    && ln -s python3 python \ # this will properly alias your python
    && ln -s python3-config python-config

RUN python -m pip install -r requirements.txt

Note the use of the python3-pip package to bundle pip. When calling pip, it's best to use the python -m pip syntax, as it ensures that the pip you are calling is the one tied to your installation of python:

python -m pip install -r requirements.txt

I managed to do that by setting aliases in the /root/.bashrc file.

I have followed this example to do get an idea on how to do that

PS I am using that in a jenkins/jenkins:lts container so as I looked around and as @C.Nivs said:

The problem is that the alias only exists for that intermediate layer in the image

So in order to do that I had to find a way to add the following commands:

ENV FLAG='--kubeconfig /root/.kube/config'
RUN echo "alias helm='helm $FLAG'" >>/root/.bashrc
CMD /bin/bash -c "source /root/.bashrc" && /usr/local/bin/jenkins.sh

for the CMD part you have to check the image you are using so you wouldn't interrupt its normal behaviour.

Related