diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..06b8406 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: + # Maintain dependencies for GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + # Maintain dependencies for GitHub Actions + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c22b5b8..4e8f414 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,22 +1,55 @@ name: Build docker php-fpm-composer on: - # schedule: - # - cron: "0 13 * * 1" # run on every monday + schedule: + - cron: "0 2 1 * *" # At 02:00 on day-of-month 1. push: branches: - main -concurrency: +concurrency: group: ${{ github.ref }} cancel-in-progress: true +env: + IMAGE_NAME: haipham22/nginx-php-fpm + jobs: + prepare: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + - name: Build docker images + uses: docker/build-push-action@v3 + with: + context: . + file: Dockerfile + cache-from: ${{ env.IMAGE_NAME }}:8.1-fpm + platforms: linux/amd64 + tags: |- + ${{ env.IMAGE_NAME }}:latest + build-args: PHP_FPM_VERSION=8.1-fpm-alpine + buildx: + needs: prepare strategy: matrix: - dockerfiles: ["7.3", "7.4", "8.0", "8.1"] - use-debug: [1, 0] + php-version: + [ + "7.3-fpm-alpine", + "7.4-fpm-alpine", + "8.0-fpm-alpine", + "8.1-fpm-alpine", + "8.2-fpm-alpine", + ] runs-on: ubuntu-latest steps: - name: Checkout @@ -35,25 +68,14 @@ jobs: password: ${{ secrets.DOCKER_PASSWORD }} - name: Build and push - if: ${{ matrix.use-debug == 0 }} uses: docker/build-push-action@v3 with: context: . - file: Dockerfile-alpine + file: Dockerfile platforms: linux/amd64,linux/arm64 pull: true push: true - tags: ${{ secrets.DOCKER_USERNAME }}/php-fpm-composer:${{ matrix.dockerfiles }}-alpine - build-args: PHP_BUILD_VERSION=${{ matrix.dockerfiles }} - - - name: Build and push with xdebug - if: ${{ matrix.use-debug == 1 }} - uses: docker/build-push-action@v3 - with: - context: . - file: Dockerfile-alpine-xdebug - platforms: linux/amd64,linux/arm64 - push: true - pull: true - tags: ${{ secrets.DOCKER_USERNAME }}/php-fpm-composer:${{ matrix.dockerfiles }}-alpine-xdebug - build-args: PHP_BUILD_VERSION=${{ matrix.dockerfiles }} \ No newline at end of file + cache-from: ${{ env.IMAGE_NAME }}:${{ matrix.php-version }} + tags: |- + ${{ env.IMAGE_NAME }}:${{ matrix.php-version }} + build-args: PHP_FPM_VERSION=${{ matrix.php-version }} diff --git a/.gitignore b/.gitignore index 1c2d52b..fd7ce93 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ .idea/* +.env +.env.* \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..2451d6a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,51 @@ +ARG PHP_FPM_VERSION=8.1-fpm-alpine + +FROM php:${PHP_FPM_VERSION} +LABEL Maintainer="Hải Phạm " +LABEL Description="Lightweight container with Nginx 1.24 & PHP based on Alpine Linux." + +# Setup document root +RUN mkdir -p /app + +WORKDIR /app + +# https://github.com/mlocati/docker-php-extension-installer +# Install packages and remove default server definition +COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ + +RUN chmod +x /usr/local/bin/install-php-extensions && \ + sync && \ + install-php-extensions ctype curl dom gd intl mbstring mysqli opcache openssl phar session xml memcached xmlreader && \ + apk add --no-cache curl nginx supervisor && \ + rm -rf /var/cache/apk/* + +# Configure nginx - http +COPY config/nginx.conf /etc/nginx/nginx.conf +# Configure nginx - default server +COPY config/conf.d /etc/nginx/conf.d/ + +# Configure PHP-FPM +COPY config/php-fpm.d/zz-docker.conf /usr/local/etc/php-fpm.d/zz-docker.conf +COPY config/php-fpm.d/fpm-pool.conf /usr/local/etc/php-fpm.d/www.conf +COPY config/php.ini /usr/local/etc/php/conf.d/custom.ini + +# Configure supervisord +COPY config/supervisord.conf /etc/supervisor/conf.d/supervisord.conf + +# Make sure files/folders needed by the processes are accessable when they run under the www-data user +RUN chown -R www-data.www-data /app /run /var/lib/nginx /var/log/nginx + +# Switch to use a non-root user from here on +USER www-data + +# Add application +COPY --chown=www-data src/ /app/ + +# Expose the port nginx is reachable on +EXPOSE 8080 + +# Let supervisord start nginx & php-fpm +CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"] + +# 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 diff --git a/Dockerfile-alpine b/Dockerfile-alpine deleted file mode 100644 index 7b69fb4..0000000 --- a/Dockerfile-alpine +++ /dev/null @@ -1,19 +0,0 @@ -ARG PHP_BUILD_VERSION - -FROM "php:$PHP_BUILD_VERSION-fpm-alpine" - -RUN mkdir -p /app - -# Set working directory -WORKDIR /app - -COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ - -RUN chmod +x /usr/local/bin/install-php-extensions \ - && sync \ - && install-php-extensions @composer gd pdo_mysql mysqli zip exif \ - && rm -rf /var/cache/apk/* - -# Expose port 9000 and start php-fpm server -EXPOSE 9000 -ENTRYPOINT ["php-fpm"] diff --git a/Dockerfile-alpine-xdebug b/Dockerfile-alpine-xdebug deleted file mode 100644 index 52714b1..0000000 --- a/Dockerfile-alpine-xdebug +++ /dev/null @@ -1,19 +0,0 @@ -ARG PHP_BUILD_VERSION - -FROM "php:$PHP_BUILD_VERSION-fpm-alpine" - -RUN mkdir -p /app - -# Set working directory -WORKDIR /app - -COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ - -RUN chmod +x /usr/local/bin/install-php-extensions \ - && sync \ - && install-php-extensions @composer xdebug gd pdo_mysql mysqli zip exif \ - && rm -rf /var/cache/apk/* - -# Expose port 9000 and start php-fpm server -EXPOSE 9000 -ENTRYPOINT ["php-fpm"] diff --git a/README.md b/README.md index 6f939b8..ae16de0 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,112 @@ -# php-fpm-composer +# Docker PHP-FPM & Nginx 1.24 on Alpine Linux +## Usage +Start the Docker container: -## Getting started +```shell +docker run -p 80:8080 haipham22/nginx-php-fpm +``` -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +See the PHP info on http://localhost, or the static html page on http://localhost/test.html -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +Or mount your own code to be served by PHP-FPM & Nginx -## Add your files +```shell +docker run -p 80:8080 -v ~/sourcecode:/app haipham22/nginx-php-fpm +``` -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +## Use in local development -``` -cd existing_repo -git remote add origin https://gitlab.com/haipham22/php-fpm-composer.git -git branch -M main -git push -uf origin main -``` +PHP configuration `custom.ini` + +```ini +[Date] +date.timezone="UTC" +expose_php= Off -## Integrate with your tools +[Opcache] +opcache.enable=0 +opcache.memory_consumption=64 +opcache.interned_strings_buffer=64 +opcache.max_accelerated_files=32531 +opcache.validate_timestamps=0 +opcache.save_comments=1 +opcache.fast_shutdown=0 +``` -- [ ] [Set up project integrations](https://gitlab.com/haipham22/php-fpm-composer/-/settings/integrations) +Run with docker -## Collaborate with your team +```shell +docker run -v "`pwd`/custom.ini:/usr/local/etc/php/conf.d/custom.ini" haipham22/nginx-php-fpm +``` -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) +Run with docker compose -## Test and Deploy +```yaml +version: "3" -Use the built-in continuous integration in GitLab. +services: + app: + build: . + image: haipham22/nginx-php-fpm + volumes: + - ./custom.ini:/usr/local/etc/php/conf.d/custom.ini + - ./:/app + ports: + - "8080:8080" +``` -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) +## Adding composer -*** +If you need [Composer](https://getcomposer.org/) in your project, here's an easy way to add it. -# Editing this README +```Dockerfile +FROM haipham22/nginx-php-fpm:latest -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. +# Install composer via install-php-extensions +RUN install-php-extensions composer -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +# Run composer install to install the dependencies +RUN composer install --optimize-autoloader --no-interaction --no-progress +``` -## Name -Choose a self-explaining name for your project. +## Configuration -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +In [config/](config/) 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; -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +Nginx configuration: -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. +```shell +docker run -v "`pwd`/nginx-server.conf:/etc/nginx/conf.d/server.conf" haipham22/nginx-php-fpm +``` -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. +PHP configuration: -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. +```shell +docker run -v "`pwd`/php-setting.ini:/usr/local/etc/php/conf.d/settings.ini" haipham22/nginx-php-fpm +``` -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +PHP-FPM configuration: -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +```shell +docker run -v "`pwd`/php-fpm-settings.conf:/usr/local/etc/php-fpm.d/server.conf" haipham22/nginx-php-fpm +``` -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +## TODO -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +- [x] Add nginx inside docker +- [x] Change `fastcgi_pass` to `unix` socket instead `TCP` socket +- [ ] Optimize docker image size +- [ ] Add defaults 5xx page html +- [ ] Testing for running -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +## Acknowledgements -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +This project started as a fork of https://github.com/TrafeX/docker-php-nginx. Thanks TrafeX! -## License -For open source projects, say how it is licensed. +Different with original repo: -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +- Use php:xxx-fpm-alpine as base docker images +- Use [mlocati/docker-php-extension-installer](https://github.com/mlocati/docker-php-extension-installer) to easy switch php versions ex 7.3, 7.4, 8.0,... diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..fda150e --- /dev/null +++ b/compose.yml @@ -0,0 +1,14 @@ +version: "3" + +services: + app: + build: . + ports: + - "8080:8080" + sut: + image: alpine:3.13 + depends_on: + - app + command: /tmp/run_tests.sh + volumes: + - "./run_tests.sh:/tmp/run_tests.sh:ro" diff --git a/config/conf.d/default.conf b/config/conf.d/default.conf new file mode 100644 index 0000000..a1e2782 --- /dev/null +++ b/config/conf.d/default.conf @@ -0,0 +1,57 @@ +# Default server definition +server { + listen [::]:8080 default_server; + listen 8080 default_server; + server_name _; + + sendfile off; + tcp_nodelay on; + absolute_redirect off; + + root /app; + 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 php-fpm.sock + location ~ \.php$ { + try_files $uri =404; + 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_index index.php; + include fastcgi_params; + } + + # Set the cache-control headers on assets to cache for 5 days + 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; + } +} diff --git a/config/nginx.conf b/config/nginx.conf new file mode 100644 index 0000000..ba8d09a --- /dev/null +++ b/config/nginx.conf @@ -0,0 +1,45 @@ +worker_processes auto; +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; + + # Hardening + proxy_hide_header X-Powered-By; + fastcgi_hide_header X-Powered-By; + server_tokens off; + + # Enable gzip compression by default + 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"; + + # Include server configs + include /etc/nginx/conf.d/*.conf; +} diff --git a/config/php-fpm.d/fpm-pool.conf b/config/php-fpm.d/fpm-pool.conf new file mode 100644 index 0000000..3690068 --- /dev/null +++ b/config/php-fpm.d/fpm-pool.conf @@ -0,0 +1,63 @@ +[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. +user = www-data +group = www-data + +listen = /run/php-fpm.sock + +;listen.owner = www-data +;listen.group = www-data +;listen.mode = 0666 + +; 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 = no + +; 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 diff --git a/config/php-fpm.d/zz-docker.conf b/config/php-fpm.d/zz-docker.conf new file mode 100644 index 0000000..c50c360 --- /dev/null +++ b/config/php-fpm.d/zz-docker.conf @@ -0,0 +1,2 @@ +[global] +daemonize = no diff --git a/config/php.ini b/config/php.ini new file mode 100644 index 0000000..6270435 --- /dev/null +++ b/config/php.ini @@ -0,0 +1,13 @@ +[Date] +date.timezone="UTC" +expose_php= Off + +; https://www.php.net/manual/en/opcache.configuration.php#ini.opcache.max-accelerated-files +[Opcache] +opcache.enable=1 +opcache.memory_consumption=64 +opcache.interned_strings_buffer=64 +opcache.max_accelerated_files=32531 +opcache.validate_timestamps=0 +opcache.save_comments=1 +opcache.fast_shutdown=0 diff --git a/config/supervisord.conf b/config/supervisord.conf new file mode 100644 index 0000000..bb2c8bf --- /dev/null +++ b/config/supervisord.conf @@ -0,0 +1,23 @@ +[supervisord] +nodaemon=true +logfile=/dev/null +logfile_maxbytes=0 +pidfile=/run/supervisord.pid + +[program:php-fpm] +command=php-fpm -F +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 +autorestart=false +startretries=0 + +[program:nginx] +command=nginx -g 'daemon off;' +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 +autorestart=false +startretries=0 diff --git a/run_tests.sh b/run_tests.sh new file mode 100755 index 0000000..39689fe --- /dev/null +++ b/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' diff --git a/src/index.php b/src/index.php new file mode 100644 index 0000000..83f1549 --- /dev/null +++ b/src/index.php @@ -0,0 +1,3 @@ +