Docker entrypoint to run commands with different users in interactive mode - docker

I have a custom image with docker installed (docker-in-docker). When running the image, the user needs to be $USERNAME (and not root). However the docker service required root to be started.
Getting docker to run as non-root seems to be overly complicated. So I have attempted to use su in the entry-point instead, which works, but it is not interactive.
FROM ubuntu:18.04
# ... A lot of steps here to install stuff that are not really relevant to the problem.
COPY container-helpers/entrypoint.sh .
USER root
ENV ENTRYUSER $USERNAME
ENTRYPOINT [ "./entrypoint.sh" ]
CMD "pulumi up"
And entrypoint.sh is:
#!/bin/bash
set -e
service docker start
export ENV_PATH=$PATH
su $ENTRY_USER -lp <<EOSU
set -e
export PATH=$ENV_PATH
. $NVM_DIR/nvm.sh
pulumi stack select -c dev
npx meteor-deploy stack configure default
$# # Run given argument as a command
EOSU
I run it as:
$ docker run --env-file local.env --privileged -it meteor-deploy-leaderboard
* Starting Docker: docker [ OK ]
Logging in using access token from PULUMI_ACCESS_TOKEN
error: --yes must be passed in to proceed when running in non-interactive mode
Or, if you don't want to take pulumi's word for it:
$ docker run --env-file local.env --privileged -it meteor-deploy-leaderboard bash; echo "exited"
* Starting Docker: docker [ OK ]
Logging in using access token from PULUMI_ACCESS_TOKEN
exited
Any idea how I can pass on the tty to the su command properly?

Related

Bash on alpine linux

I cannot get a bash shell into an alpine container.
I'm starting with this Alpine container:
gitlab/gitlab-runner:alpine
I'm adding a bash shell and other configs in this dockerfile:
from gitlab/gitlab-runner:alpine
ENV http_proxy=<corporate_proxy>
ENV https_proxy=<corporate_proxy>
RUN apk add vim wget curl nmap lsof bash bash-completion which
CMD ["/bin/bash"]
RUN ls -l /bin # THIS WORKS, I CAN SEE 'BASH' SHOW UP WITH 755 OWNED BY ROOT
RUN which bash # THIS ALSO WORKS
RUN /bin/bash -c "echo hi" # YES, THIS WORKS TOO
However when spawning the container to use a bash shell via:
docker run -idt <image_name> /bin/bash, the container fails to start with FATAL: Command /bin/bash not found.
Note that these other options also fail for me when spawning a container: ash, sh, /bin/ash, /bin/sh, etc
running the container with --user root also does not work.
The entrypoint is a GitLab Runner script. Change it to bash to get shell access:
$ docker run -it --entrypoint /bin/bash <image_name>
It turns out something funky was being set in the container's entrypoint. I need to remember to override the entrypoint when spawning a new container via docker run.
Adding this line in the Dockerfile fixed the problem:
ENTRYPOINT: []
1- verify if you container in fully loaded by :
docker ps
so after to enter in bash shell like:
docker exec -it <<container_name>> bash
Alpine doesn't have bash, use sh instead:
docker exec -it 64103333b32 /bin/sh

How to use root user from a container?

