Why does Docker -u doesnt work in my server? - linux

I add a User local in my Server with: adduser name -g 1002 and then I'd like to run my docker with this User so I make: docker run -v /home/user:/some -u "uid:gid" image there couldn't find The user: getpwuid() Not found in Passwd.

First of all, did your adduser command work for you? Following your pattern, I've created a user with useradd instead of adduser:
useradd -m -d /home/name -s /bin/bash -g 1002 name
Assuming that the group with ID 1002 already exists on your system, the following docker command should work for you as well:
docker run -v /home/name:/usr/share/nginx/html:ro -p 8080:80 -d nginx
95e38e96b6b1fdfbf18aece7ccb3c3486db5dc1b142f60515076d8d49fc815f6

Related

Creating user with uid 1000 on alpine Docker image

When I'm trying to create user with UID=1000 in Dockerfile
FROM alpine:3.16
RUN addgroup -g 1000 sail
RUN adduser -g 1000 -u 1000 sail
I'm getting error:
Step 3/3 : RUN adduser -g 1000 -u 1000 sail
---> Running in 0c4ce7e0bddf
adduser: uid '1000' in use
The command '/bin/sh -c adduser -g 1000 -u 1000 sail' returned a non-zero code: 1
But if I'm build a container without this stage and look to /etc/passwd there is no user with UID=1000. So it's exists only while building.
How to create user with UID=1000 properly in alpine?
Your syntax is incorrect, the adduser command of Alpine is the BusyBox one, so, unlike the "regular" adduser, here are its help page:
BusyBox v1.35.0 (2022-08-01 15:14:44 UTC) multi-call binary.
Usage: adduser [OPTIONS] USER [GROUP]
Create new user, or add USER to GROUP
-h DIR Home directory
-g GECOS GECOS field
-s SHELL Login shell
-G GRP Group
-S Create a system user
-D Don't assign a password
-H Don't create home directory
-u UID User id
-k SKEL Skeleton directory (/etc/skel)
You can easily go through it, running the command:
docker run -ti --rm alpine:3.16 adduser
The important part of information here are:
-g GECOS GECOS field
-G GRP Group
Where you can see that, a group, in BusyBox adduser requires your to be added with the option G, in capital letter, and that the option g in lowercase if for something else.
The option allows you to add a group, and not a GID, so you'll need the command:
RUN adduser -G sail -u 1000 sail
Furthermore, if you run that command, the shell will prompt you to fill in a password. You will need to skip this with the D option:
-D Don't assign a password
And so, your Dockerfile ends up being:
FROM alpine:3.16
RUN addgroup -g 1000 sail \
&& adduser -G sail -u 1000 sail -D
Note that it is always a good idea, in Docker, to reduce as much as possible the number of layers you are creating by running subsequent RUN instruction, for further reading on this, see here.

Using SSH inside docker with correct file permissions?

There are a few posts on how to use Docker + SSH. There are also posts on how to edit files mounted in a docker container, such that editing them won't cause the permissions to become root.
I'm trying to combine the 2 things, so I can SSH into a docker container and edit files without messing up their permissions.
For, using the correct file permissions, I use:
- /etc/passwd:/etc/passwd:ro
- /etc/group:/etc/group:ro
in my docker-compose.yml and
docker compose -f commands/dev/docker-compose.yml run \
--service-ports \
--user $(id -u) \
develop \
bash
so that when I start the docker container, my user is the same user as my local computer.
However, this breaks up my SSH setup inside the Docker container:
useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo ubuntu
echo 'ubuntu:ubuntu' | chpasswd
# passwd -d ubuntu
apt install -y --no-install-recommends openssh-server vim-tiny sudo
# See: https://stackoverflow.com/questions/22886470/start-sshd-automatically-with-docker-container
sed 's#session\s*required\s*pam_loginuid.so#session optional pam_loginuid.so#g' -i /etc/pam.d/sshd
mkdir /var/run/sshd
bash -c 'install -m755 <(printf "#!/bin/sh\nexit 0") /usr/sbin/policy-rc.d'
ex +'%s/^#\zeListenAddress/\1/g' -scwq /etc/ssh/sshd_config
ex +'%s/^#\zeHostKey .*ssh_host_.*_key/\1/g' -scwq /etc/ssh/sshd_config
RUNLEVEL=1 dpkg-reconfigure openssh-server
ssh-keygen -A -v
update-rc.d ssh defaults
# Configure sudo
ex +"%s/^%sudo.*$/%sudo ALL=(ALL:ALL) NOPASSWD:ALL/g" -scwq! /etc/sudoers
Here I'm creating a user called ubuntu with password ubuntu for SSH-ing. This lets me SSH in ubuntu#localhost using the password ubuntu.
The issue is that by mounting the /etc/passwd file into my container, I erase the ubuntu user inside the container. This means when I try to ssh in with ssh -p 9002 ubuntu#localhost, the authentication fails (9002 is what I bind port 22 in the container to on the host).
Does anyone have a solution?
Here's a first pass answer.
I can use:
useradd -rm -d /home/yourusername -s /bin/bash -g root -G sudo yourusername
instead of
useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo ubuntu
echo 'ubuntu:ubuntu' | chpasswd
then, I:
Run the ssh server in the container with:
su root
/usr/sbin/sshd -D -o ListenAddress=0.0.0.0 -o PermitRootLogin=yes
I can ssh into the container as root (using the root password "root", which I set with RUN echo 'root:root' | chpasswd in the Dockerfile).
Then, I can do su yourusername, to switch my user.
While this works, it is pretty annoying since I need to bake the user name into the Docker container.

