ソースを参照

initial commit

ksieren 3 年 前
コミット
3e8d3c4db4

+ 92 - 0
Dockerfile

@@ -0,0 +1,92 @@
+ARG ARCH=
+FROM ${ARCH}alpine:3.17
+
+LABEL Maintainer="kerstin Sieren <kerstin@sieren.biz>" \
+      Description="Lightweight container with Nginx & PHP-FPM based on Alpine Linux."
+
+# Install packages
+RUN apk --no-cache add \
+        php81 \
+        php81-fpm \
+        php81-opcache \
+        php81-pecl-apcu \
+        php81-mysqli \
+        php81-pgsql \
+        php81-json \
+        php81-openssl \
+        php81-curl \
+        php81-zlib \
+        php81-soap \
+        php81-xml \
+        php81-fileinfo \
+        php81-phar \
+        php81-intl \
+        php81-dom \
+        php81-xmlreader \
+        php81-ctype \
+        php81-session \
+        php81-iconv \
+        php81-tokenizer \
+        php81-zip \
+        php81-simplexml \
+        php81-mbstring \
+        php81-gd \
+        nginx \
+        runit \
+        curl \
+# Bring in gettext so we can get `envsubst`, then throw
+# the rest away. To do this, we need to install `gettext`
+# then move `envsubst` out of the way so `gettext` can
+# be deleted completely, then move `envsubst` back.
+    && apk add --no-cache --virtual .gettext gettext \
+    && mv /usr/bin/envsubst /tmp/ \
+    && runDeps="$( \
+        scanelf --needed --nobanner /tmp/envsubst \
+            | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \
+            | sort -u \
+            | xargs -r apk info --installed \
+            | sort -u \
+    )" \
+    && apk add --no-cache $runDeps \
+    && apk del .gettext \
+    && mv /tmp/envsubst /usr/local/bin/ \
+# Remove alpine cache
+    && rm -rf /var/cache/apk/* \
+# Remove default server definition
+    && rm /etc/nginx/http.d/default.conf \
+# Make sure files/folders needed by the processes are accessable when they run under the nobody user
+    && chown -R nobody.nobody /run \
+    && chown -R nobody.nobody /var/lib/nginx \
+    && chown -R nobody.nobody /var/log/nginx
+
+# Add configuration files
+COPY --chown=nobody rootfs/ /
+
+# Switch to use a non-root user from here on
+USER nobody
+
+# Add application
+WORKDIR /var/www/html
+
+# Expose the port nginx is reachable on
+EXPOSE 8080
+
+# Let runit start nginx & php-fpm
+CMD [ "/bin/docker-entrypoint.sh" ]
+
+# Configure a healthcheck to validate that everything is up&running
+HEALTHCHECK --timeout=10s CMD curl --silent --fail http://127.0.0.1:8080/fpm-ping
+
+ENV client_max_body_size=2M \
+    clear_env=no \
+    allow_url_fopen=On \
+    allow_url_include=Off \
+    display_errors=Off \
+    file_uploads=On \
+    max_execution_time=0 \
+    max_input_time=-1 \
+    max_input_vars=1000 \
+    memory_limit=128M \
+    post_max_size=8M \
+    upload_max_filesize=2M \
+    zlib.output_compression=On

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2021 Gedoens
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 145 - 0
README.md

@@ -0,0 +1,145 @@
+# Docker PHP-FPM 8.1 & Nginx 1.22 on Alpine Linux
+
+
+Example PHP-FPM 8.1 & Nginx 1.22 setup for Docker, build on [Alpine Linux](https://www.alpinelinux.org/).
+The image is only +/- 25MB large.
+
+Repository: https://git2.meramo.org/Infrastructure/alpine-phpfpm-nginx-baseimage.git
+
+* Built on the lightweight and secure Alpine Linux distribution
+* Very small Docker image size (+/-25MB)
+* Uses PHP 8.1 for better performance, lower cpu usage & memory footprint
+* Multi-arch support: 386, amd64, arm/v6, arm/v7, arm64, ppc64le, s390x
+* Optimized for 100 concurrent users
+* Optimized to only use resources when there's traffic (by using PHP-FPM's ondemand PM)
+* Use of runit instead of supervisord to reduce memory footprint
+* The servers Nginx, PHP-FPM run under a non-privileged user (nobody) to make it more secure
+* The logs of all the services are redirected to the output of the Docker container (visible with `docker logs -f <container name>`)
+* Follows the KISS principle (Keep It Simple, Stupid) to make it easy to understand and adjust the image to your needs
+
+
+## Usage
+
+Start the Docker container:
+
+    docker run -p 80:8080 kerstinsieren/alpine-phpfpm-nginx-baseimage
+
+See the PHP info on http://localhost, or the static html page on http://localhost/test.html
+
+Or mount your own code to be served by PHP-FPM & Nginx
+
+    docker run -p 80:8080 -v ~/my-codebase:/var/www/html kerstinsieren/alpine-phpfpm-nginx-baseimage
+
+
+## Adding additional daemons
+You can add additional daemons (e.g. your own app) to the image by creating runit entries. You only have to write a small shell script which runs your daemon, and runit will keep it up and running for you, restarting it when it crashes, etc.
+
+The shell script must be called `run`, must be executable, and is to be placed in the directory `/etc/service/<NAME>`.
+
+Here's an example showing you how a memcached server runit entry can be made.
+
+    #!/bin/sh
+    ### In memcached.sh (make sure this file is chmod +x):
+    # `chpst -u memcache` runs the given command as the user `memcache`.
+    # If you omit that part, the command will be run as root.
+    exec 2>&1 chpst -u memcache /usr/bin/memcached
+
+    ### In Dockerfile:
+    RUN mkdir /etc/service/memcached
+    ADD memcached.sh /etc/service/memcached/run
+
+Note that the shell script must run the daemon **without letting it daemonize/fork it**. Usually, daemons provide a command line flag or a config file option for that.
+
+
+## Running scripts during container startup
+You can set your own scripts during startup, just add your scripts in `/docker-entrypoint-init.d/`. The scripts are run in lexicographic order.
+
+All scripts must exit correctly, e.g. with exit code 0. If any script exits with a non-zero exit code, the booting will fail.
+
+The following example shows how you can add a startup script. This script simply logs the time of boot to the file /tmp/boottime.txt.
+
+    #!/bin/sh
+    ### In logtime.sh (make sure this file is chmod +x):
+    date > /tmp/boottime.txt
+
+    ### In Dockerfile:
+    ADD logtime.sh /docker-entrypoint-init.d/logtime.sh
+
+
+## Configuration
+In [rootfs/etc/](rootfs/etc/) you'll find the default configuration files for Nginx, PHP and PHP-FPM.
+If you want to extend or customize that you can do so by mounting a configuration file in the correct folder;
+
+Nginx configuration:
+
+    docker run -v "`pwd`/nginx-server.conf:/etc/nginx/conf.d/server.conf" kerstinsieren/alpine-phpfpm-nginx-baseimage
+
+PHP configuration:
+
+    docker run -v "`pwd`/php-setting.ini:/etc/php8/conf.d/settings.ini" kerstinsieren/alpine-phpfpm-nginx-baseimage
+
+PHP-FPM configuration:
+
+    docker run -v "`pwd`/php-fpm-settings.conf:/etc/php8/php-fpm.d/server.conf" kerstinsieren/alpine-phpfpm-nginx-baseimage
+
+_Note; Because `-v` requires an absolute path I've added `pwd` in the example to return the absolute path to the current directory_
+
+## Environment variables
+
+You can define the next environment variables to change values from NGINX and PHP
+
+| Server | Variable Name           | Default | description                                                                                                                                                                                                                                            |
+|--------|-------------------------|---------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| NGINX  | client_max_body_size    | 2m      | Sets the maximum allowed size of the client request body, specified in the “Content-Length” request header field.                                                                                                                                      |
+| PHP8   | clear_env               | no      | Clear environment in FPM workers. Prevents arbitrary environment variables from reaching FPM worker processes by clearing the environment in workers before env vars specified in this pool configuration are added.                                   |
+| PHP8   | allow_url_fopen         | On      | Enable the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.              |
+| PHP8   | allow_url_include       | Off     | Allow the use of URL-aware fopen wrappers with the following functions: include(), include_once(), require(), require_once().                                                                                                                          |
+| PHP8   | display_errors          | Off     | Eetermine whether errors should be printed to the screen as part of the output or if they should be hidden from the user.                                                                                                                              |
+| PHP8   | file_uploads            | On      | Whether or not to allow HTTP file uploads.                                                                                                                                                                                                             |
+| PHP8   | max_execution_time      | 0       | Maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30.                                                               |
+| PHP8   | max_input_time          | -1      | Maximum time in seconds a script is allowed to parse input data, like POST, GET and file uploads.                                                                                                                                                      |
+| PHP8   | max_input_vars          | 1000    | Maximum number of input variables allowed per request and can be used to deter denial of service attacks involving hash collisions on the input variable names.                                                                                        |
+| PHP8   | memory_limit            | 128M    | Maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1.                         |
+| PHP8   | post_max_size           | 8M      | Max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. Generally speaking, memory_limit should be larger than post_max_size.                                 |
+| PHP8   | upload_max_filesize     | 2M      | Maximum size of an uploaded file.                                                                                                                                                                                                                      |
+| PHP8   | zlib.output_compression | On      | Whether to transparently compress pages. If this option is set to "On" in php.ini or the Apache configuration, pages are compressed if the browser sends an "Accept-Encoding: gzip" or "deflate" header.                                               |
+
+_Note; Because `-v` requires an absolute path I've added `pwd` in the example to return the absolute path to the current directory_
+
+
+## Adding composer
+
+If you need [Composer](https://getcomposer.org/) in your project, here's an easy way to add it.
+
+```dockerfile
+FROM kerstinsieren/alpine-phpfpm-nginx-baseimage:latest
+USER root
+# Install composer from the official image
+RUN apk add --no-cache composer
+USER nobody
+# Run composer install to install the dependencies
+RUN composer install --optimize-autoloader --no-interaction --no-progress
+```
+
+### Building with composer
+
+If you are building an image with source code in it and dependencies managed by composer then the definition can be improved.
+The dependencies should be retrieved by the composer but the composer itself (`/usr/bin/composer`) is not necessary to be included in the image.
+
+```Dockerfile
+FROM composer AS composer
+
+# copying the source directory and install the dependencies with composer
+COPY <your_directory>/ /app
+
+# run composer install to install the dependencies
+RUN composer install \
+  --optimize-autoloader \
+  --no-interaction \
+  --no-progress
+
+# continue stage build with the desired image and copy the source including the
+# dependencies downloaded by composer
+FROM kerstinsieren/alpine-phpfpm-nginx-baseimage
+COPY --chown=nginx --from=composer /app /var/www/html
+```

+ 11 - 0
docker-compose.test.yml

@@ -0,0 +1,11 @@
+version: '3.5'
+services:
+  app:
+    build: .
+  sut:
+    image: alpine:3.17
+    depends_on:
+      - app
+    command: /tmp/run_tests.sh
+    volumes:
+      - "./run_tests.sh:/tmp/run_tests.sh:ro"

+ 57 - 0
rootfs/bin/docker-entrypoint.sh

@@ -0,0 +1,57 @@
+#!/bin/sh
+
+shutdown() {
+  echo "shutting down container"
+
+  # first shutdown any service started by runit
+  for _srv in $(ls -1 /etc/service); do
+    sv force-stop $_srv
+  done
+
+  # shutdown runsvdir command
+  kill -HUP $RUNSVDIR
+  wait $RUNSVDIR
+
+  # give processes time to stop
+  sleep 0.5
+
+  # kill any other processes still running in the container
+  for _pid  in $(ps -eo pid | grep -v PID  | tr -d ' ' | grep -v '^1$' | head -n -6); do
+    timeout -t 5 /bin/sh -c "kill $_pid && wait $_pid || kill -9 $_pid"
+  done
+  exit
+}
+
+echo "Starting startup scripts in /docker-entrypoint-init.d ..."
+
+for script in $(find /docker-entrypoint-init.d/ -executable -type f); do
+
+    echo >&2 "*** Running: $script"
+    $script
+    retval=$?
+    if [ $retval != 0 ];
+    then
+        echo >&2 "*** Failed with return value: $?"
+        exit $retval
+    fi
+
+done
+echo "Finished startup scripts in /docker-entrypoint-init.d"
+
+echo "Starting runit..."
+exec runsvdir -P /etc/service &
+
+RUNSVDIR=$!
+echo "Started runsvdir, PID is $RUNSVDIR"
+echo "wait for processes to start...."
+
+sleep 5
+for _srv in $(ls -1 /etc/service); do
+    sv status $_srv
+done
+
+# catch shutdown signals
+trap shutdown SIGTERM SIGHUP SIGQUIT SIGINT
+wait $RUNSVDIR
+
+shutdown

+ 3 - 0
rootfs/docker-entrypoint-init.d/01-uname.sh

@@ -0,0 +1,3 @@
+#!/bin/sh
+# Test file to check init scripts
+uname -a

+ 103 - 0
rootfs/etc/nginx/nginx.conf

@@ -0,0 +1,103 @@
+worker_processes 1;
+error_log stderr warn;
+pid /run/nginx.pid;
+
+events {
+    worker_connections 1024;
+}
+
+http {
+    include mime.types;
+    default_type application/octet-stream;
+
+    # Define custom log format to include reponse times
+    log_format main_timed '$remote_addr - $remote_user [$time_local] "$request" '
+                          '$status $body_bytes_sent "$http_referer" '
+                          '"$http_user_agent" "$http_x_forwarded_for" '
+                          '$request_time $upstream_response_time $pipe $upstream_cache_status';
+
+    access_log /dev/stdout main_timed;
+    error_log /dev/stderr notice;
+
+    keepalive_timeout 65;
+
+    # Write temporary files to /tmp so they can be created as a non-privileged user
+    client_body_temp_path /tmp/client_temp;
+    proxy_temp_path /tmp/proxy_temp_path;
+    fastcgi_temp_path /tmp/fastcgi_temp;
+    uwsgi_temp_path /tmp/uwsgi_temp;
+    scgi_temp_path /tmp/scgi_temp;
+
+    # Default server definition
+    server {
+        listen 8080 default_server;
+        server_name _;
+
+        sendfile off;
+
+        # Increase proxy buffers for large requests
+        proxy_buffer_size 128k;
+        proxy_buffers 4 256k;
+        proxy_busy_buffers_size 256k;
+
+        # Upload limit
+        client_max_body_size ${client_max_body_size};
+        client_body_buffer_size 128k;
+
+        root /var/www/html/public;
+        index index.php index.html;
+
+        location / {
+            # First attempt to serve request as file, then
+            # as directory, then fall back to index.php
+            try_files $uri $uri/ /index.php?q=$uri&$args;
+        }
+
+        # Redirect server error pages to the static page /50x.html
+        error_page 500 502 503 504 /50x.html;
+        location = /50x.html {
+            root /var/lib/nginx/html;
+        }
+
+        # Pass the PHP scripts to PHP-FPM listening on 127.0.0.1:9000
+        location ~ [^/]\.php(/|$) {
+            fastcgi_split_path_info ^(.+\.php)(/.+)$;
+            fastcgi_pass 127.0.0.1:9000;
+            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
+            fastcgi_param SCRIPT_NAME $fastcgi_script_name;
+            fastcgi_param PATH_INFO $fastcgi_path_info;
+            fastcgi_index index.php;
+            include fastcgi_params;
+        }
+
+        location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
+            expires 5d;
+        }
+
+        # Deny access to . files, for security
+        location ~ /\. {
+            log_not_found off;
+            deny all;
+        }
+
+        # Allow fpm ping and status from localhost
+        location ~ ^/(fpm-status|fpm-ping)$ {
+            access_log off;
+            allow 127.0.0.1;
+            deny all;
+            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
+            include fastcgi_params;
+            fastcgi_pass 127.0.0.1:9000;
+        }
+    }
+
+    # Include other server configs
+    include /etc/nginx/conf.d/*.conf;
+
+    gzip on;
+    gzip_proxied any;
+    gzip_types text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/json application/xml+rss;
+    gzip_vary on;
+    gzip_disable "msie6";
+
+}

+ 14 - 0
rootfs/etc/php81/conf.d/custom.ini

@@ -0,0 +1,14 @@
+[Date]
+date.timezone="UTC"
+
+allow_url_fopen = $allow_url_fopen
+allow_url_include= $allow_url_include
+display_errors= $display_errors
+file_uploads= $file_uploads
+max_execution_time= $max_execution_time
+max_input_time= $max_input_time
+max_input_vars= $max_input_vars
+memory_limit= $memory_limit
+post_max_size= $post_max_size
+upload_max_filesize= $upload_max_filesize
+zlib.output_compression= $zlib.output_compression

+ 56 - 0
rootfs/etc/php81/php-fpm.d/www.conf

@@ -0,0 +1,56 @@
+[global]
+; Log to stderr
+error_log = /dev/stderr
+
+[www]
+; The address on which to accept FastCGI requests.
+; Valid syntaxes are:
+;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
+;                            a specific port;
+;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
+;                            a specific port;
+;   'port'                 - to listen on a TCP socket to all addresses
+;                            (IPv6 and IPv4-mapped) on a specific port;
+;   '/path/to/unix/socket' - to listen on a unix socket.
+; Note: This value is mandatory.
+listen = 127.0.0.1:9000
+
+; Enable status page
+pm.status_path = /fpm-status
+
+; Ondemand process manager
+pm = ondemand
+
+; The number of child processes to be created when pm is set to 'static' and the
+; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
+; This value sets the limit on the number of simultaneous requests that will be
+; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
+; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
+; CGI. The below defaults are based on a server without much resources. Don't
+; forget to tweak pm.* to fit your needs.
+; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
+; Note: This value is mandatory.
+pm.max_children = 100
+
+; The number of seconds after which an idle process will be killed.
+; Note: Used only when pm is set to 'ondemand'
+; Default Value: 10s
+pm.process_idle_timeout = 10s;
+
+; The number of requests each child process should execute before respawning.
+; This can be useful to work around memory leaks in 3rd party libraries. For
+; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
+; Default Value: 0
+pm.max_requests = 1000
+
+; Make sure the FPM workers can reach the environment variables for configuration
+clear_env = $clear_env
+
+; Catch output from PHP
+catch_workers_output = yes
+
+; Remove the 'child 10 said into stderr' prefix in the log and only show the actual message
+decorate_workers_output = no
+
+; Enable ping page to use in healthcheck
+ping.path = /fpm-ping

+ 10 - 0
rootfs/etc/service/nginx/run

@@ -0,0 +1,10 @@
+#!/bin/sh -e
+
+# Replace ENV vars in configuration files
+tmpfile=$(mktemp)
+cat /etc/nginx/nginx.conf | envsubst "$(env | cut -d= -f1 | sed -e 's/^/$/')" | tee "$tmpfile" > /dev/null
+mv "$tmpfile" /etc/nginx/nginx.conf
+
+# pipe stderr to stdout and run nginx omiting ENV vars to avoid security leaks
+exec 2>&1
+exec env - PATH=$PATH nginx -g 'daemon off;'

+ 14 - 0
rootfs/etc/service/php/run

@@ -0,0 +1,14 @@
+#!/bin/sh -e
+
+# Replace ENV vars in configuration files
+tmpfile=$(mktemp)
+cat /etc/php81/conf.d/custom.ini | envsubst "$(env | cut -d= -f1 | sed -e 's/^/$/')" | tee "$tmpfile" > /dev/null
+mv "$tmpfile" /etc/php81/conf.d/custom.ini
+
+tmpfile=$(mktemp)
+cat /etc/php81/php-fpm.d/www.conf | envsubst "$(env | cut -d= -f1 | sed -e 's/^/$/')" | tee "$tmpfile" > /dev/null
+mv "$tmpfile" /etc/php81/php-fpm.d/www.conf
+
+# pipe stderr to stdout and run php-fpm
+exec 2>&1
+exec php-fpm81 -F

+ 2 - 0
rootfs/var/www/html/index.php

@@ -0,0 +1,2 @@
+<?php
+phpinfo();

+ 1 - 0
rootfs/var/www/html/test.html

@@ -0,0 +1 @@
+This static HTML file is served by Nginx

+ 3 - 0
run_tests.sh

@@ -0,0 +1,3 @@
+#!/usr/bin/env sh
+apk --no-cache add curl
+curl --silent --fail http://app:8080 | grep 'PHP 8.1'