Search code examples
dockerdockerfile

Running docker container with user


I have created this docker file to run a python script in docker container. I am creating a user here and I want this user to run the container from docker image.

FROM ubuntu:16.04
MAINTAINER "Vijendra Kulhade" <xxxxxx@xxxxxx.com>
RUN yum makecache fast
RUN yum -y update
RUN yum -y install gcc
RUN yum -y install zlib-devel
RUN yum -y install openssl-devel
RUN yum -y install python-setuptools python-setuptools-devel
RUN yum -y install libyaml
RUN useradd newuser -d /home/newuser
RUN chown -R newuser.newuser /usr/bin/
RUN chown -R newuser.newuser /usr/lib64/
RUN chown -R newuser.newuser /usr/lib/
ENV https_proxy=http://proxy.xxxx.com:8080
RUN easy_install pip
RUN pip -V
RUN pip install --upgrade pip
RUN pip install --upgrade --force-reinstall setuptools

I use this command to create the image docker build -t python-container . And I am using docker run --security-opt label=user:newuser -i -t python-container:latest /bin/bash to run container from image. I was expecting that this would start the container and login into it with newuser@xxxxxxxx. But It is not happening. Please let know how I can achieve that.


Solution

  • There are two possibilities to run docker containers with a user different from root.


    First possibility: Create user in Dockerfile

    In your example Dockerfile, you create user newuser with command useradd. You can write instruction

    USER newuser
    

    in the Dockerfile. All following commands will be executed as user newuser. This goes for all following RUN instructions as well as for docker run commands.


    Second possibility: option --user (tops possible USER instruction in image)

    You can use docker run option --user. It can be used to specify either an UID without a name:

    docker run --user 1000
    

    Or specify UID and GID without a name:

    docker run --user 1000:100
    

    or specify a name only without knowing which UID the user will get:

    docker run --user newuser
    

    You can combine both ways. Create a user in Dockerfile with specified (!) UID and GID and add him to all desired groups. Use matching docker run --user UID:GID, and your container user will have all attributes you gave him in the Dockerfile.


    (I do not understand your approach with --security-opt label=user:newuser, either it is wrong or it is something I know nothing about.)