Running non-root Docker within Ubuntu Docker container

I'm trying to run a Docker build within a Docker container based upon Ubuntu 20.04. The container needs to run as a non-root use for the build process before the Docker build occurs.
Here's some snippets of my Dockerfile to show what I'm doing:
FROM amd64/ubuntu:20.04
# Install required packages
RUN apt-get update && apt-get install -y software-properties-common
build-essential \
libssl-dev \
openssl \
libsqlite3-dev \
libtool \
wget \
autoconf \
automake \
git \
make \
pkg-config \
cmake \
doxygen \
graphviz \
docker.io
# Add user for CI purposes
RUN useradd -ms /bin/bash ciuser
RUN passwd -d ciuser
# Set docker group membership
RUN usermod -aG docker ciuser
# Run bash as the non-root user
CMD ["su", "-", "ciuser", "/bin/bash"]
When I run the container up, and try to run docker commands, I get an error:
$ docker run -ti --privileged=true -v /var/run/docker.sock:/var/run/docker.sock ci_container_staging
ciuser#0bb768506106:~$ docker ps
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/json: dial unix /var/run/docker.sock: connect: permission denied
If I remove the running as ciuser it works ok:
$ docker run -ti --privileged=true -v /var/run/docker.sock:/var/run/docker.sock /ci_container_staging
root#d71654581cec:/# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d71654581cec ci_container_staging "/bin/bash" 3 seconds ago Up 2 seconds vigilant_lalande
root#d71654581cec:/#
Where am I going wrong with setting up Docker via Dockerfile and then setting user to run as?
amd64/ubuntu:20.04 has a docker group with group id 103. Most likely the gid of the docker group for your local machine is not 103 (check getent group docker). So even though ciuser is part of the docker group, the id is different and so the user is not granted access to the docker socket.
A simple fix would be to change the gid of the docker group in the container to match your host's:
RUN groupmod -g <HOST_DOCKER_GROUP_ID> docker
There are plenty of other ways to solve issues with mapping uid/gid to docker containers but this should give you enough information to move forward.
Example/more info:
# gid on docker socket is 998
root#c349e1d13b76:/# ls -al /var/run/docker.sock
srw-rw---- 1 root 998 0 Apr 12 14:54 /var/run/docker.sock
# But gid of docker group is 103
root#c349e1d13b76:/# getent group docker
docker:x:103:ciuser
# root can `docker ps`
root#c349e1d13b76:/# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c349e1d13b76 nonroot:latest "/bin/bash" About a minute ago Up About a minute kind_satoshi
# but fails for ciuser
root#c349e1d13b76:/# runuser -l ciuser -c 'docker ps'
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.24/containers/json: dial unix /var/run/docker.sock: connect: permission denied
# change docker gid in the container to match the one on the socket/localhost
# 998 is the docker gid on my machine, yours may (will) be different.
root#c349e1d13b76:/# groupmod -g 998 docker
# run `docker ps` again as ciuser, works.
root#c349e1d13b76:/# runuser -l ciuser -c 'docker ps'
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c349e1d13b76 nonroot:latest "/bin/bash" About a minute ago Up About a minute kind_satoshi
Part of the Docker metadata when it starts a container is which user it should run as; you wouldn't generally use su or sudo.
USER ciuser
CMD ["/bin/bash"] # or the actual thing the container should do
This is important because you can override the user when the container starts up, with the docker run -u option; or you can docker run --group-add extra groups. These should typically be numeric group IDs, and they do not need to exist in the container's /etc/passwd or /etc/group files.
If the host's Docker socket is mode 0660 and owned by a docker group, you can look up the corresponding group ID and specify the container process has that group ID:
docker run \
--group-add $(getent group docker | cut -d: -f3) \
-v /var/run/docker.sock:/var/run/docker.sock \
--rm \
ci_container_staging \
docker ps
(The container does not specifically need to be --privileged, though nothing stops it from launching additional privileged containers.)

