问题描述
docker启动的centos,每次进入终端,配置在/ect/profile
的环境变量没有生效
# 运行centos 获取systemctl权限 docker run \ --privileged \ -itd \ --name centos7 \ -p 8082:8080 \ -v /sys/fs/cgroup:/sys/fs/cgroup:ro \ centos:centos7 /usr/sbin/init # 进入终端 docker exec -it centos7 /bin/bash
问题分析
通过查看几个用户环境变量文件,发现有如下调用链
~/.bash_profile ~/.bashrc /etc/bashrc /etc/profile.d/*.sh
唯独漏了配置文件 /etc/profile
# 查看 ~/.bash_profile $ more ~/.bash_profile # .bash_profile # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi # 查看 ~/.bashrc $ more ~/.bashrc # .bashrc # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc fi # 查看 /etc/bashrc $ more /etc/bashrc # /etc/bashrc for i in /etc/profile.d/*.sh; do if [ -r "$i" ]; then if [ "$PS1" ]; then . "$i" else . "$i" >/dev/null fi fi done # 查看 /etc/profile $ more /etc/profile # /etc/profile for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do if [ -r "$i" ]; then if [ "${-#*i}" != "$-" ]; then . "$i" else . "$i" >/dev/null fi fi done
问题解决
所以,我们可以将环境放到文件夹/etc/profile.d
中
无论哪种方式都会执行该文件夹中的shell脚本
添加环境变量
# 新建环境变量文件 vim /etc/profile.d/env.sh # /etc/profile.d/env.sh # jdk JAVA_HOME=/usr/local/jdk1.8.0_351 PATH=$JAVA_HOME/bin:$PATH
再次启动,就可以生效了
其实,几个配置文件也都有提示
# It's NOT a good idea to change this file unless you know what you # are doing. It's much better to create a custom.sh shell script in # /etc/profile.d/ to make custom changes to your environment, as this # will prevent the need for merging in future updates.
大致意思就说,用户环境变量放在文件夹/etc/profile.d/
中是比较好的方式