简体   繁体   中英

How to run docker container from non-root user?

How do I make a docker container run as non-root user and have working directory (and its files) owned by a non-root user. Variants I could find in various online tutorials didn't work for some reason, files in /var/www would still be owned by root root .

Below is my Dockerfile , I use docker-compose to build and run containers. Host system is Windows 10.

FROM php:7.4-fpm

ARG user
ARG uid

RUN apt-get update && apt-get install -y \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip

RUN apt-get clean && rm -rf /var/lib/apt/lists/*

RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

WORKDIR /var/www

USER $user

Simply add

RUN chown $user:$user -R /var/www

before your WORKDIR instruction. Similarly you can change ownership for other locations as needed.

You can try this docker file

FROM php:7.4-fpm

ARG user
ARG uid

RUN apt-get update && apt-get install -y \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip

RUN addgroup -g $uid $user && \
    adduser -S -G $user -u $uid -h $user

RUN apt-get clean && rm -rf /var/lib/apt/lists/*
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

RUN chown $user:$user -R /var/www

WORKDIR /var/www

USER $user

This change is needed to make sure that the user is created in the docker image

RUN addgroup -g $uid $user && \
    adduser -S -G $user -u $uid -h $user

This is needed to change the ownership of the files to the new user

RUN chown $user:$user -R /var/www

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