Starting a Docker container with a user different from the one on the host

I am trying to deploy an image on a Ubuntu server. The problem is I would like the container to have a user other than root. In other words, I would like to start the container under that user.
What I have tried.
I have successfully created a user in my container which has an image.
I tried to start the container with the docker start command which was unsuccessful.
I tried to create a new container with a user defined inside the dockerfile, it was also unsuccessful.
root#juju_dev_server:/home/dev# sudo docker run -it --user dev d08d53c4d78b
docker: Error response from daemon: linux spec user: unable to find user dev: no matching entries in passwd file
.
Here is my dockerfile
FROM debian
RUN groupadd -g 61000 dev
RUN useradd -g 61000 -l -m -s /bin/false -u 61000 dev
USER dev
CMD ["bash"]
FROM java:8
EXPOSE 8080
ADD /target/juju-0.0.1.jar juju-0.0.1.jar
ENTRYPOINT ["java","-jar","juju-0.0.1.jar"]
How I've done it, I use Alpine not Ubuntu but it should work fine:
Creating and running as a user called "developer"
Dockerfile
RUN /bin/bash -c "adduser -D -u 1000 developer"
RUN passwd -d developer
RUN chown -R developer /home/developer/.bash*
RUN echo "developer ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/developer
ENTRYPOINT ["/entrypoint.sh"]
CMD ["bash"]
entrypoint.sh
# stuff I need running as root here. Then below runs a bash shell as "developer"
sudo -u developer -H bash -c "$#;"
I suppose you'll want to change your ENTRYPOINT to CMD or similar, or write it into your entrypoint.sh however you like to launch your java stuff.
The Dockerfile you show creates two images. The first one is a plain debian image with a non-root user. The second one ignores the first one and is a somewhat routine Java image.
You need to do these two steps in the same image. If I was going to write your Dockerfile it might look like
FROM java:8
EXPOSE 8080
# (Prefer COPY to ADD unless you explicitly want its
# auto-unpacking semantics.)
COPY /target/juju-0.0.1.jar juju-0.0.1.jar
# Set up a non-root user context, after COPYing content
# in. (Prevents the application from overwriting
# itself as a useful security measure.)
RUN groupadd -g 61000 app
RUN useradd -g 61000 -l -m -s /bin/false -u 61000 app
USER app
# Set the main container command. (Generally prefer
# CMD to ENTRYPOINT if you’re only using one; it makes
# both getting debugging shells and later adopting the
# pattern of an initializing entrypoint script easier.)
CMD ["java","-jar","juju-0.0.1.jar"]

Set docker image username at container creation time?

