python - 在 Dockerfile 中设置别名不起作用 : command not found

标签 python docker dockerfile

我的 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用于加载别名。

最佳答案

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

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 session ,所以别名会在后面的层中丢失。

为了保持一个稳定的别名,你可以像 python 在他们的 official image 中那样使用符号链接(symbolic link)。 :

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

关于python - 在 Dockerfile 中设置别名不起作用 : command not found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60383262/

相关文章:

python - 如何在 SQLAlchemy 或 SQL 的间隔交集中查找匹配月份的条目?

python - Pandas 在 bool 索引匹配周围获取 N 行

ruby-on-rails - 运行后无法访问docker Ruby on Rails镜像

node.js - 如何在 Docker 中为 Postgres 运行 sql 脚本?

django - docker-为开发和生产组合相同的配置,但仅在开发中启用主机和容器之间的代码共享

docker - 在 VS Code 中调试 .NET Core Docker 容器

windows - Docker 构建 COPY Pipfile Pipfile.lock 缓存键错误

python setup.py sdist 错误 : Operation not permitted

python - 用一个值替换一系列值

Docker Compose、Nginx、解析器不工作