Your Location is: Home > Php

Change user/group for PHP-FPM (Docker)

From: Taiwan View: 3074 Serge 

Question

I ran docker php-fpm container with the following config

  php-fpm:
    tty: true
    image: bitnami/php-fpm:latest
    volumes:
      - ./www:/www

php-fpm is running as daemon:daemon. How to properly change user/group for the container? For example, run it as www:www...

Best answer

Build this into your Docker image. In your Dockerfile:

FROM bitnami/php-fpm:latest # (Debian-based)

# Create the non-root runtime user.  It does not need a
# specific uid, shell, home directory, or other settings.
RUN adduser --system --no-create-home --group www

# Copy the files in as root, so they don't accidentally get
# overwritten at runtime
# (The base image sets WORKDIR /app)
COPY www ./

# Then set the runtime user
USER www

# The base image provides a useful CMD; leave it as is

(Some of the details around the base image's WORKDIR and CMD come from looking up the bitnami/php-fpm image on Docker Hub, and in turn following the link to the image's Dockerfile.)

Then your docker-compose.yml file just needs to specify the details to use this Dockerfile. You do not need volumes:; the code is already built into the image.

version: '3.8'
services:
  php-fpm:
    build: .
    # ports: ['9000:9000']
    # no volumes:

In practice it usually doesn't matter much what specific user ID a container process is running as, just so long as it isn't (or, depending on your needs, is) the special root user (with user ID 0). There shouldn't be a difference between the container process running as daemon vs. www. Conversely, looking at the bitnami/php-fpm Dockerfile, it isn't obvious to me that anything would cause the container to not run as root.