简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM