init php7

This commit is contained in:
holzi1005 2024-12-03 15:40:44 +01:00
parent 9d099439da
commit 0f4f8f40c4
14 changed files with 564 additions and 5 deletions

98
Dockerfile Normal file
View file

@ -0,0 +1,98 @@
ARG ARCH=
FROM ${ARCH}alpine:3.13
LABEL Maintainer="Ernesto Serrano <info@ernesto.es>" \
Description="Lightweight container with Nginx & PHP-FPM based on Alpine Linux."
# Install packages
RUN apk --no-cache add \
php7 \
php7-ctype \
php7-curl \
php7-dom \
php7-exif \
php7-fileinfo \
php7-fpm \
php7-gd \
php7-iconv \
php7-intl \
php7-json \
php7-mbstring \
php7-mysqli \
php7-opcache \
php7-openssl \
php7-pecl-apcu \
php7-pdo \
php7-pdo_mysql \
php7-pgsql \
php7-phar \
php7-session \
php7-simplexml \
php7-soap \
php7-sodium \
php7-tokenizer \
php7-xml \
php7-xmlreader \
php7-zip \
php7-zlib \
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/conf.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 nginx_root_directory=/var/www/html \
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 \
date_timezone=UTC

20
LICENSE
View file

@ -1,9 +1,21 @@
MIT License MIT License
Copyright (c) 2024 Public-System-Design Copyright (c) 2021 Ernesto Serrano
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: 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 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. 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.

152
README.md
View file

@ -1,2 +1,152 @@
# alpine-php7-webserver
# Docker PHP-FPM 7.4 & Nginx 1.18 on Alpine Linux
Example PHP-FPM 7.4 & Nginx 1.18 setup for Docker, build on [Alpine Linux](https://www.alpinelinux.org/).
The image is only +/- 25MB large.
Repository: https://github.com/erseco/alpine-php7-webserver
* Built on the lightweight and secure Alpine Linux distribution
* Very small Docker image size (+/-25MB)
* Uses PHP 7.4 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
* Also availabe in Apache flavour: `erseco/alpine-php7-webserver:apache`
[![Docker Pulls](https://img.shields.io/docker/pulls/erseco/alpine-php7-webserver.svg)](https://hub.docker.com/r/erseco/alpine-php7-webserver/)
[![Docker image layers](https://images.microbadger.com/badges/image/erseco/alpine-php7-webserver.svg)](https://microbadger.com/images/erseco/alpine-php7-webserver)
![nginx 1.18.0](https://img.shields.io/badge/nginx-1.18-brightgreen.svg)
![php 7.4](https://img.shields.io/badge/php-7.4-brightgreen.svg)
![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)
## Usage
Start the Docker container:
docker run -p 80:8080 erseco/alpine-php7-webserver
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 erseco/alpine-php7-webserver
## 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" erseco/alpine-php7-webserver
PHP configuration:
docker run -v "`pwd`/php-setting.ini:/etc/php7/conf.d/settings.ini" erseco/alpine-php7-webserver
PHP-FPM configuration:
docker run -v "`pwd`/php-fpm-settings.conf:/etc/php7/php-fpm.d/server.conf" erseco/alpine-php7-webserver
_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. |
| PHP7 | 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. |
| PHP7 | 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. |
| PHP7 | allow_url_include | Off | Allow the use of URL-aware fopen wrappers with the following functions: include(), include_once(), require(), require_once(). |
| PHP7 | 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. |
| PHP7 | file_uploads | On | Whether or not to allow HTTP file uploads. |
| PHP7 | 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. |
| PHP7 | max_input_time | -1 | Maximum time in seconds a script is allowed to parse input data, like POST, GET and file uploads. |
| PHP7 | 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. |
| PHP7 | 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. |
| PHP7 | 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. |
| PHP7 | upload_max_filesize | 2M | Maximum size of an uploaded file. |
| PHP7 | 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 erseco/alpine-php7-webserver: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 trafex/alpine-nginx-php7
COPY --chown=nginx --from=composer /app /var/www/html
```

11
docker-compose.test.yml Normal file
View file

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

76
rootfs/bin/docker-entrypoint.sh Executable file
View file

@ -0,0 +1,76 @@
#!/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
}
# Replace ENV vars in nginx 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
# Replace ENV vars in php configuration files
tmpfile=$(mktemp)
cat /etc/php7/conf.d/custom.ini | envsubst "$(env | cut -d= -f1 | sed -e 's/^/$/')" | tee "$tmpfile" > /dev/null
mv "$tmpfile" /etc/php7/conf.d/custom.ini
tmpfile=$(mktemp)
cat /etc/php7/php-fpm.d/www.conf | envsubst "$(env | cut -d= -f1 | sed -e 's/^/$/')" | tee "$tmpfile" > /dev/null
mv "$tmpfile" /etc/php7/php-fpm.d/www.conf
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
# If there are additional arguments, execute them
if [ $# -gt 0 ]; then
exec "$@"
fi
# catch shutdown signals
trap shutdown SIGTERM SIGHUP SIGQUIT SIGINT
wait $RUNSVDIR
shutdown

View file

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

122
rootfs/etc/nginx/nginx.conf Normal file
View file

@ -0,0 +1,122 @@
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;
# Set the forwarded_scheme variable based on the X-Forwarded-Proto header
# This is used to maintain the original protocol used by the client
# This is important when behind a reverse proxy that handles SSL termination
set $forwarded_scheme "http";
if ($http_x_forwarded_proto = "https") {
set $forwarded_scheme "https";
}
# 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 ${nginx_root_directory};
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 socket
location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php-fpm.sock;
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;
# Pass the original forwarded_scheme and HTTPS status to the PHP backend
fastcgi_param HTTP_X_FORWARDED_PROTO $forwarded_scheme;
fastcgi_param HTTPS $https if_not_empty;
}
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 unix:/run/php-fpm.sock;
}
# Include additional server-specific configurations
include /etc/nginx/server-conf.d/*.conf;
}
# Include other server configs
include /etc/nginx/conf.d/*.conf;
gzip on;
gzip_proxied any;
# Based on CloudFlare's recommended settings https://developers.cloudflare.com/speed/optimization/content/brotli/content-compression/
gzip_types text/richtext text/plain text/css text/x-script text/x-component text/x-java-source text/x-markdown application/javascript application/x-javascript text/javascript text/js image/x-icon image/vnd.microsoft.icon application/x-perl application/x-httpd-cgi text/xml application/xml application/rss+xml application/vnd.api+json application/x-protobuf application/json multipart/bag multipart/mixed application/xhtml+xml font/ttf font/otf font/x-woff image/svg+xml application/vnd.ms-fontobject application/ttf application/x-ttf application/otf application/x-otf application/truetype application/opentype application/x-opentype application/font-woff application/eot application/font application/font-sfnt application/wasm application/javascript-binast application/manifest+json application/ld+json application/graphql+json application/geo+json;
gzip_vary on;
gzip_disable "msie6";
}

View file

@ -0,0 +1,15 @@
[Date]
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
date.timezone= "$date_timezone"

View file

@ -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

5
rootfs/etc/service/nginx/run Executable file
View file

@ -0,0 +1,5 @@
#!/bin/sh -e
# 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;'

5
rootfs/etc/service/php/run Executable file
View file

@ -0,0 +1,5 @@
#!/bin/sh -e
# pipe stderr to stdout and run php-fpm
exec 2>&1
exec php-fpm7 -F

View file

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

View file

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

3
run_tests.sh Executable file
View file

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