I have an OpenSuse 42.3 docker image that I've configured to run a code. The image has a single user(other than root) called "myuser" that I create during the initial Image generation via the Dockerfile. I have three script files that generate a container from the image based on what operating system a user is on.
Question: Can the username "myuser" in the container be set to the username of the user that executes the container generation script?
My goal is to let a user pop into the container interactively and be able to run the code from within the container. The code is just a single binary that executes and has some IO, so I want the user's directory to be accessible from within the container so that they can navigate to a folder on their machine and run the code to generate output in their filesystem.
Below is what I have constructed so far. I tried setting the USER environment variable during the linux script's call to docker run, but that didn't change the user from "myuser" to say "bob" (the username on the host machine that started the container). The mounting of the directories seems to work fine. I'm not sure if it is even possible to achieve my goal.
Linux Container script:
username="$USER"
userID="$(id -u)"
groupID="$(id -g)"
home="${1:-$HOME}"
imageName="myImage:ImageTag"
containerName="version1Image"
docker run -it -d --name ${containerName} -u $userID:$groupID \
-e USER=${username} --workdir="/home/myuser" \
--volume="${home}:/home/myuser" ${imageName} /bin/bash \
Mac Container script:
username="$USER"
userID="$(id -u)"
groupID="$(id -g)"
home="${1:-$HOME}"
imageName="myImage:ImageTag"
containerName="version1Image"
docker run -it -d --name ${containerName} \
--workdir="/home/myuser" \
--v="${home}:/home/myuser" ${imageName} /bin/bash \
Windows Container script:
ECHO OFF
SET imageName="myImage:ImageTag"
SET containerName="version1Image"
docker run -it -d --name %containerName% --workdir="/home/myuser" -v="%USERPROFILE%:/home/myuser" %imageName% /bin/bash
echo "Container %containerName% was created."
echo "Run the ./startWindowsLociStream script to launch container"
The below code has been checked into https://github.com/bmitch3020/run-as-user.
I would handle this in an entrypoint.sh that checks the ownership of /home/myuser and updates the uid/gid of the user inside your container. It can look something like:
#!/bin/sh
set -x
# get uid/gid
USER_UID=`ls -nd /home/myuser | cut -f3 -d' '`
USER_GID=`ls -nd /home/myuser | cut -f4 -d' '`
# get the current uid/gid of myuser
CUR_UID=`getent passwd myuser | cut -f3 -d: || true`
CUR_GID=`getent group myuser | cut -f3 -d: || true`
# if they don't match, adjust
if [ ! -z "$USER_GID" -a "$USER_GID" != "$CUR_GID" ]; then
groupmod -g ${USER_GID} myuser
fi
if [ ! -z "$USER_UID" -a "$USER_UID" != "$CUR_UID" ]; then
usermod -u ${USER_UID} myuser
# fix other permissions
find / -uid ${CUR_UID} -mount -exec chown ${USER_UID}.${USER_GID} {} \;
fi
# drop access to myuser and run cmd
exec gosu myuser "$#"
And here's some lines from a relevant Dockerfile:
FROM debian:9
ARG GOSU_VERSION=1.10
# run as root, let the entrypoint drop back to myuser
USER root
# install prereq debian packages
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
apt-transport-https \
ca-certificates \
curl \
vim \
wget \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
# Install gosu
RUN dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \
&& wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \
&& chmod 755 /usr/local/bin/gosu \
&& gosu nobody true
RUN useradd -d /home/myuser -m myuser
WORKDIR /home/myuser
# entrypoint is used to update uid/gid and then run the users command
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD /bin/sh
Then to run it, you just need to mount /home/myuser as a volume and it will adjust permissions in the entrypoint. e.g.:
$ docker build -t run-as-user .
$ docker run -it --rm -v $(pwd):/home/myuser run-as-user /bin/bash
Inside that container you can run id and ls -l to see that you have access to /home/myuser files.
Usernames are not important. What is important are the uid and gid values.
User myuser inside your container will have a uid of 1000 (first non-root user id). Thus when you start your container and look at the container process from the host machine, you will see that the container is owned by whatever user having a uid of 1000 on the host machine.
You can override this by specifying the user once you run your container using:
docker run --user 1001 ...
Therefore if you want the user inside the container, to be able to access files on the host machine owned by a user having a uid of 1005 say, just run the container using --user 1005.
To better understand how users map between the container and host take a look at this wonderful article. https://medium.com/#mccode/understanding-how-uid-and-gid-work-in-docker-containers-c37a01d01cf
First of all (https://docs.docker.com/engine/reference/builder/#arg):
Warning: It is not recommended to use build-time variables for passing
secrets like github keys, user credentials etc. Build-time variable
values are visible to any user of the image with the docker history
command.
But if you still need to do this, read https://docs.docker.com/engine/reference/builder/#arg:
A Dockerfile may include one or more ARG instructions. For example,
the following is a valid Dockerfile:
FROM busybox
ARG user1
ARG buildno
...
and https://docs.docker.com/engine/reference/builder/#user:
The USER instruction sets the user name (or UID) and optionally the
user group (or GID) to use when running the image and for any RUN, CMD
and ENTRYPOINT instructions that follow it in the Dockerfile.
USER <user>[:<group>] or
USER <UID>[:<GID>]

Resources