I’m new to the docker and linux.
I’m using windows 10 and got a github example to create a container with Centos and nginx.
I need to use the root user to change the nginx.config.
From Kitematic, I clicked on Exec to get a bash shell in the container and I tried sudo su – as blow:
sh-4.2$ sudo su –
sh: sudo: command not found
So, I tried to install sudo by below command:
sh-4.2$ yum install sudo -y
Loaded plugins: fastestmirror, ovl
ovl: Error while doing RPMdb copy-up:
[Errno 13] Permission denied: '/var/lib/rpm/Installtid'
You need to be root to perform this command.
Then I ran su - , but I don’t know the password! How can I set the password?
sh-4.2$ su -
Password:
Then, from powershell on my windows I also tried:
PS C:\Containers\nginx-container> docker exec -u 0 -it 9e8f5e7d5013 bash
but it shows that the script is running and nothing happened and I canceled it by Ctrl+C after an hour.
Some additional information:
Here is how I created the container:
PS C:\Containers\nginx-container> s2i build https://github.com/sclorg/nginx-container.git --context->dir=examples/1.12/test-app/ centos/nginx-112-centos7 nginx-sample-app
From bash shell in the container. I can get the os information as below:
sh-4.2$ cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"
CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"
I would really appreciate if you can help me to fix these issues.
Thanks!
Your approach is generally wrong. You should prepare the file outside the container an then let the Docker itself to change it.
There are several ways to achieve this.
You can mount your file during startup:
docker run -v /your/host/path/to/config.cfg:/etc/nginx/config.cfg ...
You can copy the file into the container during building the container (inside Dockerfile):
FROM base-name
COPY config.cfg /etc/nginx/
You can apply a patch to the config script (once again, a Dockerfile):
FROM base-name
ADD config.cfg.diff /etc/nginx/
RUN ["patch", "-N", "/etc/nginx/config.cfg", "--input=/etc/nginx/config.cfg.diff"]
For each method, there are lots of examples on StackOverflow.
You should read Docker's official tutorial on building and running custom images. I rarely do work in interactive shells in containers; instead, I set up a Dockerfile that builds an image that can run autonomously, and iterate on building and running it like any other piece of software. In this context su and sudo aren't very useful because the container rarely has a controlling terminal or a human operator to enter a password (and for that matter usually doesn't have a valid password for any user).
Instead, if I want to do work in a container as a non-root user, my Dockerfile needs to set up that user:
FROM ubuntu:18.04
WORKDIR /app
COPY ...
RUN useradd -r -d /app myapp
USER myapp
CMD ["/app/myapp"]
The one exception I've seen is if you have a container that, for whatever reason, needs to do initial work as root and then drop privileges to do its real work. (In particular the official Consul image does this.) That uses a dedicated lighter-weight tool like gosu or su-exec. A typical Dockerfile setup there might look like
# Dockerfile
FROM alpine:3.8
RUN addgroup myapp \
&& adduser -S -G myapp myapp
RUN apk add su-exec
WORKDIR /app
COPY . ./
ENTRYPOINT ["/app/docker-entrypoint.sh"]
CMD ["/app/myapp"]
#!/bin/sh
# docker-entrypoint.sh
# Initially launches as root
/app/do-initial-setup
# Switches to non-root user to run real app
su-exec myapp:myapp "$#"
Both docker run and docker exec take a -u argument to indicate the user to run as. If you launched a container as the wrong user, delete it and recreate it with the correct docker run -u option. (This isn't one I find myself wanting to change often, though.)
I started the container on my local and turns out you don't need sudo you can do it with su that comes by default on the debian image
docker run -dit centos bash
docker exec -it 9e82ff936d28 sh
su
also you could try executing the following which defaults you to root:
docker run -dit centos bash
docker exec -it 9e82ff936d28 bash
never less you could create the Nginx config outside the container and just have it copy using docker container copy {file_path} {container_id}:{path_inside_container}
Thanks everyone.
I think it's better to setup a virtualbox with Centos and play with nginx.
Then when I'm ready and have a correct nginx.config, I can use Dockerfile to copy my config file.
VM is so slow and I was hoping that I can work in interactive shells in containers to learn and play instead of using a VM. do you have any better idea than virtualbox?
I tried
docker run -dit nginx-sample-app bash
docker exec -u root -it 9e8f5e7d5013 bash
And it didn't do anything , it stays in the below status:
here
the same commands worked on debian image but not centos.

Entering docker container with exec losing PATH environment variable

Here is my Dockerfile:
FROM ros:kinetic-ros-core-xenial
CMD ["bash"]
If I run docker build -t ros . && docker run -it ros, and then from within the container echo $PATH, I'll get:
/opt/ros/kinetic/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
If I exec into the container (docker exec -it festive_austin bash) and run echo $PATH, I'll get:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Why are the environment variables different? How can I get a new bash process on the container with the same initial environment?
The ENTRYPOINT command is only invoked on docker run, not on docker exec.
I assume that this /ros_entrypoint.sh script is responsible for adding stuff to PATH. If so, then you could do something like this for docker exec:
docker exec -it <CONTAINER_ID> /ros_entrypoint.sh bash
docker exec only gets environment variables defined in Dockerfile with instruction ENV. With docker exec [...] bash you additionally get those defined somewhere for bash.
Add this line to your Dockerfile:
ENV PATH=/opt/ros/kinetic/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
or shorter:
ENV PATH=/opt/ros/kinetic/bin:$PATH
This is old question but since it's where google directed me I thought I'll share solution I ended up using.
In your entrypoint script add a section similar to this:
cat >> ~/.bashrc << EOF
export PATH="$PATH"
export OTHER="$OTHER"
EOF
Once you rebuild your image you can exec into your container (notice bash is invoked in interactive mode):
docker run -d --rm --name container-name your_image
docker exec -it container-name /bin/bash -i
If you echo $PATH now it should be the same as what you have set in .bashrc

Connect to docker container as user other than root

BY default when you run
docker run -it [myimage]
OR
docker attach [mycontainer]
you connect to the terminal as root user, but I would like to connect as a different user. Is this possible?
For docker run:
Simply add the option --user <user> to change to another user when you start the docker container.
docker run -it --user nobody busybox
For docker attach or docker exec:
Since the command is used to attach/execute into the existing process, therefore it uses the current user there directly.
docker run -it busybox # CTRL-P/Q to quit
docker attach <container id> # then you have root user
/ # id
uid=0(root) gid=0(root) groups=10(wheel)
docker run -it --user nobody busybox # CTRL-P/Q to quit
docker attach <container id>
/ $ id
uid=99(nobody) gid=99(nogroup)
If you really want to attach to the user you want to have, then
start with that user run --user <user> or mention it in your Dockerfile using USER
change the user using `su
You can run a shell in a running docker container using a command like:
docker exec -it --user root <container id> /bin/bash
As an updated answer from 2020. --user, -u option is Username or UID (format: <name|uid>[:<group|gid>]).
Then, it works for me like this,
docker exec -it -u root:root container /bin/bash
Reference: https://docs.docker.com/engine/reference/commandline/exec/
You can specify USER in the Dockerfile. All subsequent actions will be performed using that account. You can specify USER one line before the CMD or ENTRYPOINT if you only want to use that user when launching a container (and not when building the image). When you start a container from the resulting image, you will attach as the specified user.
The only way I am able to make it work is by:
docker run -it -e USER=$USER -v /etc/passwd:/etc/passwd -v `pwd`:/siem mono bash
su - magnus
So I have to both specify $USER environment variable as well a point the /etc/passwd file. In this way, I can compile in /siem folder and retain ownership of files there not as root.
My solution:
#!/bin/bash
user_cmds="$#"
GID=$(id -g $USER)
UID=$(id -u $USER)
RUN_SCRIPT=$(mktemp -p $(pwd))
(
cat << EOF
addgroup --gid $GID $USER
useradd --no-create-home --home /cmd --gid $GID --uid $UID $USER
cd /cmd
runuser -l $USER -c "${user_cmds}"
EOF
) > $RUN_SCRIPT
trap "rm -rf $RUN_SCRIPT" EXIT
docker run -v $(pwd):/cmd --rm my-docker-image "bash /cmd/$(basename ${RUN_SCRIPT})"
This allows the user to run arbitrary commands using the tools provides by my-docker-image. Note how the user's current working directory is volume mounted
to /cmd inside the container.
I am using this workflow to allow my dev-team to cross-compile C/C++ code for the arm64 target, whose bsp I maintain (the my-docker-image contains the cross-compiler, sysroot, make, cmake, etc). With this a user can simply do something like:
cd /path/to/target_software
cross_compile.sh "mkdir build; cd build; cmake ../; make"
Where cross_compile.sh is the script shown above. The addgroup/useradd machinery allows user-ownership of any files/directories created by the build.
While this works for us. It seems sort of hacky. I'm open to alternative implementations ...
For docker-compose. In the docker-compose.yml:
version: '3'
services:
app:
image: ...
user: ${UID:-0}
...
In .env:
UID=1000
Execute command as www-data user: docker exec -t --user www-data container bash -c "ls -la"
This solved my use case that is: "Compile webpack stuff in nodejs container on Windows running Docker Desktop with WSL2 and have the built assets under your currently logged in user."
docker run -u 1000 -v "$PWD":/build -w /build node:10.23 /bin/sh -c 'npm install && npm run build'
Based on the answer by eigenfield. Thank you!
Also this material helped me understand what is going on.

How to run docker image as a non-root user?

I'm new to docker. When I run a docker images like ubuntu image by using the command,
sudo docker run -i -t ubuntu:14.04
By default, it is entering into the container as root like this.
I searched regarding this, but I couldn't get any of how to start a docker image as a non root user as I'm completely a starter for this topic.
It would be great if someone explains with an example of how to run a docker image as a non root user.
the docker run command has the -u parameter to allow you to specify a different user. In your case, and assuming you have a user named foo in your docker image, you could run:
sudo docker run -i -t -u foo ubuntu:14.04 /bin/bash
NOTE: The -u parameter is the equivalent of the USER instruction for Dockerfile.
This is admittedly hacky, but good for those quick little containers you start just to test something quickly:
#!/bin/bash
set -eu
NAME=$1
IMG=$2
#UID=$(id -u)
USER=$(id -un)
GID=$(id -g)
GROUP=$(id -gn)
docker run -d -v /tmp:/tmp -v "/home/$USER:/home/$USER" -h "$NAME" --name "$NAME" "$IMG" /bin/bash
docker exec "$NAME" /bin/bash -c "groupadd -g $GID $GROUP && useradd -M -s /bin/bash -g $GID -u $UID $USER"
Full version of the script I use here:
https://github.com/ericcurtin/staging/blob/master/d-run
udocker is a basic variant of docker which runs in user space:
udocker is a basic user tool to execute simple docker containers in user space without requiring root privileges. Enables download and execution of docker containers by non-privileged users in Linux systems where docker is not available. It can be used to pull and execute docker containers in Linux batch systems and interactive clusters that are managed by other entities such as grid infrastructures or externally managed batch or interactive systems.
It is not advisable to allow running docker without sudo as Docker has no auditing or logging built in, while sudo does.
If you want to give docker access to non-root users Red Hat recommends setting up sudo.
Add an entry like the following to /etc/sudoers.
dwalsh ALL=(ALL) NOPASSWD: /usr/bin/docker
Now, set up an alias in ~/.bashrc for running the docker command:
alias docker="sudo /usr/bin/docker"
Now when the user executes the docker command as non-root it will be allowed and get proper logging.
docker run -ti --privileged -v /:/host fedora chroot /host
Look at the journal or /var/log/messages.
journalctl -b | grep docker.*privileged
Aug 04 09:02:56 dhcp-10-19-62-196.boston.devel.redhat.com sudo[23422]: dwalsh : TTY=pts/3 ; PWD=/home/dwalsh/docker/src/github.com/docker/docker ; USER=root ; COMMAND=/usr/bin/docker run -ti --privileged -v /:/host fedora chroot /host

Resources