在Dockerfile中设置别名无效:未找到命令

2024-09-30 20:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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

在构建图像时,我得到以下信息:

 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

如果我在pip上面设置了一个别名,为什么它不能被识别

Ps:我不想使用.bashrc加载别名


Tags: installpiprunindockerfiletxtsteppip3
1条回答
网友
1楼 · 发布于 2024-09-30 20:34:52

问题是,别名只存在于图像中的中间层。请尝试以下操作:

FROM ubuntu

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

RUN alias python=python3

在这里测试:

❰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:/#

这是因为每个层都会启动一个新的bash会话,因此别名将在以下层中丢失

要保持一个稳定的别名,可以像python在其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

注意使用python3-pip包捆绑pip。调用pip时,最好使用python -m pip语法,因为它可以确保所调用的pip是与python安装相关的:

python -m pip install -r requirements.txt

相关问题 更多 >