问题描述
docker容器从外部传入的环境变量通过ssh登陆容器无法获取
预备
- 子进程继承父进程的环境变量
- set设置为临时变量子进程不继承,export设置环境变量子进程会继承
Docker传入环境变量
docker run
通过-e
参数传入环境变量docker run -e TEST=test
。
传入环境变量之后,docker容器中的1号进程(以tinit为例),以及它的子进程(如果没有特殊处理)都可以拿到TEST环境变量。
$ cat /proc/1/environ | tr \\0 \\n | grep TEST
$ TEST=test
NOTE:
- 容器中的1号进程隶属是该容器使用的进程空间(区别于宿主机的1号进程),它也是docker的运行时fork的子进程,正因此才有机会给它传递环境变量。
- /proc/$(pidof process)/environ 只是进程的初始化变量,程序重置了环境变量,通过这里查看是没有变化的。
启动SSHD服务之后
SSHD服务也是通过1号进程拉起来(SSHD是tinit的子进程),因此SSHD进程也继承了外部传入的环境变量
用户通过ssh远程登陆,SSHD会fork子进程(起个名字sshd-session)去处理登陆链接,sshd-session之后就会重置环境变量,再调用/bin/bash去执行命令。
// openssh code
do_child(struct ssh *ssh, Session *s, const char *command)
{
extern char **environ;
...
/*
* Make sure $SHELL points to the shell from the password file,
* even if shell is overridden from login.conf
*/
env = do_setup_env(ssh, s, shell);
...
/*
* Must take new environment into use so that .ssh/rc,
* /etc/ssh/sshrc and xauth are run in the proper environment.
*/
environ = env;
}
1 如何重置环境变量
https://stackoverflow.com/questions/18711531/how-to-delete-all-the-environment-variables-which-are-inherited-from-the-parent
To remove all environment variables in Linux with GNU C Library you can use clearenv().
When this function is not available (it is not in POSIX)
you can use environ = NULL instead. Do this before calling execl() or any variant.
2 extern char **environ 是什么东西
https://stackoverflow.com/questions/10649273/where-is-the-definition-of-extern-char-environ
environ is defined as a global variable in the Glibc source file posix/environ.c.
此时的shell环境已经没有docker传入的环境变量了。所以之后执行的所有命令都都无法拿到外部传入的环境变量。
解决
参考:
可以通过将外部传入的环境变量持久化到/etc/profile或者~/.bash_profile