跳到主要内容

SSH 登陆后命令或环境变量为什么会缺失

更新时间:2026-01-26 08:02:17

对于同一个镜像,在 Jupyter 、分布式训练中可以执行的命令,但是通过 SSH 登陆后,找不到该命令,部分环境变量也丢失。

原因​

使用 Dockerfile 构建镜像时,通过 ENV 指令定义的环境变量,无法在 ssh 登陆后获取。比如以下 Dockerfile 示例,定义了环境变量 PATH 和 LD_LIBRARY_PATH ,并且 python 和 conda 等命令在 PATH 环境变量定义的目录下。

FROM nvidia/cuda:12.6.3-cudnn-devel-ubuntu22.04

RUN wget --quiet -O ~/miniconda.sh https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-x86_64.sh && \
/bin/bash ~/miniconda.sh -b -p /opt/conda && \
rm -f ~/miniconda.sh

ENV PATH=/opt/conda/bin:$PATH
ENV LD_LIBRARY_PATH=/opt/conda/lib:$LD_LIBRARY_PATH

通过平台开发环境 jupyter 进入或本地运行 docker run 时,可以读取这些环境变量,以及 PATH 中的命令。但是通过 ssh 命令登陆时,环境变量是通过以下文件依次设置的

  • /etc/profile

  • /etc/profile.d/

  • ~/.bash_profile

  • ~/.bash_login

  • ~/.profile

  • ~/.bashrc

而 Dockerfile 的 ENV 指令定义的环境变量不会存在于这些文件中,因此 ssh 登陆后,无法找到相关命令和环境变量。

解决办法​

方法一:在 Dockerfile 文件最后将重要的环境变量写入 /etc/profile.d/your-custom-env.sh 中

ENV PATH=/opt/conda/bin:$PATH
ENV LD_LIBRARY_PATH=/opt/conda/lib:$LD_LIBRARY_PATH

RUN echo "export PATH=\${PATH}" >> /etc/profile.d/your-custom-env.sh && \
echo "export LD_LIBRARY_PATH=\${LD_LIBRARY_PATH}" >> /etc/profile.d/your-custom-env.sh

方法二:将环境变量写入 ~/.bashrc 文件中

export PATH=/opt/conda/bin:$PATH
export LD_LIBRARY_PATH=/opt/conda/lib:$LD_LIBRARY_PATH
此页面对您有帮助吗?