I can't get env var in the Docker container
Now, when I connect to it via SSH, I can't get my env there via printenv FLAG. How can I fix this? When running with -it and sh, I can my get env via printenv FLAG
You are doing two different things:
docker run -it -e FLAG='***' rastasheep/ubuntu-sshd sh
will run a container in interactive mode with a shell, and this shell session will have the environment variable you passed on the command line. Withdocker run -d -e FLAG='***' rastasheep/ubuntu-sshd
, a SSH daemon process will start with defined env vars.- when you connect in the container with SSH you will create a new shell session which does not have these environment variable set.
This can be observed when running a container, connecting to it using ssh and showing all processes and their environment variable:
docker run -d -p 2222:22 -e FLAG='test' rastasheep/ubuntu-sshdssh root@localhost -p 2222...
We are now connected into the container, we can see the SSH daemon process (PID 1) and our SSH session process (PID 7):
root@788fa982c2d0:~# ps -xf PID TTY STAT TIME COMMAND 1 ? Ss 0:00 /usr/sbin/sshd -D # <== does have the FLAG env var 7 ? Ss 0:00 sshd: root@pts/0 # <== no FLAG env var
Lets check it out, print our current process env var, and the env var of the SSH daemon process:
root@788fa982c2d0:~# printenv FLAG # Nothingroot@788fa982c2d0:~# cat /proc/1/environ # We see the FLAG env var![..]FLAG=test[...]
As pointed out by @Dmitrii, you can read Dockerize an SSH service for more details.
Try Using below Command:
docker exec <container-id> bash -c 'echo "$<variable-name>"'
As suggested by docs you might need to create your own Dockerfile with following changes
Project |--Dockerfile |--entrypoint.sh
Dockerfile
FROM rastasheep/ubuntu-sshdCOPY entrypoint.sh /usr/local/bin/entrypoint.shENTRYPOINT ["/usr/local/bin/entrypoint.sh"]CMD ["/usr/sbin/sshd", "-D"]
File: entrypoint.sh
#!/bin/bashecho "export FLAG=$FLAG" >> /etc/profileexec "$@"
Command:
docker build -t your-ubuntu-sshd . docker run --name test1 -d -e FLAG='abc' -p 2222:22 your-ubuntu-sshd